instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public String format(LogRecord record) {
Date date = new Date(record.getMillis());
String source = record.getLoggerName();
String loggerName = record.getLoggerName();
String level = record.getLevel().getLocalizedName();
String message = formatMessage(record);
String throwable = getThrowable(record);
String thread = getThreadName();
String pid = this.pid;
return String.format(this.format, date, source, loggerName, level, message, throwable, thread, pid);
}
private String getThrowable(LogRecord record) {
if (record.getThrown() == null) {
return "";
}
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
printWriter.println();
record.getThrown().printStackTrace(printWriter);
printWriter.close();
return stringWriter.toString();
|
}
private String getThreadName() {
String name = Thread.currentThread().getName();
return (name != null) ? name : "";
}
private static String getOrUseDefault(String key, String defaultValue) {
String value = null;
try {
value = System.getenv(key);
}
catch (Exception ex) {
// ignore
}
if (value == null) {
value = defaultValue;
}
return System.getProperty(key, value);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\java\SimpleFormatter.java
| 1
|
请完成以下Java代码
|
private Environment openEnvironmentExclusively() {
return Environments.newInstance(DB_PATH);
}
public String findOne(String taskId) {
try (Environment environment = openEnvironmentExclusively()) {
Transaction readonlyTransaction = environment.beginReadonlyTransaction();
try {
Store taskStore = environment.openStore(TASK_STORE,
StoreConfig.WITHOUT_DUPLICATES, readonlyTransaction);
ArrayByteIterable id = StringBinding.stringToEntry(taskId);
ByteIterable result = taskStore.get(readonlyTransaction, id);
return result == null ? null : StringBinding.entryToString(result);
} finally {
readonlyTransaction.abort();
}
}
}
public Map<String, String> findAll() {
try (Environment environment = openEnvironmentExclusively()) {
Transaction readonlyTransaction = environment.beginReadonlyTransaction();
try {
Store taskStore = environment.openStore(TASK_STORE,
StoreConfig.WITHOUT_DUPLICATES, readonlyTransaction);
Map<String, String> result = new HashMap<>();
try (Cursor cursor = taskStore.openCursor(readonlyTransaction)) {
while (cursor.getNext()) {
result.put(StringBinding.entryToString(cursor.getKey()),
StringBinding.entryToString(cursor.getValue()));
}
}
return result;
} finally {
readonlyTransaction.abort();
}
|
}
}
public void deleteAll() {
try (Environment environment = openEnvironmentExclusively()) {
Transaction exclusiveTransaction = environment.beginExclusiveTransaction();
try {
Store taskStore = environment.openStore(TASK_STORE,
StoreConfig.WITHOUT_DUPLICATES, exclusiveTransaction);
try (Cursor cursor = taskStore.openCursor(exclusiveTransaction)) {
while (cursor.getNext()) {
taskStore.delete(exclusiveTransaction, cursor.getKey());
}
}
} finally {
exclusiveTransaction.commit();
}
}
}
}
|
repos\tutorials-master\persistence-modules\persistence-libraries\src\main\java\com\baeldung\jetbrainsxodus\TaskEnvironmentRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public X509Certificate[] getAcceptedIssuers() { return null; }
};
SSLContext sslContext = SSLContext.getInstance("TLS");
trustManagers = new TrustManager[]{ trustAll };
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) { return true; }
};
} else if (sslCaCert != null) {
char[] password = null; // Any password will work.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
KeyStore caKeyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = "ca" + Integer.toString(index++);
caKeyStore.setCertificateEntry(certificateAlias, certificate);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(caKeyStore);
trustManagers = trustManagerFactory.getTrustManagers();
|
}
if (keyManagers != null || trustManagers != null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
httpClient.setSslSocketFactory(sslContext.getSocketFactory());
} else {
httpClient.setSslSocketFactory(null);
}
httpClient.setHostnameVerifier(hostnameVerifier);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, password);
return keyStore;
} catch (IOException e) {
throw new AssertionError(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\ApiClient.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the passportNumber property.
*
* @return
* possible object is
* {@link String }
|
*
*/
public String getPassportNumber() {
return passportNumber;
}
/**
* Sets the value of the passportNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPassportNumber(String value) {
this.passportNumber = value;
}
}
|
repos\spring-boot-examples-master\spring-boot-tutorial-soap-web-services\src\main\java\com\in28minutes\students\StudentDetails.java
| 2
|
请完成以下Java代码
|
protected final DataSource getDataSource() {
return this.dataSource;
}
@Override
protected boolean isEmbeddedDatabase() {
try {
return EmbeddedDatabaseConnection.isEmbedded(this.dataSource);
}
catch (Exception ex) {
logger.debug("Could not determine if datasource is embedded", ex);
return false;
}
}
@Override
protected void runScripts(Scripts scripts) {
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.setContinueOnError(scripts.isContinueOnError());
populator.setSeparator(scripts.getSeparator());
if (scripts.getEncoding() != null) {
populator.setSqlScriptEncoding(scripts.getEncoding().name());
}
for (Resource resource : scripts) {
|
populator.addScript(resource);
}
customize(populator);
DatabasePopulatorUtils.execute(populator, this.dataSource);
}
/**
* Customize the {@link ResourceDatabasePopulator}.
* @param populator the configured database populator
* @since 2.6.2
*/
protected void customize(ResourceDatabasePopulator populator) {
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\init\DataSourceScriptDatabaseInitializer.java
| 1
|
请完成以下Java代码
|
public boolean isWeighted()
{
return true;
}
@Override
public boolean isWeightable()
{
return true;
}
@Override
public boolean hasWeightTareAdjust()
{
return true;
}
@Override
public boolean hasWeightTare()
{
return true;
}
@Override
public boolean hasWeightNet()
{
return true;
}
@Override
public boolean hasWeightGross()
{
return true;
}
@Override
public AttributeCode getWeightTareAdjustAttribute()
{
return Weightables.ATTR_WeightTareAdjust;
}
@Override
public BigDecimal getWeightTareAdjust()
{
return weightTareAdjust;
}
@Override
public void setWeightTareAdjust(BigDecimal weightTareAdjust)
{
this.weightTareAdjust = weightTareAdjust;
}
@Override
public AttributeCode getWeightTareAttribute()
{
return Weightables.ATTR_WeightTare;
}
@Override
public BigDecimal getWeightTareInitial()
{
return weightTareInitial;
}
@Override
public BigDecimal getWeightTare()
{
return weightTare;
}
@Override
public AttributeCode getWeightNetAttribute()
{
return Weightables.ATTR_WeightNet;
}
@Override
public void setWeightNetNoPropagate(final BigDecimal weightNet)
{
this.weightNet = weightNet;
}
@Override
public void setWeightNet(final BigDecimal weightNet)
{
setWeightNetNoPropagate(weightNet);
}
@Override
public BigDecimal getWeightNetOrNull()
{
return getWeightNet();
}
@Override
public BigDecimal getWeightNet()
{
return weightNet;
}
@Override
public I_C_UOM getWeightNetUOM()
|
{
return uom;
}
@Override
public AttributeCode getWeightGrossAttribute()
{
return Weightables.ATTR_WeightGross;
}
@Override
public void setWeightGross(final BigDecimal weightGross)
{
this.weightGross = weightGross;
}
@Override
public BigDecimal getWeightGross()
{
return weightGross;
}
@Override
public Quantity getWeightGrossAsQuantity()
{
return Quantity.of(weightGross, uom);
}
@Override
public boolean isWeightTareAdjustAttribute(final AttributeCode attribute)
{
return AttributeCode.equals(attribute, Weightables.ATTR_WeightTareAdjust);
}
@Override
public boolean isWeightTareAttribute(final AttributeCode attribute)
{
return AttributeCode.equals(attribute, Weightables.ATTR_WeightTare);
}
@Override
public boolean isWeightNetAttribute(final AttributeCode attribute)
{
return AttributeCode.equals(attribute, Weightables.ATTR_WeightNet);
}
@Override
public boolean isWeightGrossAttribute(final AttributeCode attribute)
{
return AttributeCode.equals(attribute, Weightables.ATTR_WeightGross);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\PlainWeightable.java
| 1
|
请完成以下Java代码
|
public class ActionFactory implements ActionType
{
/**
* 不建立依存关系,只转移句法分析的焦点,即新的左焦点词是原来的右焦点词,依此类推。
* @return
*/
public static Action make_shift()
{
return new Action(kShift, 0);
}
/**
* 建立右焦点词依存于左焦点词的依存关系
* @param rel 依存关系
* @return
|
*/
public static Action make_left_arc(final int rel)
{
return new Action(kLeftArc, rel);
}
/**
* 建立左焦点词依存于右焦点词的依存关系
* @param rel 依存关系
* @return
*/
public static Action make_right_arc(final int rel)
{
return new Action(kRightArc, rel);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\action\ActionFactory.java
| 1
|
请完成以下Java代码
|
public TimerEntity createTimerInstance(ExecutionEntity execution) {
return createTimer(execution);
}
public TimerEntity createStartTimerInstance(String deploymentId) {
return createTimer(deploymentId);
}
public TimerEntity createTimer(String deploymentId) {
TimerEntity timer = super.createJobInstance((ExecutionEntity) null);
timer.setDeploymentId(deploymentId);
scheduleTimer(timer);
return timer;
}
public TimerEntity createTimer(ExecutionEntity execution) {
TimerEntity timer = super.createJobInstance(execution);
scheduleTimer(timer);
return timer;
}
protected void scheduleTimer(TimerEntity timer) {
Context
.getCommandContext()
.getJobManager()
.schedule(timer);
}
protected ExecutionEntity resolveExecution(ExecutionEntity context) {
return context;
}
@Override
protected JobHandlerConfiguration resolveJobHandlerConfiguration(ExecutionEntity context) {
return resolveJobHandler().newConfiguration(rawJobHandlerConfiguration);
}
/**
* @return all timers declared in the given scope
*/
public static Map<String, TimerDeclarationImpl> getDeclarationsForScope(PvmScope scope) {
if (scope == null) {
return Collections.emptyMap();
|
}
Map<String, TimerDeclarationImpl> result = scope.getProperties().get(BpmnProperties.TIMER_DECLARATIONS);
if (result != null) {
return result;
}
else {
return Collections.emptyMap();
}
}
/**
* @return all timeout listeners declared in the given scope
*/
public static Map<String, Map<String, TimerDeclarationImpl>> getTimeoutListenerDeclarationsForScope(PvmScope scope) {
if (scope == null) {
return Collections.emptyMap();
}
Map<String, Map<String, TimerDeclarationImpl>> result = scope.getProperties().get(BpmnProperties.TIMEOUT_LISTENER_DECLARATIONS);
if (result != null) {
return result;
}
else {
return Collections.emptyMap();
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerDeclarationImpl.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstLetter() {
return firstLetter;
}
public void setFirstLetter(String firstLetter) {
this.firstLetter = firstLetter;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getFactoryStatus() {
return factoryStatus;
}
public void setFactoryStatus(Integer factoryStatus) {
this.factoryStatus = factoryStatus;
}
public Integer getShowStatus() {
return showStatus;
}
|
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getBigPic() {
return bigPic;
}
public void setBigPic(String bigPic) {
this.bigPic = bigPic;
}
public String getBrandStory() {
return brandStory;
}
public void setBrandStory(String brandStory) {
this.brandStory = brandStory;
}
}
|
repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\dto\PmsBrandDto.java
| 1
|
请完成以下Java代码
|
private Mono<Jwt> resolveJwtAssertion(OAuth2AuthorizationContext context) {
// @formatter:off
return Mono.just(context)
.map((ctx) -> ctx.getPrincipal().getPrincipal())
.filter((principal) -> principal instanceof Jwt)
.cast(Jwt.class);
// @formatter:on
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code jwt-bearer} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code jwt-bearer} grant
*/
public void setAccessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the resolver used for resolving the {@link Jwt} assertion.
* @param jwtAssertionResolver the resolver used for resolving the {@link Jwt}
* assertion
* @since 5.7
*/
public void setJwtAssertionResolver(Function<OAuth2AuthorizationContext, Mono<Jwt>> jwtAssertionResolver) {
Assert.notNull(jwtAssertionResolver, "jwtAssertionResolver cannot be null");
this.jwtAssertionResolver = jwtAssertionResolver;
}
/**
|
* Sets the maximum acceptable clock skew, which is used when checking the
* {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\JwtBearerReactiveOAuth2AuthorizedClientProvider.java
| 1
|
请完成以下Java代码
|
public class ConversionHelper {
protected DmnDefinition dmnDefinition;
protected Decision currentDecision;
protected DmnDiDiagram currentDiDiagram;
protected DmnDiShape currentDiShape;
protected DiEdge currentDiEdge;
protected List<DmnDiDiagram> diDiagrams = new ArrayList<>();
protected Map<String, List<DmnDiShape>> diShapes = new LinkedHashMap<>();
protected Map<String, List<DmnDiEdge>> diEdges = new LinkedHashMap<>();
public DmnDefinition getDmnDefinition() {
return dmnDefinition;
}
public void setDmnDefinition(DmnDefinition dmnDefinition) {
this.dmnDefinition = dmnDefinition;
}
public Decision getCurrentDecision() {
return currentDecision;
}
public void setCurrentDecision(Decision currentDecision) {
this.currentDecision = currentDecision;
}
public void addDiDiagram(DmnDiDiagram diDiagram) {
diDiagrams.add(diDiagram);
setCurrentDiDiagram(diDiagram);
}
public void addDiShape(DmnDiShape diShape) {
diShapes.computeIfAbsent(getCurrentDiDiagram().getId(), k -> new ArrayList<>());
diShapes.get(getCurrentDiDiagram().getId()).add(diShape);
setCurrentDiShape(diShape);
}
public void addDiEdge(DmnDiEdge diEdge) {
diEdges.computeIfAbsent(getCurrentDiDiagram().getId(), k -> new ArrayList<>());
diEdges.get(getCurrentDiDiagram().getId()).add(diEdge);
setCurrentDiEdge(diEdge);
}
public DmnDiDiagram getCurrentDiDiagram() {
return currentDiDiagram;
|
}
public void setCurrentDiDiagram(DmnDiDiagram currentDiDiagram) {
this.currentDiDiagram = currentDiDiagram;
}
public DmnDiShape getCurrentDiShape() {
return currentDiShape;
}
public void setCurrentDiShape(DmnDiShape currentDiShape) {
this.currentDiShape = currentDiShape;
}
public DiEdge getCurrentDiEdge() {
return currentDiEdge;
}
public void setCurrentDiEdge(DiEdge currentDiEdge) {
this.currentDiEdge = currentDiEdge;
}
public List<DmnDiDiagram> getDiDiagrams() {
return diDiagrams;
}
public List<DmnDiShape> getDiShapes(String diagramId) {
return diShapes.get(diagramId);
}
public List<DmnDiEdge> getDiEdges(String diagramId) {
return diEdges.get(diagramId);
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\ConversionHelper.java
| 1
|
请完成以下Java代码
|
public void evaluate (final DataStatusEvent e)
{
boolean process = e == null;
String columnName = null;
if (!process)
{
columnName = e.getColumnName();
if (columnName != null)
process = m_dependents.contains(columnName);
else
process = true;
}
if (process)
{
for (int i = 0; i < components.size(); i++)
{
Component c = components.get(i);
if (c instanceof GridController)
|
{
GridController gc = (GridController)c;
if (!gc.isDetailGrid()) //ignore included tabs
{
boolean display = isDisplay(gc);
if ( display )
showTab(tabNames.get(i));
else
hideTab(tabNames.get(i));
}
}
}
}
} // evaluate
} // VTabbdPane
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\VTabbedPane.java
| 1
|
请完成以下Java代码
|
public ClientRegistrationRepository clientRegistrationRepository() {
List<ClientRegistration> registrations = clients.stream()
.map(c -> getRegistration(c))
.filter(registration -> registration != null)
.collect(Collectors.toList());
return new InMemoryClientRegistrationRepository(registrations);
}
// @Bean
public OAuth2AuthorizedClientService authorizedClientService() {
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository());
}
private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";
@Autowired
private Environment env;
private ClientRegistration getRegistration(String client) {
String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
|
if (clientId == null) {
return null;
}
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
if (client.equals("google")) {
return CommonOAuth2Provider.GOOGLE.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
if (client.equals("facebook")) {
return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
return null;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2\SecurityConfig.java
| 1
|
请完成以下Java代码
|
public void setAD_ImpFormat_ID (final int AD_ImpFormat_ID)
{
if (AD_ImpFormat_ID < 1)
set_Value (COLUMNNAME_AD_ImpFormat_ID, null);
else
set_Value (COLUMNNAME_AD_ImpFormat_ID, AD_ImpFormat_ID);
}
@Override
public int getAD_ImpFormat_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_ImpFormat_ID);
}
@Override
public void setC_DataImport_ID (final int C_DataImport_ID)
{
if (C_DataImport_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, C_DataImport_ID);
}
@Override
public int getC_DataImport_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DataImport_ID);
}
/**
* DataImport_ConfigType AD_Reference_ID=541535
* Reference name: C_DataImport_ConfigType
|
*/
public static final int DATAIMPORT_CONFIGTYPE_AD_Reference_ID=541535;
/** Standard = S */
public static final String DATAIMPORT_CONFIGTYPE_Standard = "S";
/** Bank Statement Import = BSI */
public static final String DATAIMPORT_CONFIGTYPE_BankStatementImport = "BSI";
@Override
public void setDataImport_ConfigType (final java.lang.String DataImport_ConfigType)
{
set_Value (COLUMNNAME_DataImport_ConfigType, DataImport_ConfigType);
}
@Override
public java.lang.String getDataImport_ConfigType()
{
return get_ValueAsString(COLUMNNAME_DataImport_ConfigType);
}
@Override
public void setInternalName (final @Nullable java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public java.lang.String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DataImport.java
| 1
|
请完成以下Java代码
|
public ImmutableList<AttachmentListenerSettings> getById(@NonNull final AdTableId adTableId)
{
return cache.getOrLoad(adTableId, this::retrieveAttachmentListenerSettings);
}
/**
* Queries {@link I_AD_Table_AttachmentListener} for listeners linked to the given {@link AdTableId}.
*
* @param adTableId DB identifier of the table.
* @return list of {@link AttachmentListenerSettings} ordered by {@link I_AD_Table_AttachmentListener#getSeqNo()}.
*/
private ImmutableList<AttachmentListenerSettings> retrieveAttachmentListenerSettings(final AdTableId adTableId )
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Table_AttachmentListener.class, Env.getCtx(), ITrx.TRXNAME_None)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_Table_AttachmentListener.COLUMNNAME_AD_Table_ID, adTableId.getRepoId())
|
.orderBy(I_AD_Table_AttachmentListener.COLUMNNAME_SeqNo)
.create()
.list()
.stream()
.map(this::buildAttachmentListenerSettings)
.collect(ImmutableList.toImmutableList());
}
private AttachmentListenerSettings buildAttachmentListenerSettings( final I_AD_Table_AttachmentListener record )
{
return AttachmentListenerSettings.builder()
.isSendNotification(record.isSendNotification())
.listenerJavaClassId(JavaClassId.ofRepoId(record.getAD_JavaClass_ID()))
.adMessageId(AdMessageId.ofRepoIdOrNull(record.getAD_Message_ID()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\listener\TableAttachmentListenerRepository.java
| 1
|
请完成以下Java代码
|
public class ResourceLoadingSecurityFilter extends SecurityFilter implements ResourceLoaderDependingFilter {
private ResourceLoader resourceLoader;
private WebappProperty webappProperty;
@Override
protected void loadFilterRules(FilterConfig filterConfig, String applicationPath) throws ServletException {
String configFileName = filterConfig.getInitParameter("configFile");
Resource resource = resourceLoader.getResource("classpath:" +webappProperty.getWebjarClasspath() + configFileName);
InputStream configFileResource;
try {
configFileResource = resource.getInputStream();
} catch (IOException e1) {
throw new ServletException("Could not read security filter config file '" + configFileName + "': no such resource in servlet context.");
}
try {
filterRules = FilterRules.load(configFileResource, applicationPath);
} catch (Exception e) {
throw new RuntimeException("Exception while parsing '" + configFileName + "'", e);
} finally {
IoUtil.closeSilently(configFileResource);
}
}
/**
* @return the resourceLoader
*/
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
/**
* @param resourceLoader
* the resourceLoader to set
|
*/
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* @return the webappProperty
*/
public WebappProperty getWebappProperty() {
return webappProperty;
}
/**
* @param webappProperty
* webappProperty to set
*/
public void setWebappProperty(WebappProperty webappProperty) {
this.webappProperty = webappProperty;
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\filter\ResourceLoadingSecurityFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Queue accountingQueue()
{
// final NamingStrategy eventQueueNamingStrategy = new Base64UrlNamingStrategy(EVENTBUS_TOPIC.getName() + "." + appName + "-");
// return new AnonymousQueue(eventQueueNamingStrategy);
return new Queue(EVENTBUS_TOPIC.getName(), true);
}
@Bean
public DirectExchange accountingExchange()
{
return new DirectExchange(EXCHANGE_NAME_PREFIX);
}
@Bean
public Binding accountingBinding()
{
return BindingBuilder.bind(accountingQueue())
.to(accountingExchange()).with(EXCHANGE_NAME_PREFIX);
}
@Override
public String getQueueName()
{
|
return accountingQueue().getName();
}
@Override
public Optional<String> getTopicName()
{
return Optional.of(EVENTBUS_TOPIC.getName());
}
@Override
public String getExchangeName()
{
return accountingExchange().getName();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\queues\accounting\AccountingQueueConfiguration.java
| 2
|
请完成以下Java代码
|
public void setResources(Map<String, EventResourceEntity> resources) {
this.resources = resources;
}
@Override
public Date getDeploymentTime() {
return deploymentTime;
}
@Override
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@Override
public boolean isNew() {
return isNew;
|
}
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "EventDeploymentEntity[id=" + id + ", name=" + name + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDeploymentEntityImpl.java
| 1
|
请完成以下Java代码
|
public @Nullable WarehouseTypeId getWarehouseTypeId() {return packageable.getWarehouseTypeId();}
public boolean isPartiallyPickedOrDelivered()
{
return packageable.getQtyPickedPlanned().signum() != 0
|| packageable.getQtyPickedNotDelivered().signum() != 0
|| packageable.getQtyPickedAndDelivered().signum() != 0;
}
public @NonNull ProductId getProductId() {return packageable.getProductId();}
public @NonNull String getProductName() {return packageable.getProductName();}
public @NonNull I_C_UOM getUOM() {return getQtyToDeliver().getUOM();}
public @NonNull Quantity getQtyToDeliver()
{
return schedule != null
? schedule.getQtyToPick()
: packageable.getQtyToDeliver();
}
public @NonNull HUPIItemProductId getPackToHUPIItemProductId() {return packageable.getPackToHUPIItemProductId();}
public @NonNull Quantity getQtyToPick()
|
{
return schedule != null
? schedule.getQtyToPick()
: packageable.getQtyToPick();
}
public @Nullable UomId getCatchWeightUomId() {return packageable.getCatchWeightUomId();}
public @Nullable PPOrderId getPickFromOrderId() {return packageable.getPickFromOrderId();}
public @Nullable ShipperId getShipperId() {return packageable.getShipperId();}
public @NonNull AttributeSetInstanceId getAsiId() {return packageable.getAsiId();}
public Optional<ShipmentAllocationBestBeforePolicy> getBestBeforePolicy() {return packageable.getBestBeforePolicy();}
public @NonNull WarehouseId getWarehouseId() {return packageable.getWarehouseId();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageable.java
| 1
|
请完成以下Java代码
|
public static long numberOfFilesIn_Stream(String path) {
File currentFile = new File(path);
File[] filesOrNull = currentFile.listFiles();
long currentFileNumber = currentFile.isFile() ? 1 : 0;
if (filesOrNull == null) {
return currentFileNumber;
}
return currentFileNumber + Arrays.stream(filesOrNull)
.mapToLong(FindFolder::filesInside)
.sum();
}
private static long filesInside(File it) {
if (it.isFile()) {
return 1;
} else if (it.isDirectory()) {
return numberOfFilesIn_Stream(it.getAbsolutePath());
} else {
return 0;
}
}
public static long numberOfFilesIn_Walk(String path) {
Path dir = Path.of(path);
try (Stream<Path> stream = Files.walk(dir)) {
return stream.parallel()
.map(getFileOrEmpty())
.flatMap(Optional::stream)
.filter(it -> !it.isDirectory())
.count();
|
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static Function<Path, Optional<File>> getFileOrEmpty() {
return it -> {
try {
return Optional.of(it.toFile());
} catch (UnsupportedOperationException e) {
println(e);
return Optional.empty();
}
};
}
public static long numberOfFilesIn_NIO(String path) {
try (Stream<Path> stream = Files.find(
Paths.get(path),
Integer.MAX_VALUE,
(__, attr) -> attr.isRegularFile())
) {
return stream.count();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-23\src\main\java\com\baeldung\javafeatures\FindFolder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ShortType implements VariableType {
public static final String TYPE_NAME = "short";
private static final long serialVersionUID = 1L;
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
if (valueFields.getLongValue() != null) {
return Short.valueOf(valueFields.getLongValue().shortValue());
}
return null;
}
@Override
public void setValue(Object value, ValueFields valueFields) {
|
if (value != null) {
valueFields.setLongValue(((Short) value).longValue());
valueFields.setTextValue(value.toString());
} else {
valueFields.setLongValue(null);
valueFields.setTextValue(null);
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return Short.class.isAssignableFrom(value.getClass()) || short.class.isAssignableFrom(value.getClass());
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\ShortType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* The type of unit. ERPEL recommends the use of code list UN/ECE recommendation 20. Note, that ERPEL supports both representations for piece: PCE and C62. A list of valid codes may be found under https://docs.ecosio.com/files/Measure_Unit_Qualifiers_6411.pdf
*
* @return
* possible object is
* {@link String }
*
*/
public String getUnit() {
|
return unit;
}
/**
* Sets the value of the unit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUnit(String value) {
this.unit = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ConditionalUnitType.java
| 2
|
请完成以下Java代码
|
public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation)
{
set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation);
}
@Override
public void setWorkStation_ID (final int WorkStation_ID)
{
if (WorkStation_ID < 1)
set_Value (COLUMNNAME_WorkStation_ID, null);
else
set_Value (COLUMNNAME_WorkStation_ID, WorkStation_ID);
}
@Override
public int getWorkStation_ID()
{
return get_ValueAsInt(COLUMNNAME_WorkStation_ID);
|
}
@Override
public void setYield (final BigDecimal Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order.java
| 1
|
请完成以下Java代码
|
public int getC_Dunning_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Dunning_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Create levels sequentially.
@param CreateLevelsSequentially
Create Dunning Letter by level sequentially
*/
public void setCreateLevelsSequentially (boolean CreateLevelsSequentially)
{
set_Value (COLUMNNAME_CreateLevelsSequentially, Boolean.valueOf(CreateLevelsSequentially));
}
/** Get Create levels sequentially.
@return Create Dunning Letter by level sequentially
*/
public boolean isCreateLevelsSequentially ()
{
Object oo = get_Value(COLUMNNAME_CreateLevelsSequentially);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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 Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
|
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Send dunning letters.
@param SendDunningLetter
Indicates if dunning letters will be sent
*/
public void setSendDunningLetter (boolean SendDunningLetter)
{
set_Value (COLUMNNAME_SendDunningLetter, Boolean.valueOf(SendDunningLetter));
}
/** Get Send dunning letters.
@return Indicates if dunning letters will be sent
*/
public boolean isSendDunningLetter ()
{
Object oo = get_Value(COLUMNNAME_SendDunningLetter);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Dunning.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
/**
* return the Id of the parent activity instance currently executed by this
* execution
*/
public String getParentActivityInstanceId() {
return parentActivityInstanceId;
}
/**
* Gets the id of the parent of this execution. If null, the execution
* represents a process-instance.
*/
public String getParentId() {
return parentId;
}
/**
* The business key for the process instance this execution is associated
* with.
*/
public String getProcessBusinessKey() {
return processBusinessKey;
}
/**
* The process definition key for the process instance this execution is
* associated with.
*/
public String getProcessDefinitionId() {
return processDefinitionId;
}
/** Reference to the overall process instance */
public String getProcessInstanceId() {
return processInstanceId;
|
}
/**
* Return the id of the tenant this execution belongs to. Can be
* <code>null</code> if the execution belongs to no single tenant.
*/
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventName=" + eventName
+ ", businessKey=" + businessKey
+ ", activityInstanceId=" + activityInstanceId
+ ", currentActivityId=" + currentActivityId
+ ", currentActivityName=" + currentActivityName
+ ", currentTransitionId=" + currentTransitionId
+ ", parentActivityInstanceId=" + parentActivityInstanceId
+ ", parentId=" + parentId
+ ", processBusinessKey=" + processBusinessKey
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\ExecutionEvent.java
| 1
|
请完成以下Java代码
|
public void addReceiptScheduleProducer(final IReceiptScheduleProducer producer)
{
Check.assumeNotNull(producer, "producer not null");
producers.add(producer);
}
private ArrayKey createModelKey(final Object model)
{
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
final int id = InterfaceWrapperHelper.getId(model);
return Util.mkKey(tableName, id);
}
@Override
@Nullable
public List<I_M_ReceiptSchedule> createOrUpdateReceiptSchedules(final Object model, final List<I_M_ReceiptSchedule> previousSchedules)
{
if (!modelAggregateFilter.isEligible(model))
{
return null;
}
final ArrayKey modelKey = createModelKey(model);
//
// Add model to current models that are updated.
// If an update is just running for our model, then we shall skip it because we have to avoid recursions
if (!currentUpdatingModelKeys.get().add(modelKey))
{
return null;
}
final List<I_M_ReceiptSchedule> currentPreviousSchedules = new ArrayList<I_M_ReceiptSchedule>(previousSchedules);
final List<I_M_ReceiptSchedule> currentPreviousSchedulesRO = Collections.unmodifiableList(currentPreviousSchedules);
final List<I_M_ReceiptSchedule> schedules = new ArrayList<I_M_ReceiptSchedule>();
try
{
// Iterate all producers and ask them to create/update
for (final IReceiptScheduleProducer producer : producers)
{
final List<I_M_ReceiptSchedule> currentSchedules = producer.createOrUpdateReceiptSchedules(model, currentPreviousSchedulesRO);
// Collect created/updated receipt schedules
if (currentSchedules != null)
{
|
currentPreviousSchedules.addAll(currentSchedules);
schedules.addAll(currentSchedules);
}
}
}
finally
{
// Remove current model from the list of models that are currently updated
currentUpdatingModelKeys.get().remove(modelKey);
}
return schedules;
}
@Override
public void updateReceiptSchedules(final Object model)
{
for (final IReceiptScheduleProducer producer : producers)
{
producer.updateReceiptSchedules(model);
}
}
@Override
public void inactivateReceiptSchedules(final Object model)
{
for (final IReceiptScheduleProducer producer : producers)
{
producer.inactivateReceiptSchedules(model);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\CompositeReceiptScheduleProducerExecutor.java
| 1
|
请完成以下Java代码
|
public MessageCorrelationAsyncBuilder setVariable(String variableName, Object variableValue) {
ensureNotNull("variableName", variableName);
ensurePayloadProcessInstanceVariablesInitialized();
payloadProcessInstanceVariables.put(variableName, variableValue);
return this;
}
public MessageCorrelationAsyncBuilder setVariables(Map<String, Object> variables) {
if (variables != null) {
ensurePayloadProcessInstanceVariablesInitialized();
payloadProcessInstanceVariables.putAll(variables);
}
return this;
}
protected void ensurePayloadProcessInstanceVariablesInitialized() {
if (payloadProcessInstanceVariables == null) {
payloadProcessInstanceVariables = new VariableMapImpl();
}
}
@Override
public Batch correlateAllAsync() {
return commandExecutor.execute(new CorrelateAllMessageBatchCmd(this));
}
// getters //////////////////////////////////
public CommandExecutor getCommandExecutor() {
|
return commandExecutor;
}
public String getMessageName() {
return messageName;
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public ProcessInstanceQuery getProcessInstanceQuery() {
return processInstanceQuery;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public Map<String, Object> getPayloadProcessInstanceVariables() {
return payloadProcessInstanceVariables;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\MessageCorrelationAsyncBuilderImpl.java
| 1
|
请完成以下Java代码
|
public class MaterialTrackingPPOrderDAO implements IMaterialTrackingPPOrderDAO
{
@Override
public int deleteInvoiceDetails(final I_PP_Order ppOrder)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_Invoice_Detail.class, ppOrder)
.addEqualsFilter(I_C_Invoice_Detail.COLUMN_PP_Order_ID, ppOrder.getPP_Order_ID())
.create()
.delete();
}
@Override
public int deleteRelatedUnprocessedICs(final I_PP_Order ppOrder)
{
// there might be many ICs with the regular PP_Order product but for different qualityInvoiceLineGroups
final IQueryBL queryBL = Services.get(IQueryBL.class);
// load the IC that whose C_Invoice_Detail references ppOrder.
// we expect just one, but want to be lenient if there are > 1.
final List<de.metas.materialtracking.model.I_C_Invoice_Candidate> ppOrderICs =
queryBL.createQueryBuilder(I_C_Invoice_Detail.class, ppOrder)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Invoice_Detail.COLUMN_PP_Order_ID, ppOrder.getPP_Order_ID())
.andCollect(de.metas.invoicecandidate.model.I_C_Invoice_Detail.COLUMN_C_Invoice_Candidate_ID)
.addOnlyActiveRecordsFilter()
.create()
.list(de.metas.materialtracking.model.I_C_Invoice_Candidate.class);
if (ppOrderICs.isEmpty())
{
return 0;
}
int result = 0;
for (final de.metas.materialtracking.model.I_C_Invoice_Candidate ppOrderIC : ppOrderICs)
{
// use ppOrderIC as a representative to delete all unprocessed ICs with the same PLV and M_Material_Tracking
result += queryBL.createQueryBuilder(I_C_Invoice_Candidate.class, ppOrder)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_AD_Table_ID, Services.get(IADTableDAO.class).retrieveTableId(org.eevolution.model.I_PP_Order.Table_Name))
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Record_ID, ppOrderIC.getRecord_ID())
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_M_PriceList_Version_ID, ppOrderIC.getM_PriceList_Version_ID())
|
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Processed, false)
.addEqualsFilter(de.metas.materialtracking.model.I_C_Invoice_Candidate.COLUMNNAME_M_Material_Tracking_ID, ppOrderIC.getM_Material_Tracking_ID())
.create()
.delete();
}
return result;
}
@Override
public boolean isPPOrderInvoicedForMaterialTracking(
@NonNull final I_PP_Order ppOrder,
@NonNull final I_M_Material_Tracking materialTrackingRecord)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
return queryBL.createQueryBuilder(I_C_Invoice_Detail.class, ppOrder)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Invoice_Detail.COLUMNNAME_PP_Order_ID, ppOrder.getPP_Order_ID())
.andCollect(de.metas.invoicecandidate.model.I_C_Invoice_Detail.COLUMN_C_Invoice_Candidate_ID)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMN_Processed, true)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_M_Material_Tracking_ID, materialTrackingRecord.getM_Material_Tracking_ID())
.create()
.anyMatch();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingPPOrderDAO.java
| 1
|
请完成以下Java代码
|
public void setLastNameLike(String userLastNameLike) {
this.lastNameLike = userLastNameLike;
}
@CamundaQueryParam("email")
public void setEmail(String userEmail) {
this.email = userEmail;
}
@CamundaQueryParam("emailLike")
public void setEmailLike(String userEmailLike) {
this.emailLike = userEmailLike;
}
@CamundaQueryParam("memberOfGroup")
public void setMemberOfGroup(String memberOfGroup) {
this.memberOfGroup = memberOfGroup;
}
@CamundaQueryParam("potentialStarter")
public void setPotentialStarter(String potentialStarter) {
this.potentialStarter = potentialStarter;
}
@CamundaQueryParam("memberOfTenant")
public void setMemberOfTenant(String tenantId) {
this.tenantId = tenantId;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected UserQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createUserQuery();
}
@Override
protected void applyFilters(UserQuery query) {
if (id != null) {
query.userId(id);
}
if(idIn != null) {
|
query.userIdIn(idIn);
}
if (firstName != null) {
query.userFirstName(firstName);
}
if (firstNameLike != null) {
query.userFirstNameLike(firstNameLike);
}
if (lastName != null) {
query.userLastName(lastName);
}
if (lastNameLike != null) {
query.userLastNameLike(lastNameLike);
}
if (email != null) {
query.userEmail(email);
}
if (emailLike != null) {
query.userEmailLike(emailLike);
}
if (memberOfGroup != null) {
query.memberOfGroup(memberOfGroup);
}
if (potentialStarter != null) {
query.potentialStarter(potentialStarter);
}
if (tenantId != null) {
query.memberOfTenant(tenantId);
}
}
@Override
protected void applySortBy(UserQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_USER_ID_VALUE)) {
query.orderByUserId();
} else if (sortBy.equals(SORT_BY_USER_FIRSTNAME_VALUE)) {
query.orderByUserFirstName();
} else if (sortBy.equals(SORT_BY_USER_LASTNAME_VALUE)) {
query.orderByUserLastName();
} else if (sortBy.equals(SORT_BY_USER_EMAIL_VALUE)) {
query.orderByUserEmail();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserQueryDto.java
| 1
|
请完成以下Java代码
|
public static Optional<UserId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final UserId userId)
{
return toRepoIdOr(userId, -1);
}
public static int toRepoIdOr(
@Nullable final UserId userId,
final int defaultValue)
{
return userId != null ? userId.getRepoId() : defaultValue;
}
public static boolean equals(@Nullable final UserId userId1, @Nullable final UserId userId2)
{
return Objects.equals(userId1, userId2);
}
int repoId;
private UserId(final int userRepoId)
{
this.repoId = Check.assumeGreaterOrEqualToZero(userRepoId, "userRepoId");
}
|
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public boolean isSystemUser() {return isSystemUser(repoId);}
private static boolean isSystemUser(final int repoId) {return repoId == SYSTEM.repoId;}
public boolean isRegularUser() {return !isSystemUser();}
private static boolean isRegularUser(int repoId) {return !isSystemUser(repoId);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserId.java
| 1
|
请完成以下Java代码
|
private AvailabilityInfoResultForWebui.Group createClientResultGroup(@NonNull final AvailableToPromiseResultGroup commonsResultGroup)
{
try
{
return createClientResultGroup0(commonsResultGroup);
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e).appendParametersToMessage()
.setParameter("commonsResultGroup", commonsResultGroup);
}
}
private Quantity extractQuantity(final AvailableToPromiseResultGroup commonsResultGroup)
{
final BigDecimal qty = commonsResultGroup.getQty();
final I_C_UOM uom = productsService.getStockUOM(commonsResultGroup.getProductId());
return Quantity.of(qty, uom);
}
private AvailabilityInfoResultForWebui.Group createClientResultGroup0(final AvailableToPromiseResultGroup commonsResultGroup)
{
final Quantity quantity = extractQuantity(commonsResultGroup);
final AttributesKey attributesKey = commonsResultGroup.getStorageAttributesKey();
final AvailabilityInfoResultForWebui.Group.Type type = extractGroupType(attributesKey);
final ImmutableAttributeSet attributes = AvailabilityInfoResultForWebui.Group.Type.ATTRIBUTE_SET.equals(type)
? AttributesKeys.toImmutableAttributeSet(attributesKey)
|
: ImmutableAttributeSet.EMPTY;
return AvailabilityInfoResultForWebui.Group.builder()
.productId(commonsResultGroup.getProductId())
.qty(quantity)
.type(type)
.attributes(attributes)
.build();
}
public Set<AttributesKeyPattern> getPredefinedStorageAttributeKeys()
{
return availableToPromiseRepository.getPredefinedStorageAttributeKeys();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\adapter\AvailableToPromiseAdapter.java
| 1
|
请完成以下Java代码
|
protected CustomPropertiesResolver createCustomPropertiesResolver(ActivitiListener activitiListener) {
CustomPropertiesResolver customPropertiesResolver = null;
ListenerFactory listenerFactory = Context.getProcessEngineConfiguration().getListenerFactory();
if (
ImplementationType.IMPLEMENTATION_TYPE_CLASS.equalsIgnoreCase(
activitiListener.getCustomPropertiesResolverImplementationType()
)
) {
customPropertiesResolver = listenerFactory.createClassDelegateCustomPropertiesResolver(activitiListener);
} else if (
ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION.equalsIgnoreCase(
activitiListener.getCustomPropertiesResolverImplementationType()
)
) {
customPropertiesResolver = listenerFactory.createExpressionCustomPropertiesResolver(activitiListener);
} else if (
ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equalsIgnoreCase(
activitiListener.getCustomPropertiesResolverImplementationType()
)
) {
customPropertiesResolver = listenerFactory.createDelegateExpressionCustomPropertiesResolver(
activitiListener
);
}
return customPropertiesResolver;
}
protected Map<String, Object> invokeCustomPropertiesResolver(
DelegateExecution execution,
CustomPropertiesResolver customPropertiesResolver
|
) {
Map<String, Object> customPropertiesMapToUse = null;
if (customPropertiesResolver != null) {
customPropertiesMapToUse = customPropertiesResolver.getCustomPropertiesMap(execution);
}
return customPropertiesMapToUse;
}
protected void addTransactionListener(ActivitiListener activitiListener, TransactionListener transactionListener) {
TransactionContext transactionContext = Context.getTransactionContext();
if (
TransactionDependentExecutionListener.ON_TRANSACTION_BEFORE_COMMIT.equals(
activitiListener.getOnTransaction()
)
) {
transactionContext.addTransactionListener(TransactionState.COMMITTING, transactionListener);
} else if (
TransactionDependentExecutionListener.ON_TRANSACTION_COMMITTED.equals(activitiListener.getOnTransaction())
) {
transactionContext.addTransactionListener(TransactionState.COMMITTED, transactionListener);
} else if (
TransactionDependentExecutionListener.ON_TRANSACTION_ROLLED_BACK.equals(activitiListener.getOnTransaction())
) {
transactionContext.addTransactionListener(TransactionState.ROLLED_BACK, transactionListener);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\ListenerNotificationHelper.java
| 1
|
请完成以下Java代码
|
public java.lang.String getStoreCreditCardData()
{
return get_ValueAsString(COLUMNNAME_StoreCreditCardData);
}
@Override
public void setSupervisor_ID (final int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID);
}
@Override
public int getSupervisor_ID()
{
return get_ValueAsInt(COLUMNNAME_Supervisor_ID);
}
@Override
public void setTimeZone (final @Nullable java.lang.String TimeZone)
{
set_Value (COLUMNNAME_TimeZone, TimeZone);
}
@Override
public java.lang.String getTimeZone()
{
return get_ValueAsString(COLUMNNAME_TimeZone);
}
@Override
public void setTransferBank_ID (final int TransferBank_ID)
{
if (TransferBank_ID < 1)
set_Value (COLUMNNAME_TransferBank_ID, null);
else
set_Value (COLUMNNAME_TransferBank_ID, TransferBank_ID);
}
@Override
public int getTransferBank_ID()
|
{
return get_ValueAsInt(COLUMNNAME_TransferBank_ID);
}
@Override
public org.compiere.model.I_C_CashBook getTransferCashBook()
{
return get_ValueAsPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class);
}
@Override
public void setTransferCashBook(final org.compiere.model.I_C_CashBook TransferCashBook)
{
set_ValueFromPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class, TransferCashBook);
}
@Override
public void setTransferCashBook_ID (final int TransferCashBook_ID)
{
if (TransferCashBook_ID < 1)
set_Value (COLUMNNAME_TransferCashBook_ID, null);
else
set_Value (COLUMNNAME_TransferCashBook_ID, TransferCashBook_ID);
}
@Override
public int getTransferCashBook_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferCashBook_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgInfo.java
| 1
|
请完成以下Java代码
|
public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
@Override
public void setC_DocType_PrintOptions_ID (final int C_DocType_PrintOptions_ID)
{
if (C_DocType_PrintOptions_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DocType_PrintOptions_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocType_PrintOptions_ID, C_DocType_PrintOptions_ID);
}
@Override
public int getC_DocType_PrintOptions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_PrintOptions_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* DocumentFlavor AD_Reference_ID=541225
* Reference name: C_DocType_PrintOptions_DocumentFlavor
*/
public static final int DOCUMENTFLAVOR_AD_Reference_ID=541225;
/** EMail = E */
public static final String DOCUMENTFLAVOR_EMail = "E";
/** Print = P */
public static final String DOCUMENTFLAVOR_Print = "P";
@Override
public void setDocumentFlavor (final java.lang.String DocumentFlavor)
{
set_Value (COLUMNNAME_DocumentFlavor, DocumentFlavor);
}
@Override
public java.lang.String getDocumentFlavor()
{
|
return get_ValueAsString(COLUMNNAME_DocumentFlavor);
}
@Override
public void setPRINTER_OPTS_IsPrintLogo (final boolean PRINTER_OPTS_IsPrintLogo)
{
set_Value (COLUMNNAME_PRINTER_OPTS_IsPrintLogo, PRINTER_OPTS_IsPrintLogo);
}
@Override
public boolean isPRINTER_OPTS_IsPrintLogo()
{
return get_ValueAsBoolean(COLUMNNAME_PRINTER_OPTS_IsPrintLogo);
}
@Override
public void setPRINTER_OPTS_IsPrintTotals (final boolean PRINTER_OPTS_IsPrintTotals)
{
set_Value (COLUMNNAME_PRINTER_OPTS_IsPrintTotals, PRINTER_OPTS_IsPrintTotals);
}
@Override
public boolean isPRINTER_OPTS_IsPrintTotals()
{
return get_ValueAsBoolean(COLUMNNAME_PRINTER_OPTS_IsPrintTotals);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_PrintOptions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class M_Forecast
{
private static final String MSG_DOC_ACTION_NOT_ALLOWED_AFTER_COMPLETION = "M_Forecast_DocAction_Not_Allowed_After_Completion";
private final IMsgBL msgBL = Services.get(IMsgBL.class);
private final IForecastDAO forecastsRepo = Services.get(IForecastDAO.class);
private final ICalendarBL calendarBL = Services.get(ICalendarBL.class);
private final ICalendarDAO calendarDAO = Services.get(ICalendarDAO.class);
public static final AdMessageKey MSG_CALENDAR_DOES_NOT_CONTAIN_PROMISED_DATE = AdMessageKey.of("de.metas.material.interceptor.M_Forecast.CalendarDoesNotContainPromisedDate");
public M_Forecast()
{
CopyRecordFactory.enableForTableName(I_M_Forecast.Table_Name);
}
@DocValidate(timings = {
ModelValidator.TIMING_BEFORE_CLOSE,
ModelValidator.TIMING_BEFORE_REVERSEACCRUAL,
ModelValidator.TIMING_BEFORE_REVERSECORRECT,
})
public void preventUnsupportedDocActions(@NonNull final I_M_Forecast forecast)
{
final String message = msgBL.getMsg(Env.getCtx(), MSG_DOC_ACTION_NOT_ALLOWED_AFTER_COMPLETION);
throw new AdempiereException(message);
}
@ModelChange(
timings = {
ModelValidator.TYPE_BEFORE_CHANGE,
ModelValidator.TYPE_BEFORE_NEW
},
ifColumnsChanged = {
I_M_Forecast.COLUMNNAME_DatePromised,
})
public void updateFieldsFromDatePromised(@NonNull final I_M_Forecast forecast)
{
final CalendarId calendarId = calendarBL.getOrgCalendarOrDefault(OrgId.ofRepoId(forecast.getAD_Org_ID()));
final Timestamp datePromised = forecast.getDatePromised();
final I_C_Period period = calendarDAO.findByCalendar(datePromised, calendarId);
|
if (period == null)
{
final String calendarName = calendarDAO.getName(calendarId);
throw new AdempiereException(MSG_CALENDAR_DOES_NOT_CONTAIN_PROMISED_DATE, calendarName, datePromised);
}
forecast.setC_Calendar_ID(calendarId.getRepoId());
forecast.setC_Period_ID(period.getC_Period_ID());
forecast.setC_Year_ID(period.getC_Year_ID());
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = {
I_M_Forecast.COLUMNNAME_C_BPartner_ID,
I_M_Forecast.COLUMNNAME_C_Period_ID,
I_M_Forecast.COLUMNNAME_DatePromised,
I_M_Forecast.COLUMNNAME_M_Warehouse_ID
})
public void updateForecastLines(@NonNull final I_M_Forecast forecast)
{
final List<I_M_ForecastLine> forecastLines = forecastsRepo.retrieveLinesByForecastId(ForecastId.ofRepoId(forecast.getM_Forecast_ID()));
forecastLines.forEach(forecastLine -> updateForecastLineFromHeaderAndSave(forecastLine, forecast));
}
private void updateForecastLineFromHeaderAndSave(final I_M_ForecastLine forecastLine, final I_M_Forecast forecast)
{
forecastLine.setC_BPartner_ID(forecast.getC_BPartner_ID());
forecastLine.setM_Warehouse_ID(forecast.getM_Warehouse_ID());
forecastLine.setC_Period_ID(forecast.getC_Period_ID());
forecastLine.setDatePromised(forecast.getDatePromised());
saveRecord(forecastLine);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\interceptor\M_Forecast.java
| 2
|
请完成以下Java代码
|
public boolean supports(Class<?> authentication) {
return OAuth2DeviceVerificationAuthenticationToken.class.isAssignableFrom(authentication);
}
/**
* Sets the {@code Predicate} used to determine if authorization consent is required.
*
* <p>
* The {@link OAuth2DeviceVerificationAuthenticationContext} gives the predicate
* access to the {@link OAuth2DeviceVerificationAuthenticationToken}, as well as, the
* following context attributes:
* <ul>
* <li>The {@link RegisteredClient} associated with the device authorization
* request.</li>
* <li>The {@link OAuth2Authorization} containing the device authorization request
* parameters.</li>
* <li>The {@link OAuth2AuthorizationConsent} previously granted to the
* {@link RegisteredClient}, or {@code null} if not available.</li>
* </ul>
* </p>
* @param authorizationConsentRequired the {@code Predicate} used to determine if
* authorization consent is required
*/
public void setAuthorizationConsentRequired(
Predicate<OAuth2DeviceVerificationAuthenticationContext> authorizationConsentRequired) {
Assert.notNull(authorizationConsentRequired, "authorizationConsentRequired cannot be null");
this.authorizationConsentRequired = authorizationConsentRequired;
}
|
private static boolean isAuthorizationConsentRequired(
OAuth2DeviceVerificationAuthenticationContext authenticationContext) {
if (authenticationContext.getAuthorizationConsent() != null && authenticationContext.getAuthorizationConsent()
.getScopes()
.containsAll(authenticationContext.getRequestedScopes())) {
return false;
}
return true;
}
private static boolean isPrincipalAuthenticated(Authentication principal) {
return principal != null && !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass())
&& principal.isAuthenticated();
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceVerificationAuthenticationProvider.java
| 1
|
请完成以下Java代码
|
public void setP_String (java.lang.String P_String)
{
set_Value (COLUMNNAME_P_String, P_String);
}
/** Get Process String.
@return Prozess-Parameter
*/
@Override
public java.lang.String getP_String ()
{
return (java.lang.String)get_Value(COLUMNNAME_P_String);
}
/** Set Parameter Name.
|
@param ParameterName Parameter Name */
@Override
public void setParameterName (java.lang.String ParameterName)
{
set_ValueNoCheck (COLUMNNAME_ParameterName, ParameterName);
}
/** Get Parameter Name.
@return Parameter Name */
@Override
public java.lang.String getParameterName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ParameterName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Param.java
| 1
|
请完成以下Java代码
|
public int getProcessIdAsInt()
{
int processIdAsInt = this.processIdAsInt;
if (processIdAsInt <= 0)
{
final String processIdStr = getProcessId();
processIdAsInt = Integer.parseInt(processIdStr);
if (processIdAsInt <= 0)
{
throw new IllegalStateException("processId cannot be converted to int: " + processIdStr);
}
this.processIdAsInt = processIdAsInt;
}
return processIdAsInt;
}
public AdProcessId toAdProcessId()
{
final AdProcessId adProcessId = toAdProcessIdOrNull();
if (adProcessId == null)
{
throw new AdempiereException("Cannot convert " + this + " to " + AdProcessId.class.getSimpleName() + " because the processHanderType=" + processHandlerType + " is not supported");
}
return adProcessId;
}
/**
* Convenience method to get the {@link AdProcessId} for this instance if its {@code processIdAsInt} member is set and/or if {@link #getProcessHandlerType()} is {@link #PROCESSHANDLERTYPE_AD_Process}.
|
* {@code null} otherwise.
*/
public AdProcessId toAdProcessIdOrNull()
{
if (this.processIdAsInt > 0) // was set by the creator of this instance
{
return AdProcessId.ofRepoId(this.processIdAsInt);
}
else if (this.processHandlerType.isADProcess())
{
return AdProcessId.ofRepoId(getProcessIdAsInt());
}
else // nothing we can do here
{
return null;
}
}
public DocumentId toDocumentId()
{
return DocumentId.ofString(toJson());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ProcessId.java
| 1
|
请完成以下Java代码
|
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Book> getBooks() {
return books;
}
|
public void setBooks(List<Book> books) {
this.books = books;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootFetchJoinAndQueries\src\main\java\com\bookstore\entity\Author.java
| 1
|
请完成以下Java代码
|
public void setDateTo (java.sql.Timestamp DateTo)
{
set_Value (COLUMNNAME_DateTo, DateTo);
}
/** Get Datum bis.
@return End date of a date range
*/
@Override
public java.sql.Timestamp getDateTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateTo);
}
/** Set Vorgangsdatum.
@param DateTrx
Transaction Date
*/
@Override
public void setDateTrx (java.sql.Timestamp DateTrx)
{
set_Value (COLUMNNAME_DateTrx, DateTrx);
}
/** Get Vorgangsdatum.
@return Transaction Date
*/
@Override
public java.sql.Timestamp getDateTrx ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateTrx);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** 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 Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
|
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclaration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public I_C_Location retrieveOrgLocation(@NonNull final OrgId orgId)
{
final BPartnerLocationId orgBPLocationId = retrieveOrgBPLocationId(orgId);
if (orgBPLocationId == null)
{
return null;
}
final I_C_BPartner_Location bpLocation = Services.get(IBPartnerDAO.class).getBPartnerLocationByIdEvenInactive(orgBPLocationId);
if (bpLocation != null) // 03378 : Temporary. Will be removed when OrgBP_Location is mandatory.
{
return bpLocation.getC_Location();
}
return null;
}
@Override
public BPartnerLocationId retrieveOrgBPLocationId(final OrgId orgId)
{
final IOrgDAO orgsRepo = Services.get(IOrgDAO.class);
return orgsRepo.getOrgInfoById(orgId).getOrgBPartnerLocationId();
}
@Override
public Optional<UserId> retrieveUserInChargeOrNull(@NonNull final OrgId orgId)
{
final org.compiere.model.I_AD_User user = retrieveUserInChargeOrNull(Env.getCtx(), orgId.getRepoId(), ITrx.TRXNAME_None);
if (user != null)
{
return Optional.of(UserId.ofRepoId(user.getAD_User_ID()));
}
return Optional.empty();
}
@Override
@Deprecated
public org.compiere.model.I_AD_User retrieveUserInChargeOrNull(final Properties ctx, final int orgId, final String trxName)
{
final IBPartnerDAO bPartnerPA = Services.get(IBPartnerDAO.class);
org.compiere.model.I_AD_User defaultContact;
try
|
{
final I_C_BPartner orgBPartner = bPartnerPA.retrieveOrgBPartner(ctx, orgId, I_C_BPartner.class, trxName);
defaultContact = bPartnerPA.retrieveDefaultContactOrNull(orgBPartner, I_AD_User.class);
}
catch (final OrgHasNoBPartnerLinkException e)
{
defaultContact = null;
}
return defaultContact;
}
@NonNull
@Override
public String getOrgLanguageOrLoggedInUserLanguage(@NonNull final OrgId orgId)
{
final OrgInfo orgInfo = orgDAO.getOrgInfoById(orgId);
final BPartnerId orgBpartnerId = orgInfo.getOrgBPartnerLocationId().getBpartnerId();
final Language language = Services.get(IBPartnerBL.class)
.getLanguage(orgBpartnerId)
.orElse(null);
if (language != null)
{
return language.getAD_Language();
}
else
{
return Env.getADLanguageOrBaseLanguage();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerOrgBL.java
| 2
|
请完成以下Java代码
|
public class FindSecondSmallestNumber {
public static int usingArraySort(int[] arr) {
Arrays.sort(arr);
int smallest = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != smallest) {
return arr[i];
}
}
return -1;
}
public static int usingSinglePassThrough(int[] arr) {
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int num : arr) {
if (num < smallest) {
secondSmallest = smallest;
smallest = num;
} else if (num < secondSmallest && num != smallest) {
secondSmallest = num;
}
}
if (secondSmallest == Integer.MAX_VALUE) {
return -1;
} else {
return secondSmallest;
}
}
public static int usingMinHeap(int[] arr) {
if (arr.length < 2) {
return -1;
}
|
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : arr) {
if (minHeap.isEmpty() || num != minHeap.peek()) {
minHeap.offer(num);
}
}
// Check if the heap less than 2 (all elements were the same)
if (minHeap.size() < 2) {
return -1;
}
minHeap.poll(); // Remove the smallest element
return minHeap.peek(); // Second smallest element is at the root (peek)
}
}
|
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\secondsmallest\FindSecondSmallestNumber.java
| 1
|
请完成以下Java代码
|
public void add(String userId, List<Group> groups) {
this.groupCache.put(userId, new LDAPGroupCacheEntry(clockReader.get().getCurrentTime(), groups));
}
public List<Group> get(String userId) {
LDAPGroupCacheEntry cacheEntry = groupCache.get(userId);
if (cacheEntry != null) {
if ((clockReader.get().getCurrentTime().getTime() - cacheEntry.getTimestamp().getTime()) < expirationTime) {
if (ldapCacheListener != null) {
ldapCacheListener.cacheHit(userId);
}
return cacheEntry.getGroups();
} else {
this.groupCache.remove(userId);
if (ldapCacheListener != null) {
ldapCacheListener.cacheExpired(userId);
ldapCacheListener.cacheEviction(userId);
}
}
}
if (ldapCacheListener != null) {
ldapCacheListener.cacheMiss(userId);
}
return null;
}
public void clear() {
groupCache.clear();
}
public Map<String, LDAPGroupCacheEntry> getGroupCache() {
return groupCache;
}
public void setGroupCache(Map<String, LDAPGroupCacheEntry> groupCache) {
this.groupCache = groupCache;
}
public long getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(long expirationTime) {
this.expirationTime = expirationTime;
}
public LDAPGroupCacheListener getLdapCacheListener() {
return ldapCacheListener;
}
public void setLdapCacheListener(LDAPGroupCacheListener ldapCacheListener) {
this.ldapCacheListener = ldapCacheListener;
}
// Helper classes ////////////////////////////////////
static class LDAPGroupCacheEntry {
protected Date timestamp;
protected List<Group> groups;
public LDAPGroupCacheEntry() {
}
public LDAPGroupCacheEntry(Date timestamp, List<Group> groups) {
this.timestamp = timestamp;
|
this.groups = groups;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
}
// Cache listeners. Currently not yet exposed (only programmatically for the
// moment)
// Experimental stuff!
public static interface LDAPGroupCacheListener {
void cacheHit(String userId);
void cacheMiss(String userId);
void cacheEviction(String userId);
void cacheExpired(String userId);
}
}
|
repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\LDAPGroupCache.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static Set<Class<?>> getConfigurableTypes() {
Set<Class<?>> classesToAdd = getClassesToAdd();
Set<Class<?>> genericsToAdd = new HashSet<>();
Set<Class<?>> superTypes = new HashSet<>();
for (Class<?> clazz : classesToAdd) {
ResolvableType resolvableType = ResolvableType.forType(clazz);
addGenericsForClass(genericsToAdd, resolvableType);
addSuperTypesForClass(resolvableType, superTypes, genericsToAdd);
}
classesToAdd.addAll(genericsToAdd);
classesToAdd.addAll(superTypes);
return classesToAdd.stream().filter(Objects::nonNull).collect(Collectors.toSet());
}
private static void addGenericsForClass(Set<Class<?>> genericsToAdd, ResolvableType resolvableType) {
if (resolvableType.getSuperType().hasGenerics()) {
genericsToAdd.addAll(Arrays.stream(resolvableType.getSuperType().getGenerics())
.map(ResolvableType::toClass)
.collect(Collectors.toSet()));
}
}
private static void addSuperTypesForClass(ResolvableType resolvableType, Set<Class<?>> supertypesToAdd,
Set<Class<?>> genericsToAdd) {
ResolvableType superType = resolvableType.getSuperType();
if (!ResolvableType.NONE.equals(superType)) {
addGenericsForClass(genericsToAdd, superType);
supertypesToAdd.add(superType.toClass());
addSuperTypesForClass(superType, supertypesToAdd, genericsToAdd);
}
}
@SuppressWarnings({ "rawtypes" })
private static Set<Class<?>> getClassesToAdd() {
Set<Class<?>> classesToAdd = new HashSet<>();
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(Configurable.class));
Set<BeanDefinition> components = provider.findCandidateComponents(ROOT_GATEWAY_PACKAGE_NAME);
for (BeanDefinition component : components) {
Class clazz;
try {
clazz = Class.forName(component.getBeanClassName());
if (shouldRegisterClass(clazz)) {
classesToAdd.add(clazz);
|
}
}
catch (NoClassDefFoundError | ClassNotFoundException exception) {
if (LOG.isDebugEnabled()) {
LOG.debug(exception);
}
}
}
return classesToAdd;
}
private static boolean shouldRegisterClass(Class<?> clazz) {
Set<String> conditionClasses = beansConditionalOnClasses.getOrDefault(clazz, Collections.emptySet());
for (String conditionClass : conditionClasses) {
try {
ConfigurableHintsRegistrationProcessor.class.getClassLoader().loadClass(conditionClass);
}
catch (ClassNotFoundException e) {
return false;
}
}
return true;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\ConfigurableHintsRegistrationProcessor.java
| 2
|
请完成以下Spring Boot application配置
|
server:
port: 8080
tomcat:
max-swallow-size: -1
error:
include-exception: true
include-stacktrace: ALWAYS
include-message: ALWAYS
servlet:
context-path: /jeecg-boot
compression:
enabled: true
min-response-size: 1024
mime-types: application/javascript,application/json,application/xml,text/html,text/xml,text/plain,text/css,image/*
management:
endpoints:
web:
exposure:
include: metrics,httpexchanges,jeecghttptrace
spring:
# main:
# # 启动加速 (建议开发环境,开启后flyway自动升级失效)
# lazy-initialization: true
flyway:
# 是否启用flyway
enabled: false
# 迁移sql脚本存放路径
locations: classpath:flyway/sql/mysql
# 是否关闭要清除已有库下的表功能,生产环境必须为true,否则会删库,非常重要!!!
clean-disabled: true
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
mail:
# 定时任务发送邮件
timeJobSend: false
host: smtp.163.com
username: jeecgos@163.com
password: ??
properties:
mail.smtp.timeout: 10000 # 连接超时(毫秒)
mail.smtp.connectiontimeout: 10000 # 连接超时(毫秒)
mail.smtp.writetimeout: 10000 # 写入超时(毫秒)
mail.smtp.auth: true
smtp.ssl.enable: true
# mail.debug: true # 启用调试模式(查看详细日志)
## quartz定时任务,采用数据库方式
quartz:
job-store-type: jdbc
jdbc:
initialize-schema: embedded
#定时任务启动开关,true-开 false-关
auto-startup: true
#延迟1秒启动定时任务
startup-delay: 1s
#启动时更新己存在的Job
overwrite-existing-jobs: true
properties:
org:
quartz:
scheduler:
instanceName: MyScheduler
instanceId: AUTO
jobStore:
class: org.springframework.scheduling.quartz.LocalDataSourceJobStore
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
tablePrefix: QRTZ_
isClustered: true
misfireThreshold: 12000
clusterCheckinInterval: 15000
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 10
threadPriority: 5
threadsInheritContextClassLoaderOfInitializingThread: true
#json 时间戳统一转换
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
jpa:
open-in-view: false
aop:
proxy-target-class: true
#配置freemarker
freemarker:
# 设置模板后缀名
suffix: .ftl
# 设置文档类型
content-type: text/html
# 设置页面编码格式
charset: UTF-8
# 设置页面缓存
cache: false
prefer-file-system-access: false
# 设置ftl文件路径
template-loader-path:
- classpath:/templates
template_update_delay: 0
# 设置静态文件路径,js,css等
mvc:
static-path-pattern: /**
#Spring Boot 2.6+后映射匹配的默认策略已从AntPathMatcher更改为PathPatternParser,需要手动指定为ant-path-matcher
pathmatch:
matching-strategy: ant_path_matcher
resource:
static-locations: classpath:/static/,classpath:/public/
autoconfigure:
exclude:
- com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure
- org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration
datasource:
druid:
stat-view-servlet:
enabled: true
loginUsername: admin
loginPassword: 123456
allow:
web-stat-filter:
enabled: true
dynamic:
druid: # 全局druid参数,绝大部分值和默认保持一致。(现已支持的参数如下,不清楚含义不要乱设置)
# 连接池的配置信息
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
maxActive: 1000
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,slf4j
# 允许SELECT语句的WHERE子句是一个永真条件
wall:
selectWhereAlwayTrueCheck: false
# 打开mergeSql功能;慢SQL记录
stat:
merge-sql: false
slow-sql-millis: 5000
datasource:
master:
url: jdbc:mysql://127.0.0.1:3306/jeecg-boot?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# # shardingjdbc数据源
# sharding-db:
# driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
# url: jdbc:shardingsphere:classpath:sharding.yaml
#redis 配置
data:
redis:
database: 0
host: 127.0.0.1
port: 6379
password:
#mybatis plus 设置
mybatis-plus:
mapper-locations: classpath*:org/jeecg/**/xml/*Mapper.xml
global-config:
# 关闭MP3.0自带的banner
banner: false
db-config:
#主键类型 0:"数据库ID自增",1:"该类型为未设置主键类型", 2:"用户输入ID",3:"全局唯一ID (数字类型唯一ID)", 4:"全局唯一ID UUID",5:"字符串全局唯一ID (idWorker 的字符串表示)";
id-type: ASSIGN_ID
# 默认数据库表下划线命名
table-underline: true
configuration:
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
#log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 返回类型为Map,显示null对应的字段
call-setters-on-nulls: true
#jeecg专用配置
minidao:
base-package: org.jeecg.modules.jmreport.*,org.jeecg.modules.drag.*
jeecg:
# AI集成
ai-chat:
enabled: true
model: deepseek-chat
apiKey: ??
apiHost: https://api.deepseek.com/v1
timeout: 60
# AIRag向量库
ai-rag:
embed-store:
host: 127.0.0.1
port: 5432
database: postgres
user: postgres
password: postgres
table: embeddings
# Unipush配置 云函数调用 URL 化地址
unicloud:
pushUrl:
# 平台上线安全配置
firewall:
# 数据源安全 (开启后,Online报表和图表的数据源为必填)
dataSourceSafe: false
# 低代码模式(dev:开发模式,prod:发布模式——关闭所有在线开发配置能力)
lowCodeMode: dev
# 是否允许同一账号多地同时登录 (为 true 时允许一起登录, 为 false 时新登录挤掉旧登录)
is-concurrent: true
# 签名密钥串(前后端要一致,正式发布请自行修改)
signatureSecret: dd05f1c54d63749eda95f9fa6d49v442a
#签名拦截接口
signUrls: /sys/dict/getDictItems/*,/sys/dict/loadDict/*,/sys/dict/loadDictOrderByValue/*,/sys/dict/loadDictItem/*,/sys/dict/loadTreeData,/sys/api/queryTableDictItemsByCode,/sys/api/queryFilterTableDictInfo,/sys/api/queryTableDictByKeys,/sys/api/translateDictFromTable,/sys/api/translateDictFromTableByKeys,/sys/sendChangePwdSms,/sys/user/sendChangePhoneSms,/sys/sms,/desform/api/sendVerifyCode
# 本地:local、Minio:minio、阿里云:alioss
uploadType: local
# 前端访问地址
domainUrl:
pc: http://localhost:3100
app: http://localhost:8051
path:
#文件上传根目录 设置
upload: /opt/upFiles
#webapp文件路径
webapp: /opt/webapp
shiro:
excludeUrls: /test/jeecgDemo/demo3,/test/jeecgDemo/redisDemo/**,/bigscreen/
|
category/**,/bigscreen/visual/**,/bigscreen/map/**,/jmreport/bigscreen2/**
# 短信发送方式 aliyun阿里云短信 tencent腾讯云短信
smsSendType: aliyun
#阿里云oss存储和大鱼短信秘钥配置
oss:
accessKey: ??
secretKey: ??
endpoint: oss-cn-beijing.aliyuncs.com
bucketName: jeecgdev
# 短信模板
sms-template:
# 签名
signature:
# 模板code
templateCode:
# 登录短信、忘记密码模板编码
SMS_175435174:
# 修改密码短信模板编码
SMS_465391221:
# 注册账号短信模板编码
SMS_175430166:
#腾讯短信秘钥配置
tencent:
# 接入域名
endpoint: sms.tencentcloudapi.com
secretId: ??
secretKey: ??
# 应用ID
sdkAppId: ??
# 地域信息
region: ap-beijing
# 在线预览文件服务器地址配置
file-view-domain: http://fileview.jeecg.com
# minio文件上传
minio:
minio_url: http://minio.jeecg.com
minio_name: ??
minio_pass: ??
bucketName: otatest
#大屏报表参数设置
jmreport:
#多租户模式,默认值为空(created:按照创建人隔离、tenant:按照租户隔离) (v1.6.2+ 新增)
saasMode:
# 平台上线安全配置(v1.6.2+ 新增)
firewall:
# 数据源安全 (开启后,不允许使用平台数据源、SQL解析加签并且不允许查询数据库)
dataSourceSafe: false
# 低代码开发模式(dev:开发模式,prod:发布模式—关闭在线报表设计功能,分配角色admin、lowdeveloper可以放开限制)
lowCodeMode: dev
# 高德地图Api配置(v2.1.3+ BI新增高德地图)
gao-de-api:
# 应用key
api-key: ??
# 应用秘钥
secret-key: ??
#xxl-job配置
xxljob:
enabled: false
adminAddresses: http://127.0.0.1:9080/xxl-job-admin
appname: ${spring.application.name}
accessToken: ''
address: 127.0.0.1:30007
ip: 127.0.0.1
port: 30007
logPath: logs/jeecg/job/jobhandler/
logRetentionDays: 30
#分布式锁配置
redisson:
address: 127.0.0.1:6379
password:
type: STANDALONE
enabled: true
# 百度开放API配置
baidu-api:
app-id: ??
api-key: ??
secret-key: ??
#cas单点登录
cas:
prefixUrl: http://cas.example.org:8443/cas
#Mybatis输出sql日志
logging:
level:
org.springframework.context.support.PostProcessorRegistrationDelegate: error
org.flywaydb: debug
org.jeecg.modules.system.mapper: info
org.jeecg.modules.demo.test.mapper: info
#swagger
knife4j:
#开启增强配置
enable: true
#开启生产环境屏蔽
production: false
basic:
enable: false
username: jeecg
password: jeecg1314
#第三方登录
justauth:
enabled: true
type:
GITHUB:
client-id: ??
client-secret: ??
redirect-uri: http://sso.test.com:8080/jeecg-boot/sys/thirdLogin/github/callback
WECHAT_ENTERPRISE:
client-id: ??
client-secret: ??
redirect-uri: http://sso.test.com:8080/jeecg-boot/sys/thirdLogin/wechat_enterprise/callback
agent-id: ??
DINGTALK:
client-id: ??
client-secret: ??
redirect-uri: http://sso.test.com:8080/jeecg-boot/sys/thirdLogin/dingtalk/callback
WECHAT_OPEN:
client-id: ??
client-secret: ??
redirect-uri: http://sso.test.com:8080/jeecg-boot/sys/thirdLogin/wechat_open/callback
cache:
type: default
prefix: 'demo::'
timeout: 1h
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-start\src\main\resources\application-dev.yml
| 2
|
请完成以下Java代码
|
protected void registerInterceptors(@NonNull final IModelValidationEngine engine)
{
engine.addModelValidator(new C_Queue_PackageProcessor());
engine.addModelValidator(new C_Queue_Processor());
engine.addModelValidator(new de.metas.lock.model.validator.Main());
engine.addModelValidator(new C_Async_Batch());
}
/**
* Init the async queue processor service on user login.
*/
@Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
if (!Ini.isSwingClient())
{
return;
}
final int delayMillis = getInitDelayMillis();
Services.get(IQueueProcessorExecutorService.class).init(delayMillis);
}
/**
* Destroy all queueud processors on user logout.
*/
|
@Override
public void beforeLogout(final MFSession session)
{
if (!Ini.isSwingClient())
{
return;
}
Services.get(IQueueProcessorExecutorService.class).removeAllQueueProcessors();
}
@Override
protected List<Topic> getAvailableUserNotificationsTopics()
{
return ImmutableList.of(
Async_Constants.WORKPACKAGE_ERROR_USER_NOTIFICATIONS_TOPIC,
DataImportService.USER_NOTIFICATIONS_TOPIC);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\model\validator\Main.java
| 1
|
请完成以下Java代码
|
public class ScriptCondition implements Condition {
protected final ExecutableScript script;
public ScriptCondition(ExecutableScript script) {
this.script = script;
}
@Override
public boolean evaluate(DelegateExecution execution) {
return evaluate(execution, execution);
}
@Override
public boolean evaluate(VariableScope scope, DelegateExecution execution) {
ScriptInvocation invocation = new ScriptInvocation(script, scope, execution);
try {
Context
.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(invocation);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ProcessEngineException(e);
}
Object result = invocation.getInvocationResult();
ensureNotNull("condition script returns null", "result", result);
ensureInstanceOf("condition script returns non-Boolean", "result", result, Boolean.class);
return (Boolean) result;
}
|
@Override
public boolean tryEvaluate(VariableScope scope, DelegateExecution execution) {
boolean result = false;
try {
result = evaluate(scope, execution);
} catch (ProcessEngineException pex) {
if (! (pex.getMessage().contains("No such property") ||
pex.getCause() instanceof ScriptEvaluationException) ) {
throw pex;
}
}
return result;
}
public ExecutableScript getScript() {
return script;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\ScriptCondition.java
| 1
|
请完成以下Java代码
|
private String getTableName()
{
return Services.get(IADTableDAO.class).retrieveTableName(getAD_Table_ID());
}
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (isActive())
{
setDataToLevel();
listChildRecords();
}
return true;
}
private String setDataToLevel()
{
String info = "-";
if (isClientLevelOnly())
{
StringBuilder sql = new StringBuilder("UPDATE ")
.append(getTableName())
.append(" SET AD_Org_ID=0 WHERE AD_Org_ID<>0 AND AD_Client_ID=?");
int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), getAD_Client_ID(), get_TrxName());
info = getTableName() + " set to Shared #" + no;
log.info(info);
}
else if (isOrgLevelOnly())
{
StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM ")
.append(getTableName())
.append(" WHERE AD_Org_ID=0 AND AD_Client_ID=?");
int no = DB.getSQLValue(get_TrxName(), sql.toString(), getAD_Client_ID());
info = getTableName() + " Shared records #" + no;
log.info(info);
}
return info;
} // setDataToLevel
private String listChildRecords()
{
final StringBuilder info = new StringBuilder();
String sql = "SELECT AD_Table_ID, TableName "
+ "FROM AD_Table t "
+ "WHERE AccessLevel='3' AND IsView='N'"
+ " AND EXISTS (SELECT * FROM AD_Column c "
+ "WHERE t.AD_Table_ID=c.AD_Table_ID"
+ " AND c.IsParent='Y'"
|
+ " AND c.ColumnName IN (SELECT ColumnName FROM AD_Column cc "
+ "WHERE cc.IsKey='Y' AND cc.AD_Table_ID=?))";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, getAD_Table_ID());
rs = pstmt.executeQuery();
while (rs.next())
{
String TableName = rs.getString(2);
if (info.length() != 0)
{
info.append(", ");
}
info.append(TableName);
}
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
}
return info.toString();
}
@Override
protected boolean beforeSave(boolean newRecord)
{
if (getAD_Org_ID() != 0)
{
setAD_Org_ID(0);
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClientShare.java
| 1
|
请完成以下Java代码
|
public class User {
private String userId;
private String username;
private String email;
private String contactNumber;
private String userType;
// Standard constructors, getters and setters
public User() {
}
public User(String userId, String username, String email, String contactNumber, String userType) {
this.userId = userId;
this.username = username;
this.email = email;
this.contactNumber = contactNumber;
this.userType = userType;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
|
public void setUsername(String userName) {
this.username = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-conversions-2\src\main\java\com\baeldung\modelmapper\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public HttpStatus getStatusCode() {
return getReason().getStatus();
}
/**
* Return the reason why the authorization exception was thrown.
* @return the reason
*/
public Reason getReason() {
return this.reason;
}
/**
* Reasons why the exception can be thrown.
*/
public enum Reason {
/**
* Access Denied.
*/
ACCESS_DENIED(HttpStatus.FORBIDDEN),
/**
* Invalid Audience.
*/
INVALID_AUDIENCE(HttpStatus.UNAUTHORIZED),
/**
* Invalid Issuer.
*/
INVALID_ISSUER(HttpStatus.UNAUTHORIZED),
/**
* Invalid Key ID.
*/
INVALID_KEY_ID(HttpStatus.UNAUTHORIZED),
/**
* Invalid Signature.
*/
INVALID_SIGNATURE(HttpStatus.UNAUTHORIZED),
/**
* Invalid Token.
*/
INVALID_TOKEN(HttpStatus.UNAUTHORIZED),
/**
* Missing Authorization.
*/
MISSING_AUTHORIZATION(HttpStatus.UNAUTHORIZED),
/**
* Token Expired.
*/
|
TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED),
/**
* Unsupported Token Signing Algorithm.
*/
UNSUPPORTED_TOKEN_SIGNING_ALGORITHM(HttpStatus.UNAUTHORIZED),
/**
* Service Unavailable.
*/
SERVICE_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE);
private final HttpStatus status;
Reason(HttpStatus status) {
this.status = status;
}
public HttpStatus getStatus() {
return this.status;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\CloudFoundryAuthorizationException.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected ListQueryParameterObject configureParameterizedQuery(Object parameter) {
return getTenantManager().configureQuery(parameter);
}
@Override
public DecisionDefinitionEntity findLatestDefinitionById(String id) {
return findDecisionDefinitionById(id);
}
@Override
public DecisionDefinitionEntity findLatestDefinitionByKey(String key) {
return findLatestDecisionDefinitionByKey(key);
}
@Override
public DecisionDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) {
return getDbEntityManager().getCachedEntity(DecisionDefinitionEntity.class, definitionId);
}
@Override
|
public DecisionDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return findLatestDecisionDefinitionByKeyAndTenantId(definitionKey, tenantId);
}
@Override
public DecisionDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) {
return findDecisionDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId);
}
@Override
public DecisionDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) {
return findDecisionDefinitionByKeyVersionTagAndTenantId(definitionKey, definitionVersionTag, tenantId);
}
@Override
public DecisionDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return findDecisionDefinitionByDeploymentAndKey(deploymentId, definitionKey);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionManager.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public TaskService taskServiceBean(ProcessEngine processEngine) {
return processEngine.getTaskService();
}
@Bean
@ConditionalOnMissingBean
public HistoryService historyServiceBean(ProcessEngine processEngine) {
return processEngine.getHistoryService();
}
@Bean
@ConditionalOnMissingBean
public ManagementService managementServiceBean(ProcessEngine processEngine) {
return processEngine.getManagementService();
}
@Bean
@ConditionalOnMissingBean
public DynamicBpmnService dynamicBpmnServiceBean(ProcessEngine processEngine) {
return processEngine.getDynamicBpmnService();
}
|
@Bean
@ConditionalOnMissingBean
public ProcessMigrationService processInstanceMigrationService(ProcessEngine processEngine) {
return processEngine.getProcessMigrationService();
}
@Bean
@ConditionalOnMissingBean
public FormService formServiceBean(ProcessEngine processEngine) {
return processEngine.getFormService();
}
@Bean
@ConditionalOnMissingBean
public IdentityService identityServiceBean(ProcessEngine processEngine) {
return processEngine.getIdentityService();
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\ProcessEngineServicesAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public MessagePayloadMappingProvider create(
Event bpmnEvent,
MessageEventDefinition messageEventDefinition,
ExpressionManager expressionManager
) {
List<FieldDeclaration> fieldDeclarations = createFieldDeclarations(
messageEventDefinition.getFieldExtensions(),
expressionManager
);
return new BpmnMessagePayloadMappingProvider(fieldDeclarations);
}
public List<FieldDeclaration> createFieldDeclarations(
List<FieldExtension> fieldList,
ExpressionManager expressionManager
) {
List<FieldDeclaration> fieldDeclarations = new ArrayList<FieldDeclaration>();
for (FieldExtension fieldExtension : fieldList) {
FieldDeclaration fieldDeclaration = null;
if (StringUtils.isNotEmpty(fieldExtension.getExpression())) {
fieldDeclaration = new FieldDeclaration(
fieldExtension.getFieldName(),
Expression.class.getName(),
|
expressionManager.createExpression(fieldExtension.getExpression())
);
} else {
fieldDeclaration = new FieldDeclaration(
fieldExtension.getFieldName(),
Expression.class.getName(),
new FixedValue(fieldExtension.getStringValue())
);
}
fieldDeclarations.add(fieldDeclaration);
}
return fieldDeclarations;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\delegate\BpmnMessagePayloadMappingProviderFactory.java
| 1
|
请完成以下Java代码
|
public void removeTransientVariable(String variableName) {
if (transientVariabes != null && transientVariabes.containsKey(variableName)) {
removeTransientVariableLocal(variableName);
return;
}
VariableScopeImpl parentVariableScope = getParentVariableScope();
if (parentVariableScope != null) {
parentVariableScope.removeTransientVariable(variableName);
}
}
@Override
public void removeTransientVariables() {
removeTransientVariablesLocal();
VariableScopeImpl parentVariableScope = getParentVariableScope();
if (parentVariableScope != null) {
parentVariableScope.removeTransientVariablesLocal();
}
}
// getters and setters //////////////////////////////////////////////////////
public ELContext getCachedElContext() {
return cachedElContext;
}
public void setCachedElContext(ELContext cachedElContext) {
this.cachedElContext = cachedElContext;
}
public String getId() {
|
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public <T> T getVariable(String variableName, Class<T> variableClass) {
return variableClass.cast(getVariable(variableName));
}
@Override
public <T> T getVariableLocal(String variableName, Class<T> variableClass) {
return variableClass.cast(getVariableLocal(variableName));
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\VariableScopeImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Flux<User> getUsers() {
return userDao.findAll();
}
public Mono<User> getUser(String id) {
return this.userDao.findById(id);
}
/**
* 新增和修改都是 save方法,
* id 存在为修改,id 不存在为新增
*/
public Mono<User> createUser(User user) {
return userDao.save(user);
}
public Mono<Void> deleteUser(String id) {
return this.userDao.findById(id)
.flatMap(user -> this.userDao.delete(user));
}
public Mono<User> updateUser(String id, User user) {
return this.userDao.findById(id)
.flatMap(u -> {
u.setName(user.getName());
u.setAge(user.getAge());
u.setDescription(user.getDescription());
return this.userDao.save(u);
});
}
public Flux<User> getUserByAge(Integer from, Integer to) {
return this.userDao.findByAgeBetween(from, to);
}
public Flux<User> getUserByName(String name) {
return this.userDao.findByNameEquals(name);
}
public Flux<User> getUserByDescription(String description) {
return this.userDao.findByDescriptionIsLike(description);
|
}
/**
* 分页查询,只返回分页后的数据,count值需要通过 getUserByConditionCount
* 方法获取
*/
public Flux<User> getUserByCondition(int size, int page, User user) {
Query query = getQuery(user);
Sort sort = new Sort(Sort.Direction.DESC, "age");
Pageable pageable = PageRequest.of(page, size, sort);
return template.find(query.with(pageable), User.class);
}
/**
* 返回 count,配合 getUserByCondition使用
*/
public Mono<Long> getUserByConditionCount(User user) {
Query query = getQuery(user);
return template.count(query, User.class);
}
private Query getQuery(User user) {
Query query = new Query();
Criteria criteria = new Criteria();
if (!StringUtils.isEmpty(user.getName())) {
criteria.and("name").is(user.getName());
}
if (!StringUtils.isEmpty(user.getDescription())) {
criteria.and("description").regex(user.getDescription());
}
query.addCriteria(criteria);
return query;
}
}
|
repos\SpringAll-master\58.Spring-Boot-WebFlux-crud\src\main\java\com\example\webflux\service\UserService.java
| 2
|
请完成以下Java代码
|
public int deleteJobsByEntityId(TenantId tenantId, EntityId entityId) { // TODO: cancel all jobs for this entity
return jobDao.removeByEntityId(tenantId, entityId);
}
private Job findForUpdate(TenantId tenantId, JobId jobId) {
return jobDao.findByIdForUpdate(tenantId, jobId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findJobById(tenantId, (JobId) entityId));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(jobDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
|
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
jobDao.removeById(tenantId, id.getId());
}
@Override
public void deleteByTenantId(TenantId tenantId) {
jobDao.removeByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.JOB;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\job\DefaultJobService.java
| 1
|
请完成以下Java代码
|
public static XForwardedRemoteAddressResolver maxTrustedIndex(int maxTrustedIndex) {
Assert.isTrue(maxTrustedIndex > 0, "An index greater than 0 is required");
return new XForwardedRemoteAddressResolver(maxTrustedIndex);
}
/**
* The X-Forwarded-For header contains a comma separated list of IP addresses. This
* method parses those IP addresses into a list. If no X-Forwarded-For header is
* found, an empty list is returned. If multiple X-Forwarded-For headers are found, an
* empty list is returned out of caution.
* @return The parsed values of the X-Forwarded-Header.
*/
@Override
public InetSocketAddress resolve(ServerWebExchange exchange) {
List<String> xForwardedValues = extractXForwardedValues(exchange);
if (!xForwardedValues.isEmpty()) {
int index = Math.max(0, xForwardedValues.size() - maxTrustedIndex);
return new InetSocketAddress(xForwardedValues.get(index), 0);
}
return defaultRemoteIpResolver.resolve(exchange);
|
}
private List<String> extractXForwardedValues(ServerWebExchange exchange) {
List<String> xForwardedValues = exchange.getRequest().getHeaders().get(X_FORWARDED_FOR);
if (xForwardedValues == null || xForwardedValues.isEmpty()) {
return Collections.emptyList();
}
if (xForwardedValues.size() > 1) {
log.warn("Multiple X-Forwarded-For headers found, discarding all");
return Collections.emptyList();
}
String[] values = StringUtils.tokenizeToStringArray(xForwardedValues.get(0), ",");
if (values.length == 1 && !StringUtils.hasText(values[0])) {
return Collections.emptyList();
}
return Arrays.asList(values);
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ipresolver\XForwardedRemoteAddressResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<Long> getDeptIds(UserDto user) {
String key = CacheKey.DATA_USER + user.getId();
List<Long> ids = redisUtils.getList(key, Long.class);
if (CollUtil.isEmpty(ids)) {
// 用于存储部门id
Set<Long> deptIds = new HashSet<>();
// 查询用户角色
List<RoleSmallDto> roleSet = roleService.findByUsersId(user.getId());
// 获取对应的部门ID
for (RoleSmallDto role : roleSet) {
DataScopeEnum dataScopeEnum = DataScopeEnum.find(role.getDataScope());
switch (Objects.requireNonNull(dataScopeEnum)) {
case THIS_LEVEL:
deptIds.add(user.getDept().getId());
break;
case CUSTOMIZE:
deptIds.addAll(getCustomize(deptIds, role));
break;
default:
return new ArrayList<>();
}
}
ids = new ArrayList<>(deptIds);
redisUtils.set(key, ids, 1, TimeUnit.DAYS);
}
|
return new ArrayList<>(ids);
}
/**
* 获取自定义的数据权限
* @param deptIds 部门ID
* @param role 角色
* @return 数据权限ID
*/
public Set<Long> getCustomize(Set<Long> deptIds, RoleSmallDto role){
Set<Dept> depts = deptService.findByRoleId(role.getId());
for (Dept dept : depts) {
deptIds.add(dept.getId());
List<Dept> deptChildren = deptService.findByPid(dept.getId());
if (CollUtil.isNotEmpty(deptChildren)) {
deptIds.addAll(deptService.getDeptChildren(deptChildren));
}
}
return deptIds;
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DataServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void init(List<TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgs) {
super.init(msgs);
initMaps();
}
@Override
public void submitAttempt(BiConsumer<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgConsumer) {
this.msgConsumer = msgConsumer;
entityIdToListMap.forEach((entityId, queue) -> {
IdMsgPair<TransportProtos.ToRuleEngineMsg> msg = queue.peek();
if (msg != null) {
msgConsumer.accept(msg.uuid, msg.msg);
}
});
}
@Override
public void update(ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> reprocessMap) {
super.update(reprocessMap);
initMaps();
}
@Override
protected void doOnSuccess(UUID id) {
EntityId entityId = msgToEntityIdMap.get(id);
if (entityId != null) {
Queue<IdMsgPair<TransportProtos.ToRuleEngineMsg>> queue = entityIdToListMap.get(entityId);
if (queue != null) {
IdMsgPair<TransportProtos.ToRuleEngineMsg> next = null;
synchronized (queue) {
IdMsgPair<TransportProtos.ToRuleEngineMsg> expected = queue.peek();
if (expected != null && expected.uuid.equals(id)) {
queue.poll();
next = queue.peek();
}
|
}
if (next != null) {
msgConsumer.accept(next.uuid, next.msg);
}
}
}
}
private void initMaps() {
msgToEntityIdMap.clear();
entityIdToListMap.clear();
for (IdMsgPair<TransportProtos.ToRuleEngineMsg> pair : orderedMsgList) {
EntityId entityId = getEntityId(pair.msg.getValue());
if (entityId != null) {
msgToEntityIdMap.put(pair.uuid, entityId);
entityIdToListMap.computeIfAbsent(entityId, id -> new LinkedList<>()).add(pair);
}
}
}
protected abstract EntityId getEntityId(TransportProtos.ToRuleEngineMsg msg);
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\SequentialByEntityIdTbRuleEngineSubmitStrategy.java
| 2
|
请完成以下Java代码
|
public long getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + (int) (id ^ (id >>> 32));
result = (prime * result) + ((name == null) ? 0 : name.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;
}
final Possession other = (Possession) obj;
if (id != other.id) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Possession.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected TbQueueConsumer<TbProtoQueueMsg<ToCalculatedFieldNotificationMsg>> createNotificationsConsumer() {
return queueFactory.createToCalculatedFieldNotificationMsgConsumer();
}
@Override
protected void handleNotification(UUID id, TbProtoQueueMsg<ToCalculatedFieldNotificationMsg> msg, TbCallback callback) {
ToCalculatedFieldNotificationMsg toCfNotification = msg.getValue();
if (toCfNotification.hasLinkedTelemetryMsg()) {
forwardToActorSystem(toCfNotification.getLinkedTelemetryMsg(), callback);
}
}
@EventListener
public void handleComponentLifecycleEvent(ComponentLifecycleMsg event) {
if (event.getEntityId().getEntityType() == EntityType.TENANT) {
if (event.getEvent() == ComponentLifecycleEvent.DELETED) {
Set<TopicPartitionInfo> partitions = stateService.getPartitions();
if (CollectionUtils.isEmpty(partitions)) {
return;
}
stateService.delete(partitions.stream()
.filter(tpi -> tpi.getTenantId().isPresent() && tpi.getTenantId().get().equals(event.getTenantId()))
.collect(Collectors.toSet()));
}
}
}
private void forwardToActorSystem(CalculatedFieldTelemetryMsgProto msg, TbCallback callback) {
var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB());
|
var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB()));
actorContext.tell(new CalculatedFieldTelemetryMsg(tenantId, entityId, msg, callback));
}
private void forwardToActorSystem(CalculatedFieldLinkedTelemetryMsgProto linkedMsg, TbCallback callback) {
var msg = linkedMsg.getMsg();
var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB());
var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB()));
actorContext.tell(new CalculatedFieldLinkedTelemetryMsg(tenantId, entityId, linkedMsg, callback));
}
private TenantId toTenantId(long tenantIdMSB, long tenantIdLSB) {
return TenantId.fromUUID(new UUID(tenantIdMSB, tenantIdLSB));
}
@Override
protected void stopConsumers() {
super.stopConsumers();
stateService.stop(); // eventConsumer will be stopped by stateService
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbCalculatedFieldConsumerService.java
| 2
|
请完成以下Java代码
|
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 Increment.
@param IncrementNo
The number to increment the last document number by
*/
public void setIncrementNo (int IncrementNo)
{
set_Value (COLUMNNAME_IncrementNo, Integer.valueOf(IncrementNo));
}
/** Get Increment.
@return The number to increment the last document number by
*/
public int getIncrementNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IncrementNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Serial No Control.
@param M_SerNoCtl_ID
Product Serial Number Control
*/
public void setM_SerNoCtl_ID (int M_SerNoCtl_ID)
{
if (M_SerNoCtl_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, Integer.valueOf(M_SerNoCtl_ID));
}
/** Get Serial No Control.
@return Product Serial Number Control
*/
public int getM_SerNoCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
|
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Prefix.
@param Prefix
Prefix before the sequence number
*/
public void setPrefix (String Prefix)
{
set_Value (COLUMNNAME_Prefix, Prefix);
}
/** Get Prefix.
@return Prefix before the sequence number
*/
public String getPrefix ()
{
return (String)get_Value(COLUMNNAME_Prefix);
}
/** Set Start No.
@param StartNo
Starting number/position
*/
public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suffix.
@param Suffix
Suffix after the number
*/
public void setSuffix (String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
/** Get Suffix.
@return Suffix after the number
*/
public String getSuffix ()
{
return (String)get_Value(COLUMNNAME_Suffix);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_SerNoCtl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CredentialController {
@Autowired
CredentialService credentialService;
@PostMapping("/credentials")
public ResponseEntity<String> generatePassword(@RequestBody String credentialName) {
return new ResponseEntity<>(credentialService.generatePassword(credentialName), HttpStatus.OK);
}
@PutMapping("/credentials")
public ResponseEntity<String> writeJSONCredential(@RequestBody Credential secret) {
return new ResponseEntity<>(credentialService.writeCredential(secret), HttpStatus.OK);
}
@PostMapping("/credentials/rotate")
public ResponseEntity<String> rotatePassword(@RequestBody String credentialName) {
return new ResponseEntity<>(credentialService.rotatePassword(credentialName), HttpStatus.OK);
}
@DeleteMapping("/credentials")
public ResponseEntity<String> deletePassword(@RequestBody String credentialName) {
|
return new ResponseEntity<>(credentialService.deletePassword(credentialName), HttpStatus.OK);
}
@GetMapping("/credentials")
public ResponseEntity<String> getPassword(@RequestBody String credentialName) {
return new ResponseEntity<>(credentialService.getPassword(credentialName), HttpStatus.OK);
}
@PostMapping("/permissions")
public ResponseEntity<CredentialPermission> addPermission(@RequestBody String credentialName) {
return new ResponseEntity<>(credentialService.addCredentialPermission(credentialName), HttpStatus.OK);
}
@GetMapping("/permissions")
public ResponseEntity<CredentialPermission> getPermission(@RequestBody String credentialName) {
return new ResponseEntity<>(credentialService.getCredentialPermission(credentialName), HttpStatus.OK);
}
}
|
repos\tutorials-master\spring-credhub\src\main\java\com\baeldung\controller\CredentialController.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
|
public Integer getArticleCount() {
return articleCount;
}
public void setArticleCount(Integer articleCount) {
this.articleCount = articleCount;
}
public Boolean isActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-mongodb\src\main\java\com\baeldung\model\Author.java
| 1
|
请完成以下Java代码
|
public void setPackageNetTotal (final @Nullable BigDecimal PackageNetTotal)
{
set_Value (COLUMNNAME_PackageNetTotal, PackageNetTotal);
}
@Override
public BigDecimal getPackageNetTotal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageNetTotal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPackageWeight (final @Nullable BigDecimal PackageWeight)
{
set_Value (COLUMNNAME_PackageWeight, PackageWeight);
}
@Override
public BigDecimal getPackageWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setReceivedInfo (final @Nullable java.lang.String ReceivedInfo)
{
set_Value (COLUMNNAME_ReceivedInfo, ReceivedInfo);
}
@Override
public java.lang.String getReceivedInfo()
{
return get_ValueAsString(COLUMNNAME_ReceivedInfo);
}
@Override
public void setShipDate (final @Nullable java.sql.Timestamp ShipDate)
{
set_Value (COLUMNNAME_ShipDate, ShipDate);
}
|
@Override
public java.sql.Timestamp getShipDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ShipDate);
}
@Override
public void setTrackingInfo (final @Nullable java.lang.String TrackingInfo)
{
set_Value (COLUMNNAME_TrackingInfo, TrackingInfo);
}
@Override
public java.lang.String getTrackingInfo()
{
return get_ValueAsString(COLUMNNAME_TrackingInfo);
}
@Override
public void setTrackingURL (final @Nullable java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
@Override
public java.lang.String getTrackingURL()
{
return get_ValueAsString(COLUMNNAME_TrackingURL);
}
@Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Package.java
| 1
|
请完成以下Java代码
|
private InvoiceRule getDefaultInvoiceRule()
{
final String invoiceRule = sysConfigBL.getValue(SYSCONFIG_DEFAULT_INVOICE_RULE, X_C_Order.INVOICERULE_AfterDelivery);
return StringUtils.trimBlankToOptional(invoiceRule)
.map(InvoiceRule::ofCode)
.orElse(InvoiceRule.AfterDelivery);
}
private void setIncoterms(
@NonNull final I_C_BPartner bPartnerRecord,
@NonNull final I_C_BP_Group bpGroup,
@Nullable final I_C_BP_Group bpParentGroup,
@NonNull final OrgId orgId,
final Function<I_C_BPartner, Integer> bpartnerIncotermsIdGetter,
final Function<I_C_BP_Group, Integer> bpGroupIncotermsIdGetter,
final Function<I_C_BPartner, String> bpartnerLocationGetter,
final Function<I_C_BP_Group, String> bpGroupLocationGetter,
final Consumer<Incoterms> incotermsConsumer)
{
final Incoterms incoterms = getEffectiveValue(
bPartnerRecord, bpGroup, bpParentGroup,
bpartnerIncotermsIdGetter,
bpGroupIncotermsIdGetter,
this::getIncoterms,
() -> incotermsRepository.getDefaultIncoterms(orgId));
if (incoterms == null)
{
return;
}
final String location = getEffectiveValue(
bPartnerRecord, bpGroup, bpParentGroup,
bpartnerLocationGetter,
bpGroupLocationGetter,
StringUtils::trimBlankToNull,
() -> getDefaultIncotermsLocation(orgId));
incotermsConsumer.accept(incoterms.withLocationEffective(location));
}
@Nullable
|
private Incoterms getIncoterms(final int incotermsId)
{
final IncotermsId id = IncotermsId.ofRepoIdOrNull(incotermsId);
if (id == null)
{
return null;
}
return incotermsRepository.getById(id);
}
@Nullable
private String getDefaultIncotermsLocation(@NonNull final OrgId orgId)
{
final Incoterms incoterms = incotermsRepository.getDefaultIncoterms(orgId);
if (incoterms == null)
{
return null;
}
return StringUtils.trimBlankToNull(incoterms.getDefaultLocation());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\effective\BPartnerEffectiveBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SumUpTransactionStatusChangedEvent
{
@NonNull SumUpTransaction trx;
@Nullable SumUpTransaction trxPrev;
public static SumUpTransactionStatusChangedEvent ofNewTransaction(@NonNull final SumUpTransaction trx)
{
return builderFrom(trx).build();
}
public static SumUpTransactionStatusChangedEvent ofChangedTransaction(
@NonNull final SumUpTransaction trx,
@NonNull final SumUpTransaction trxPrev)
{
return builderFrom(trx)
.trxPrev(trxPrev)
.build();
}
private static SumUpTransactionStatusChangedEventBuilder builderFrom(final @NonNull SumUpTransaction trx)
|
{
return builder().trx(trx);
}
@NonNull
public ClientId getClientId() {return trx.getClientAndOrgId().getClientId();}
@NonNull
public OrgId getOrgId() {return trx.getClientAndOrgId().getOrgId();}
@NonNull
public SumUpTransactionStatus getStatusNew() {return trx.getStatus();}
@Nullable
public SumUpPOSRef getPosRef() {return trx.getPosRef();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpTransactionStatusChangedEvent.java
| 2
|
请完成以下Java代码
|
public RestartProcessInstanceBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery query) {
this.query = query;
return this;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return query;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) {
this.instructions = instructions;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public RestartProcessInstanceBuilder processInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds.addAll(processInstanceIds);
return this;
}
@Override
public RestartProcessInstanceBuilder initialSetOfVariables() {
this.initialVariables = true;
return this;
}
public boolean isInitialVariables() {
return initialVariables;
|
}
@Override
public RestartProcessInstanceBuilder skipCustomListeners() {
this.skipCustomListeners = true;
return this;
}
@Override
public RestartProcessInstanceBuilder skipIoMappings() {
this.skipIoMappings = true;
return this;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
@Override
public RestartProcessInstanceBuilder withoutBusinessKey() {
withoutBusinessKey = true;
return this;
}
public boolean isWithoutBusinessKey() {
return withoutBusinessKey;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstanceBuilderImpl.java
| 1
|
请完成以下Java代码
|
public void setDescription_Customized (final @Nullable java.lang.String Description_Customized)
{
set_Value (COLUMNNAME_Description_Customized, Description_Customized);
}
@Override
public java.lang.String getDescription_Customized()
{
return get_ValueAsString(COLUMNNAME_Description_Customized);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setIsUseCustomization (final boolean IsUseCustomization)
{
set_Value (COLUMNNAME_IsUseCustomization, IsUseCustomization);
}
@Override
public boolean isUseCustomization()
{
return get_ValueAsBoolean(COLUMNNAME_IsUseCustomization);
}
@Override
public void setMobile_Application_ID (final int Mobile_Application_ID)
{
if (Mobile_Application_ID < 1)
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID);
}
@Override
public int getMobile_Application_ID()
|
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setName_Customized (final @Nullable java.lang.String Name_Customized)
{
set_Value (COLUMNNAME_Name_Customized, Name_Customized);
}
@Override
public java.lang.String getName_Customized()
{
return get_ValueAsString(COLUMNNAME_Name_Customized);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Trl.java
| 1
|
请完成以下Java代码
|
public final class PathPatternParserServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private static final Log logger = LogFactory.getLog(PathPatternParserServerWebExchangeMatcher.class);
private final PathPattern pattern;
private final @Nullable HttpMethod method;
public PathPatternParserServerWebExchangeMatcher(PathPattern pattern) {
this(pattern, null);
}
public PathPatternParserServerWebExchangeMatcher(PathPattern pattern, @Nullable HttpMethod method) {
Assert.notNull(pattern, "pattern cannot be null");
this.pattern = pattern;
this.method = method;
}
public PathPatternParserServerWebExchangeMatcher(String pattern, @Nullable HttpMethod method) {
Assert.notNull(pattern, "pattern cannot be null");
this.pattern = parse(pattern);
this.method = method;
}
public PathPatternParserServerWebExchangeMatcher(String pattern) {
this(pattern, null);
}
private PathPattern parse(String pattern) {
PathPatternParser parser = PathPatternParser.defaultInstance;
pattern = parser.initFullPathPattern(pattern);
return parser.parse(pattern);
}
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
ServerHttpRequest request = exchange.getRequest();
PathContainer path = request.getPath().pathWithinApplication();
if (this.method != null && !this.method.equals(request.getMethod())) {
return MatchResult.notMatch().doOnNext((result) -> {
if (logger.isDebugEnabled()) {
|
logger.debug("Request '" + request.getMethod() + " " + path + "' doesn't match '" + this.method
+ " " + this.pattern.getPatternString() + "'");
}
});
}
PathPattern.PathMatchInfo pathMatchInfo = this.pattern.matchAndExtract(path);
if (pathMatchInfo == null) {
return MatchResult.notMatch().doOnNext((result) -> {
if (logger.isDebugEnabled()) {
logger.debug("Request '" + request.getMethod() + " " + path + "' doesn't match '" + this.method
+ " " + this.pattern.getPatternString() + "'");
}
});
}
Map<String, String> pathVariables = pathMatchInfo.getUriVariables();
Map<String, Object> variables = new HashMap<>(pathVariables);
if (logger.isDebugEnabled()) {
logger
.debug("Checking match of request : '" + path + "'; against '" + this.pattern.getPatternString() + "'");
}
return MatchResult.match(variables);
}
@Override
public String toString() {
return "PathMatcherServerWebExchangeMatcher{" + "pattern='" + this.pattern + '\'' + ", method=" + this.method
+ '}';
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\PathPatternParserServerWebExchangeMatcher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
// read - one
@Override
@Transactional(readOnly = true)
public T findOne(final long id) {
return getDao().findById(id).orElse(null);
}
// read - all
@Override
@Transactional(readOnly = true)
public List<T> findAll() {
return Lists.newArrayList(getDao().findAll());
}
@Override
public Page<T> findPaginated(final int page, final int size) {
return getDao().findAll(PageRequest.of(page, size));
}
// write
@Override
public T create(final T entity) {
return getDao().save(entity);
}
@Override
public T update(final T entity) {
|
return getDao().save(entity);
}
@Override
public void delete(final T entity) {
getDao().delete(entity);
}
@Override
public void deleteById(final long entityId) {
getDao().deleteById(entityId);
}
protected abstract PagingAndSortingRepository<T, Long> getDao();
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\services\impl\AbstractService.java
| 2
|
请完成以下Java代码
|
private PaySelectionId getPaySelectionId()
{
return PaySelectionId.ofRepoId(getRecord_ID());
}
private BPartnerId getBPartnerIdFromSelectedLines()
{
final PaySelectionId paySelectionId = getPaySelectionId();
final ImmutableSet<PaySelectionLineId> paySelectionLineIds = getSelectedIncludedRecordIds(I_C_PaySelectionLine.class, repoId -> PaySelectionLineId.ofRepoId(paySelectionId, repoId));
final ImmutableSet<BPartnerId> bpartnerIds = paySelectionBL.getBPartnerIdsFromPaySelectionLineIds(paySelectionLineIds);
if (bpartnerIds.isEmpty())
{
throw new AdempiereException("No BPartners");
}
else if (bpartnerIds.size() != 1)
{
throw new AdempiereException("More than one BPartner selected");
}
else
{
|
return bpartnerIds.iterator().next();
}
}
private void openViewForBPartner(final BPartnerId bpartnerId)
{
final ViewId viewId = viewsFactory.createView(
CreateViewRequest.builder(PaymentsViewFactory.WINDOW_ID)
.setParameter(PaymentsViewFactory.PARAMETER_TYPE_BPARTNER_ID, bpartnerId)
.build())
.getViewId();
getResult().setWebuiViewToOpen(WebuiViewToOpen.modalOverlay(viewId.getViewId()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentView_Launcher_From_PaySelection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setPRICETYPE(String value) {
this.pricetype = value;
}
/**
* Gets the value of the pricebasis property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPRICEBASIS() {
return pricebasis;
}
/**
* Sets the value of the pricebasis property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRICEBASIS(String value) {
this.pricebasis = value;
}
/**
* Gets the value of the pricemeasureunit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPRICEMEASUREUNIT() {
return pricemeasureunit;
}
/**
* Sets the value of the pricemeasureunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRICEMEASUREUNIT(String value) {
this.pricemeasureunit = value;
|
}
/**
* Gets the value of the currency property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCY() {
return currency;
}
/**
* Sets the value of the currency property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCY(String value) {
this.currency = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DPRIC1.java
| 2
|
请完成以下Java代码
|
public Bar getBar() {
return bar;
}
public void setBar(final Bar bar) {
this.bar = bar;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
|
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Foo.java
| 1
|
请完成以下Java代码
|
public void setRecordId(Integer value) {
this.recordId = value;
}
/**
* Gets the value of the costUnit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCostUnit() {
return costUnit;
}
/**
* Sets the value of the costUnit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCostUnit(String value) {
this.costUnit = value;
}
|
/**
* Gets the value of the status property.
*
*/
public int getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
*/
public void setStatus(int value) {
this.status = 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\ValidationResultType.java
| 1
|
请完成以下Java代码
|
public DocumentPrintOptions mergeWithFallback(@NonNull final DocumentPrintOptions fallback)
{
if (fallback.isNone())
{
return this;
}
else if (isNone())
{
return fallback;
}
else
{
if (this == fallback)
{
throw new IllegalArgumentException("Merging with itself is not allowed");
}
final DocumentPrintOptions newFallback;
|
if (this.fallback != null)
{
newFallback = this.fallback.mergeWithFallback(fallback);
}
else
{
newFallback = fallback;
}
return !Objects.equals(this.fallback, newFallback)
? toBuilder().fallback(newFallback).build()
: this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentPrintOptions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
|
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
return "ExceptionMessage [timestamp=" + timestamp + ", status=" + status + ", error=" + error + ", message=" + message + ", path=" + path + "]";
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign-2\src\main\java\com\baeldung\cloud\openfeign\fileupload\config\ExceptionMessage.java
| 2
|
请完成以下Java代码
|
public boolean isTaxWithholding ()
{
Object oo = get_Value(COLUMNNAME_IsTaxWithholding);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Max Amount.
@param MaxAmt
Maximum Amount in invoice currency
*/
public void setMaxAmt (BigDecimal MaxAmt)
{
set_Value (COLUMNNAME_MaxAmt, MaxAmt);
}
/** Get Max Amount.
@return Maximum Amount in invoice currency
*/
public BigDecimal getMaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Min Amount.
@param MinAmt
Minimum Amount in invoice currency
*/
public void setMinAmt (BigDecimal MinAmt)
{
set_Value (COLUMNNAME_MinAmt, MinAmt);
}
/** Get Min Amount.
@return Minimum Amount in invoice currency
*/
public BigDecimal getMinAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** 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 Percent.
@param Percent
Percentage
*/
public void setPercent (BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
|
@return Percentage
*/
public BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Threshold max.
@param ThresholdMax
Maximum gross amount for withholding calculation (0=no limit)
*/
public void setThresholdMax (BigDecimal ThresholdMax)
{
set_Value (COLUMNNAME_ThresholdMax, ThresholdMax);
}
/** Get Threshold max.
@return Maximum gross amount for withholding calculation (0=no limit)
*/
public BigDecimal getThresholdMax ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ThresholdMax);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Threshold min.
@param Thresholdmin
Minimum gross amount for withholding calculation
*/
public void setThresholdmin (BigDecimal Thresholdmin)
{
set_Value (COLUMNNAME_Thresholdmin, Thresholdmin);
}
/** Get Threshold min.
@return Minimum gross amount for withholding calculation
*/
public BigDecimal getThresholdmin ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Thresholdmin);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Withholding.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setS_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Issue)
{
set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue);
}
@Override
public void setS_Issue_ID (final int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, S_Issue_ID);
}
@Override
public int getS_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Issue_ID);
|
}
@Override
public void setS_TimeBooking_ID (final int S_TimeBooking_ID)
{
if (S_TimeBooking_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, S_TimeBooking_ID);
}
@Override
public int getS_TimeBooking_ID()
{
return get_ValueAsInt(COLUMNNAME_S_TimeBooking_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_TimeBooking.java
| 2
|
请完成以下Spring Boot application配置
|
server:
port: 9090 #指定一个端口,避免和 XXL-JOB 调度中心的端口冲突。仅仅测试之用
# xxl-job
xxl:
job:
admin:
addresses: http://127.0.0.1:8080/xxl-job-admin # 调度中心部署跟地址 [选填]:如调度中心集群部署存在多个地址则用逗号分隔。执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调";为空则关闭自动注册;
executor:
appname: lab-28-executor # 执行器 AppName [选填]:执行器心跳注册分组依据;为空则关闭自动注册
ip: # 执行器IP [选填]:默认为空表示自动获取IP,多网卡时可手动设置指定IP,该IP不会绑定Host仅作为通讯实用;地址信息用于 "执行器注册" 和 "调度中心请求并触发任务";
port: 6666 # ### 执行器端口号 [选填]:小于等于0则自动获取;默认端口为9999,单机部署多个执行器时,注意要配置不同执行器端口;
logpath: /Users/yun
|
ai/logs/xxl-job/lab-28-executor # 执行器运行日志文件存储磁盘路径 [选填] :需要对该路径拥有读写权限;为空则使用默认路径;
logretentiondays: 30 # 执行器日志文件保存天数 [选填] : 过期日志自动清理, 限制值大于等于3时生效; 否则, 如-1, 关闭自动清理功能;
accessToken: yudaoyuanma # 执行器通讯TOKEN [选填]:非空时启用;
|
repos\SpringBoot-Labs-master\lab-28\lab-28-task-xxl-job\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
private BooleanWithReason checkTriggerMatching(@NonNull final BusinessRule rule, @NonNull final BusinessRuleTrigger trigger)
{
final BusinessRuleStopwatch stopwatch = logger.newStopwatch();
BooleanWithReason matching = BooleanWithReason.FALSE;
try
{
if (!trigger.isChangeTypeMatching(timing))
{
return BooleanWithReason.falseBecause("timing not matching");
}
matching = checkConditionMatching(trigger.getCondition());
}
catch (final Exception ex)
{
logger.debug("Failed evaluating trigger condition {}/{} for {}/{}", rule, trigger, sourceModel, timing, ex);
matching = BooleanWithReason.falseBecause(ex);
}
finally
{
logger.debug(stopwatch, "Checked if trigger is matching source: {}", matching);
}
|
return matching;
}
private BooleanWithReason checkConditionMatching(@Nullable final Validation condition)
{
return condition == null || recordMatcher.isRecordMatching(sourceModelRef, condition)
? BooleanWithReason.TRUE
: BooleanWithReason.FALSE;
}
private void enqueueToRecompute(@NonNull final BusinessRule rule, @NonNull final BusinessRuleTrigger trigger)
{
eventRepository.create(BusinessRuleEventCreateRequest.builder()
.clientAndOrgId(clientAndOrgId)
.triggeringUserId(triggeringUserId)
.recordRef(sourceModelRef)
.businessRuleId(rule.getId())
.triggerId(trigger.getId())
.build());
logger.debug("Enqueued event for re-computation");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\trigger\BusinessRuleFireTriggersCommand.java
| 1
|
请完成以下Java代码
|
public void onAction(String name, boolean isPressed, float tpf) {
if (name.equals("Rotate") && !isPressed) {
rotationEnabled = !rotationEnabled;
}
}
};
AnalogListener analogListener = new AnalogListener() {
@Override
public void onAnalog(String name, float value, float tpf) {
if (name.equals("Left")) {
rotation.rotate(0, -tpf, 0);
} else if (name.equals("Right")) {
rotation.rotate(0, tpf, 0);
}
|
}
};
inputManager.addListener(actionListener, "Rotate");
inputManager.addListener(analogListener, "Left", "Right");
}
@Override
public void simpleUpdate(float tpf) {
if (rotationEnabled) {
Spatial rotation = rootNode.getChild("rotation");
rotation.rotate(0, 0, tpf);
}
}
}
|
repos\tutorials-master\jmonkeyengine\src\main\java\com\baeldung\jmonkeyengine\UserInputApplication.java
| 1
|
请完成以下Java代码
|
public HttpStatus getHttpStatus() {
return httpStatus;
}
public Integer getStatus() {
return status;
}
/**
* Whether this status code is in the HTTP series
* {@link org.springframework.http.HttpStatus.Series#INFORMATIONAL}.
* @return <code>true</code> if status code is in the INFORMATIONAL http series
*/
public boolean is1xxInformational() {
return HttpStatus.Series.INFORMATIONAL.equals(getSeries());
}
/**
* Whether this status code is in the HTTP series
* {@link org.springframework.http.HttpStatus.Series#SUCCESSFUL}.
* @return <code>true</code> if status code is in the SUCCESSFUL http series
*/
public boolean is2xxSuccessful() {
return HttpStatus.Series.SUCCESSFUL.equals(getSeries());
}
/**
* Whether this status code is in the HTTP series
* {@link org.springframework.http.HttpStatus.Series#REDIRECTION}.
* @return <code>true</code> if status code is in the REDIRECTION http series
*/
public boolean is3xxRedirection() {
return HttpStatus.Series.REDIRECTION.equals(getSeries());
}
/**
* Whether this status code is in the HTTP series
* {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR}.
* @return <code>true</code> if status code is in the CLIENT_ERROR http series
*/
public boolean is4xxClientError() {
|
return HttpStatus.Series.CLIENT_ERROR.equals(getSeries());
}
/**
* Whether this status code is in the HTTP series
* {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR}.
* @return <code>true</code> if status code is in the SERVER_ERROR http series
*/
public boolean is5xxServerError() {
return HttpStatus.Series.SERVER_ERROR.equals(getSeries());
}
public HttpStatus.Series getSeries() {
if (httpStatus != null) {
return httpStatus.series();
}
if (status != null) {
return HttpStatus.Series.valueOf(status);
}
return null;
}
/**
* Whether this status code is in the HTTP series
* {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR} or
* {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR}.
* @return <code>true</code> if is either CLIENT_ERROR or SERVER_ERROR
*/
public boolean isError() {
return is4xxClientError() || is5xxServerError();
}
@Override
public String toString() {
return new ToStringCreator(this).append("httpStatus", httpStatus).append("status", status).toString();
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\HttpStatusHolder.java
| 1
|
请完成以下Java代码
|
public byte[] get(String key, int chunkSize, int chunk) {
try (RedisConnection connection = redisConnectionFactory.getConnection()) {
if (chunkSize == 0) {
return connection.get(toOtaPackageCacheKey(key));
}
int startIndex = chunkSize * chunk;
int endIndex = startIndex + chunkSize - 1;
return connection.getRange(toOtaPackageCacheKey(key), startIndex, endIndex);
}
}
@Override
public void put(String key, byte[] value) {
try (RedisConnection connection = redisConnectionFactory.getConnection()) {
|
connection.set(toOtaPackageCacheKey(key), value);
}
}
@Override
public void evict(String key) {
try (RedisConnection connection = redisConnectionFactory.getConnection()) {
connection.del(toOtaPackageCacheKey(key));
}
}
private byte[] toOtaPackageCacheKey(String key) {
return String.format("%s::%s", OTA_PACKAGE_DATA_CACHE, key).getBytes();
}
}
|
repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\ota\RedisOtaPackageDataCache.java
| 1
|
请完成以下Java代码
|
public int getK_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_K_CategoryValue getK_CategoryValue() throws RuntimeException
{
return (I_K_CategoryValue)MTable.get(getCtx(), I_K_CategoryValue.Table_Name)
.getPO(getK_CategoryValue_ID(), get_TrxName()); }
/** Set Category Value.
@param K_CategoryValue_ID
The value of the category
*/
public void setK_CategoryValue_ID (int K_CategoryValue_ID)
{
if (K_CategoryValue_ID < 1)
set_Value (COLUMNNAME_K_CategoryValue_ID, null);
else
set_Value (COLUMNNAME_K_CategoryValue_ID, Integer.valueOf(K_CategoryValue_ID));
}
/** Get Category Value.
@return The value of the category
*/
public int getK_CategoryValue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_CategoryValue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getK_CategoryValue_ID()));
}
public I_K_Entry getK_Entry() throws RuntimeException
{
return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name)
.getPO(getK_Entry_ID(), get_TrxName()); }
/** Set Entry.
@param K_Entry_ID
Knowledge Entry
*/
public void setK_Entry_ID (int K_Entry_ID)
{
if (K_Entry_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID));
}
/** Get Entry.
@return Knowledge Entry
*/
public int getK_Entry_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_EntryCategory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setInvolvedUser(String involvedUser) {
this.involvedUser = involvedUser;
}
public Boolean getSuspended() {
return suspended;
}
public void setSuspended(Boolean suspended) {
this.suspended = suspended;
}
public Boolean getIncludeProcessVariables() {
return includeProcessVariables;
}
public void setIncludeProcessVariables(Boolean includeProcessVariables) {
this.includeProcessVariables = includeProcessVariables;
}
public Collection<String> getIncludeProcessVariablesNames() {
return includeProcessVariablesNames;
}
public void setIncludeProcessVariablesNames(Collection<String> includeProcessVariablesNames) {
this.includeProcessVariablesNames = includeProcessVariablesNames;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class)
public List<QueryVariable> getVariables() {
return variables;
}
public void setVariables(List<QueryVariable> variables) {
this.variables = variables;
}
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 getParentCaseInstanceId() {
return parentCaseInstanceId;
}
public void setParentCaseInstanceId(String parentCaseInstanceId) {
this.parentCaseInstanceId = parentCaseInstanceId;
}
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLikeIgnoreCase() {
return tenantIdLikeIgnoreCase;
}
public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) {
this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getCallbackIds() {
return callbackIds;
}
public void setCallbackIds(Set<String> callbackIds) {
this.callbackIds = callbackIds;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceQueryRequest.java
| 2
|
请完成以下Java代码
|
public void stop() {
super.stop();
if (monitorExecutorService != null) {
monitorExecutorService.shutdownNow();
}
if (jsExecutor != null) {
jsExecutor.shutdownNow();
}
}
@Override
protected ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo scriptInfo, String jsScript) {
return jsExecutor.submit(() -> {
try {
evalLock.lock();
try {
if (useJsSandbox) {
sandbox.eval(jsScript);
} else {
engine.eval(jsScript);
}
} finally {
evalLock.unlock();
}
scriptInfoMap.put(scriptId, scriptInfo);
return scriptId;
} catch (ScriptException e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.COMPILATION, jsScript, e);
} catch (ScriptCPUAbuseException e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.TIMEOUT, jsScript, e);
} catch (Exception e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.OTHER, jsScript, e);
}
});
}
@Override
protected ListenableFuture<Object> doInvokeFunction(UUID scriptId, JsScriptInfo scriptInfo, Object[] args) {
return jsExecutor.submit(() -> {
try {
|
if (useJsSandbox) {
return sandbox.getSandboxedInvocable().invokeFunction(scriptInfo.getFunctionName(), args);
} else {
return ((Invocable) engine).invokeFunction(scriptInfo.getFunctionName(), args);
}
} catch (ScriptException e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.RUNTIME, null, e);
} catch (Exception e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.OTHER, null, e);
}
});
}
protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException {
if (useJsSandbox) {
sandbox.eval(scriptInfo.getFunctionName() + " = undefined;");
} else {
engine.eval(scriptInfo.getFunctionName() + " = undefined;");
}
}
}
|
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\NashornJsInvokeService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public InventoryItem addInventory(String sku, int quantity) {
return inventory.compute(sku, (k, v) -> {
if (v == null) {
return new InventoryItem(sku, quantity, 0);
} else {
return new InventoryItem(sku, v.quantity() + quantity, v.reserved());
}
});
}
public InventoryItem reserveInventory(String sku, int quantity) {
return inventory.compute(sku, (k, v) -> {
if (v == null) {
return new InventoryItem(sku, 0, quantity);
} else {
return new InventoryItem(sku, v.quantity(), v.reserved() + quantity);
}
});
}
public void confirmInventoryReservation(String sku, int quantity) {
inventory.compute(sku, (k, v) -> {
if (v == null) {
return new InventoryItem(sku, 0, 0);
} else {
return new InventoryItem(sku, v.quantity() - quantity, v.reserved() - quantity);
}
});
}
public void cancelInventoryReservation(String sku, int quantity) {
inventory.compute(sku, (k, v) -> {
if (v == null) {
|
return new InventoryItem(sku, 0, 0);
} else {
return new InventoryItem(sku, v.quantity(), v.reserved() - quantity);
}
});
}
public InventoryItem getInventory(String sku) {
return inventory.getOrDefault(sku, new InventoryItem(sku, 0, 0));
}
public record InventoryItem(String sku, int quantity, int reserved) {
}
}
|
repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\sboot\order\services\InventoryService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
@ApiModelProperty(example = "cmmn")
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@ApiModelProperty(example = "async-history")
public String getJobHandlerType() {
return jobHandlerType;
}
public void setJobHandlerType(String jobHandlerType) {
this.jobHandlerType = jobHandlerType;
}
@ApiModelProperty(example = "myCfg")
public String getJobHandlerConfiguration() {
return jobHandlerConfiguration;
}
public void setJobHandlerConfiguration(String jobHandlerConfiguration) {
this.jobHandlerConfiguration = jobHandlerConfiguration;
}
@ApiModelProperty(example = "myAdvancedCfg")
public String getAdvancedJobHandlerConfiguration() {
return advancedJobHandlerConfiguration;
}
public void setAdvancedJobHandlerConfiguration(String advancedJobHandlerConfiguration) {
this.advancedJobHandlerConfiguration = advancedJobHandlerConfiguration;
}
@ApiModelProperty(example = "custom value")
public String getCustomValues() {
|
return customValues;
}
public void setCustomValues(String customValues) {
this.customValues = customValues;
}
@ApiModelProperty(example = "node1")
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
@ApiModelProperty(example = "2023-06-03T22:05:05.474+0000")
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\HistoryJobResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Boolean getFailed() {
return failed;
}
public void setFailed(Boolean failed) {
this.failed = failed;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getTenantId() {
return tenantId;
}
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java
| 2
|
请完成以下Java代码
|
public void setProcessVariablesToTriggeredScope(Map<String, VariableValueDto> processVariablesToTriggeredScope) {
this.processVariablesToTriggeredScope = processVariablesToTriggeredScope;
}
public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public String getProcessInstanceId() {
return processInstanceId;
|
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public boolean isResultEnabled() {
return resultEnabled;
}
public void setResultEnabled(boolean resultEnabled) {
this.resultEnabled = resultEnabled;
}
public boolean isVariablesInResultEnabled() {
return variablesInResultEnabled;
}
public void setVariablesInResultEnabled(boolean variablesInResultEnabled) {
this.variablesInResultEnabled = variablesInResultEnabled;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\message\CorrelationMessageDto.java
| 1
|
请完成以下Java代码
|
public void setBusy (boolean busy)
{
if (busy == m_glassPane.isVisible())
return;
log.info("Busy=" + busy);
if (busy)
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
else
setCursor(Cursor.getDefaultCursor());
m_glassPane.setMessage(null);
m_glassPane.setVisible(busy);
m_glassPane.requestFocus();
} // setBusy
/**
* Set Busy Message.
*
* If you want to directly set a message, without any transaction, use {@link #setMessagePlain(String)}.
*
* @param AD_Message to be translated - null resets to default message.
*/
public final void setBusyMessage (final String AD_Message)
{
m_glassPane.setMessage(AD_Message);
}
/**
* Sets given busy message directly. No transaction or any other processing will be performed.
*
* @param message plain message to be set directly.
*/
public final void setBusyMessagePlain(final String message)
{
m_glassPane.setMessagePlain(message);
}
/**
* Set and start Busy Counter
* @param time in seconds
*/
public void setBusyTimer (int time)
{
m_glassPane.setBusyTimer (time);
} // setBusyTimer
/**
* Set Maximize Window
* @param max maximize
*/
public void setMaximize (boolean max)
{
m_maximize = max;
} // setMaximize
/**
* Form Window Opened.
* Maximize window if required
* @param evt event
*/
private void formWindowOpened(java.awt.event.WindowEvent evt)
{
if (m_maximize == true)
{
super.setVisible(true);
super.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
} // formWindowOpened
|
// Add window and tab no called from
public void setProcessInfo(ProcessInfo pi)
{
m_pi = pi;
}
public ProcessInfo getProcessInfo()
{
return m_pi;
}
// End
/**
* Start Batch
* @param process
* @return running thread
*/
public Thread startBatch (final Runnable process)
{
Thread worker = new Thread()
{
@Override
public void run()
{
setBusy(true);
process.run();
setBusy(false);
}
};
worker.start();
return worker;
} // startBatch
/**
* @return Returns the AD_Form_ID.
*/
public int getAD_Form_ID ()
{
return p_AD_Form_ID;
} // getAD_Window_ID
public int getWindowNo()
{
return m_WindowNo;
}
/**
* @return Returns the manuBar
*/
public JMenuBar getMenu()
{
return menuBar;
}
public void showFormWindow()
{
if (m_panel instanceof FormPanel2)
{
((FormPanel2)m_panel).showFormWindow(m_WindowNo, this);
}
else
{
AEnv.showCenterScreenOrMaximized(this);
}
}
} // FormFrame
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\FormFrame.java
| 1
|
请完成以下Java代码
|
public Region getQuadrant(int quadrantIndex) {
float quadrantWidth = (this.x2 - this.x1) / 2;
float quadrantHeight = (this.y2 - this.y1) / 2;
// 0=SW, 1=NW, 2=NE, 3=SE
switch (quadrantIndex) {
case 0:
return new Region(x1, y1, x1 + quadrantWidth, y1 + quadrantHeight);
case 1:
return new Region(x1, y1 + quadrantHeight, x1 + quadrantWidth, y2);
case 2:
return new Region(x1 + quadrantWidth, y1 + quadrantHeight, x2, y2);
case 3:
return new Region(x1 + quadrantWidth, y1, x2, y1 + quadrantHeight);
}
return null;
}
public boolean containsPoint(Point point) {
// Consider left and top side to be inclusive for points on border
return point.getX() >= this.x1
&& point.getX() < this.x2
&& point.getY() >= this.y1
&& point.getY() < this.y2;
}
public boolean doesOverlap(Region testRegion) {
// Is test region completely to left of my region?
if (testRegion.getX2() < this.getX1()) {
return false;
}
// Is test region completely to right of my region?
if (testRegion.getX1() > this.getX2()) {
return false;
}
// Is test region completely above my region?
if (testRegion.getY1() > this.getY2()) {
return false;
}
// Is test region completely below my region?
if (testRegion.getY2() < this.getY1()) {
return false;
}
return true;
|
}
@Override
public String toString() {
return "[Region (x1=" + x1 + ", y1=" + y1 + "), (x2=" + x2 + ", y2=" + y2 + ")]";
}
public float getX1() {
return x1;
}
public float getY1() {
return y1;
}
public float getX2() {
return x2;
}
public float getY2() {
return y2;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\quadtree\Region.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getRefundReferenceId()
{
return refundReferenceId;
}
public void setRefundReferenceId(String refundReferenceId)
{
this.refundReferenceId = refundReferenceId;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
LineItemRefund lineItemRefund = (LineItemRefund)o;
return Objects.equals(this.amount, lineItemRefund.amount) &&
Objects.equals(this.refundDate, lineItemRefund.refundDate) &&
Objects.equals(this.refundId, lineItemRefund.refundId) &&
Objects.equals(this.refundReferenceId, lineItemRefund.refundReferenceId);
}
@Override
public int hashCode()
{
|
return Objects.hash(amount, refundDate, refundId, refundReferenceId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class LineItemRefund {\n");
sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" refundDate: ").append(toIndentedString(refundDate)).append("\n");
sb.append(" refundId: ").append(toIndentedString(refundId)).append("\n");
sb.append(" refundReferenceId: ").append(toIndentedString(refundReferenceId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LineItemRefund.java
| 2
|
请完成以下Java代码
|
public ProcessEngineException exceptionWhileParsingCycleExpresison(String duedateDescription, Exception e) {
return new ProcessEngineException(exceptionMessage(
"026",
"Exception while parsing cycle expression '{}': {}", duedateDescription, e.getMessage()), e);
}
public ProcessEngineException exceptionWhileResolvingDuedate(String duedate, Exception e) {
return new ProcessEngineException(exceptionMessage(
"027",
"Exception while resolving duedate '{}': {}", duedate, e.getMessage()), e);
}
public Exception cannotParseDuration(String expressions) {
return new ProcessEngineException(exceptionMessage(
"028",
"Cannot parse duration '{}'.", expressions));
}
public void logParsingRetryIntervals(String intervals, Exception e) {
logWarn(
"029",
"Exception while parsing retry intervals '{}'", intervals, e.getMessage(), e);
}
public void logJsonException(Exception e) {
logDebug(
"030",
"Exception while parsing JSON: {}", e.getMessage(), e);
}
public void logAccessExternalSchemaNotSupported(Exception e) {
logDebug(
"031",
"Could not restrict external schema access. "
+ "This indicates that this is not supported by your JAXP implementation: {}",
e.getMessage());
|
}
public void logMissingPropertiesFile(String file) {
logWarn("032", "Could not find the '{}' file on the classpath. " +
"If you have removed it, please restore it.", file);
}
public ProcessEngineException exceptionDuringFormParsing(String cause, String resourceName) {
return new ProcessEngineException(
exceptionMessage("033", "Could not parse Camunda Form resource {}. Cause: {}", resourceName, cause));
}
public void debugCouldNotResolveCallableElement(
String callingProcessDefinitionId,
String activityId,
Throwable cause) {
logDebug("046", "Could not resolve a callable element for activity {} in process {}. Reason: {}",
activityId,
callingProcessDefinitionId,
cause.getMessage());
}
public ProcessEngineException exceptionWhileSettingXxeProcessing(Throwable cause) {
return new ProcessEngineException(exceptionMessage(
"047",
"Exception while configuring XXE processing: {}", cause.getMessage()), cause);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\EngineUtilLogger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String validatePhoneTwilioNumber(String phoneNumber) throws SmsParseException {
phoneNumber = phoneNumber.trim();
if (!E_164_PHONE_NUMBER_PATTERN.matcher(phoneNumber).matches() && !PHONE_NUMBERS_SID_MESSAGE_SERVICE_SID.matcher(phoneNumber).matches()) {
throw new SmsParseException("Invalid phone number format. Phone number must be in E.164 format/Phone Number's SID/Messaging Service SID.");
}
return phoneNumber;
}
public TwilioSmsSender(TwilioSmsProviderConfiguration config) {
if (StringUtils.isEmpty(config.getAccountSid()) || StringUtils.isEmpty(config.getAccountToken()) || StringUtils.isEmpty(config.getNumberFrom())) {
throw new IllegalArgumentException("Invalid twilio sms provider configuration: accountSid, accountToken and numberFrom should be specified!");
}
this.numberFrom = this.validatePhoneTwilioNumber(config.getNumberFrom());
this.twilioRestClient = new TwilioRestClient.Builder(config.getAccountSid(), config.getAccountToken()).build();
}
@Override
public int sendSms(String numberTo, String message) throws SmsException {
|
numberTo = this.validatePhoneNumber(numberTo);
message = this.prepareMessage(message);
try {
String numSegments = Message.creator(new PhoneNumber(numberTo), new PhoneNumber(this.numberFrom), message).create(this.twilioRestClient).getNumSegments();
return Integer.valueOf(numSegments);
} catch (Exception e) {
throw new SmsSendException("Failed to send SMS message - " + e.getMessage(), e);
}
}
@Override
public void destroy() {
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sms\twilio\TwilioSmsSender.java
| 2
|
请完成以下Java代码
|
public void logout(final @NonNull UserId userId)
{
abortAll(userId);
}
@Override
public WFProcess getWFProcessById(final WFProcessId wfProcessId)
{
final Inventory inventory = jobService.getById(toInventoryId(wfProcessId));
return toWFProcess(inventory);
}
@Override
public WFProcessHeaderProperties getHeaderProperties(final @NonNull WFProcess wfProcess)
{
final WarehousesLoadingCache warehouses = warehouseService.newLoadingCache();
final Inventory inventory = getInventory(wfProcess);
return WFProcessHeaderProperties.builder()
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("DocumentNo"))
.value(inventory.getDocumentNo())
.build())
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("MovementDate"))
.value(TranslatableStrings.date(inventory.getMovementDate().toLocalDate()))
|
.build())
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("M_Warehouse_ID"))
.value(inventory.getWarehouseId() != null
? warehouses.getById(inventory.getWarehouseId()).getWarehouseName()
: "")
.build())
.build();
}
@NonNull
public static Inventory getInventory(final @NonNull WFProcess wfProcess)
{
return wfProcess.getDocumentAs(Inventory.class);
}
public static WFProcess mapJob(@NonNull final WFProcess wfProcess, @NonNull final UnaryOperator<Inventory> mapper)
{
final Inventory inventory = getInventory(wfProcess);
final Inventory inventoryChanged = mapper.apply(inventory);
return !Objects.equals(inventory, inventoryChanged) ? toWFProcess(inventoryChanged) : wfProcess;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\InventoryMobileApplication.java
| 1
|
请完成以下Java代码
|
private Map<Integer, List<MyCell>> readXSSFWorkbook(FileInputStream fis) throws IOException {
XSSFWorkbook workbook = null;
Map<Integer, List<MyCell>> data = new HashMap<>();
try {
workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<>());
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
XSSFCell cell = row.getCell(j);
if (cell != null) {
XSSFCellStyle cellStyle = cell.getCellStyle();
MyCell myCell = new MyCell();
XSSFColor bgColor = cellStyle.getFillForegroundColorColor();
if (bgColor != null) {
byte[] rgbColor = bgColor.getRGB();
myCell.setBgColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")");
}
XSSFFont font = cellStyle.getFont();
myCell.setTextSize(font.getFontHeightInPoints() + "");
if (font.getBold()) {
myCell.setTextWeight("bold");
}
XSSFColor textColor = font.getXSSFColor();
if (textColor != null) {
byte[] rgbColor = textColor.getRGB();
|
myCell.setTextColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")");
}
myCell.setContent(readCellContent(cell));
data.get(i)
.add(myCell);
} else {
data.get(i)
.add(new MyCell(""));
}
}
}
}
} finally {
if (workbook != null) {
workbook.close();
}
}
return data;
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-java-2\src\main\java\com\baeldung\excel\ExcelPOIHelper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isEncodeDefaults() {
return this.encodeDefaults;
}
public void setEncodeDefaults(boolean encodeDefaults) {
this.encodeDefaults = encodeDefaults;
}
public boolean isExplicitNulls() {
return this.explicitNulls;
}
public void setExplicitNulls(boolean explicitNulls) {
this.explicitNulls = explicitNulls;
}
public boolean isCoerceInputValues() {
return this.coerceInputValues;
}
public void setCoerceInputValues(boolean coerceInputValues) {
this.coerceInputValues = coerceInputValues;
}
public boolean isAllowStructuredMapKeys() {
return this.allowStructuredMapKeys;
}
public void setAllowStructuredMapKeys(boolean allowStructuredMapKeys) {
this.allowStructuredMapKeys = allowStructuredMapKeys;
}
public boolean isAllowSpecialFloatingPointValues() {
return this.allowSpecialFloatingPointValues;
}
public void setAllowSpecialFloatingPointValues(boolean allowSpecialFloatingPointValues) {
this.allowSpecialFloatingPointValues = allowSpecialFloatingPointValues;
}
public String getClassDiscriminator() {
return this.classDiscriminator;
}
public void setClassDiscriminator(String classDiscriminator) {
this.classDiscriminator = classDiscriminator;
}
public ClassDiscriminatorMode getClassDiscriminatorMode() {
return this.classDiscriminatorMode;
}
public void setClassDiscriminatorMode(ClassDiscriminatorMode classDiscriminatorMode) {
this.classDiscriminatorMode = classDiscriminatorMode;
}
public boolean isDecodeEnumsCaseInsensitive() {
return this.decodeEnumsCaseInsensitive;
}
public void setDecodeEnumsCaseInsensitive(boolean decodeEnumsCaseInsensitive) {
this.decodeEnumsCaseInsensitive = decodeEnumsCaseInsensitive;
}
public boolean isUseAlternativeNames() {
return this.useAlternativeNames;
}
public void setUseAlternativeNames(boolean useAlternativeNames) {
this.useAlternativeNames = useAlternativeNames;
}
|
public boolean isAllowTrailingComma() {
return this.allowTrailingComma;
}
public void setAllowTrailingComma(boolean allowTrailingComma) {
this.allowTrailingComma = allowTrailingComma;
}
public boolean isAllowComments() {
return this.allowComments;
}
public void setAllowComments(boolean allowComments) {
this.allowComments = allowComments;
}
/**
* Enum representing strategies for JSON property naming. The values correspond to
* {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot
* be directly referenced.
*/
public enum JsonNamingStrategy {
/**
* Snake case strategy.
*/
SNAKE_CASE,
/**
* Kebab case strategy.
*/
KEBAB_CASE
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java
| 2
|
请完成以下Java代码
|
private static boolean isGitRepositoryRoot(final File dir)
{
if (!dir.isDirectory())
{
return false;
}
final File gitDir = new File(dir, ".git");
return gitDir.exists() && gitDir.isDirectory();
}
private static boolean isProjectsGroupDir(final File dir)
{
return dir.isDirectory() && "backend".equals(dir.getName()); // metasfresh/backend
}
private static boolean isMavenProjectDir(final File dir)
{
return dir.isDirectory() && new File(dir, "pom.xml").exists();
}
private List<IScript> getScriptFilesFromProjectDir(final File projectDir, final String defaultProjectName)
{
final File scriptsRootDir = new File(projectDir, "src/main/sql/postgresql/system");
if (!scriptsRootDir.isDirectory())
{
return ImmutableList.of();
}
final ArrayList<IScript> scripts = new ArrayList<>();
//
// Script files in subfolders
// e.g. .../src/main/sql/postgresql/system/10-de.metas.adempiere
for (final File subProjectDir : scriptsRootDir.listFiles(File::isDirectory))
{
final String projectName = subProjectDir.getName();
for (final File scriptFile : subProjectDir.listFiles(this::isSupportedScriptFile))
{
scripts.add(new LocalScript(projectName, scriptFile));
}
}
//
// Script files directly in .../src/main/sql/postgresql/system/ folder
for (final File scriptFile : scriptsRootDir.listFiles(File::isFile))
{
scripts.add(new LocalScript(defaultProjectName, scriptFile));
}
|
logger.info("Considering {} ({} scripts)", projectDir, scripts.size());
return scripts;
}
private boolean isSupportedScriptFile(final File file)
{
if (!file.exists() || !file.isFile())
{
return false;
}
final String fileExtLC = FileUtils.getFileExtension(file.getName(), false).toLowerCase();
return supportedFileExtensionsLC.contains(fileExtLC);
}
private static String getDefaultProjectName(final File projectDir)
{
final File mavenPOMFile = new File(projectDir, "pom.xml");
if (mavenPOMFile.exists())
{
final Document xmlDocument = XmlUtils.loadDocument(mavenPOMFile);
try
{
return XmlUtils.getString("/project/properties/migration-sql-basedir", xmlDocument);
}
catch (Exception ex)
{
ex.printStackTrace(); // FIXME remove
return null;
}
}
else
{
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\WorkspaceScriptScanner.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.