instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private boolean isMissingAttachmentEntryForRecordId(@NonNull final BankStatementImportFileId bankStatementImportFileId)
{
return !getSingleAttachmentEntryId(bankStatementImportFileId).isPresent();
}
@NonNull
private Optional<AttachmentEntryId> getSingleAttachmentEntryId(@NonNull final BankStatementImportFileId bankStatementImportFileId)
{
final List<AttachmentEntry> attachments = attachmentEntryService
.getByReferencedRecord(TableRecordReference.of(I_C_BankStatement_Import_File.Table_Name, bankStatementImportFileId));
if (attachments.isEmpty())
{
return Optional.empty();
}
if (attachments.size() != 1)
{
throw new AdempiereException(MSG_MULTIPLE_ATTACHMENTS)
.markAsUserValidationError(); | }
return Optional.of(attachments.get(0).getId());
}
@NonNull
private AttachmentEntryDataResource retrieveAttachmentResource(@NonNull final BankStatementImportFileId bankStatementImportFileId)
{
final AttachmentEntryId attachmentEntryId = getSingleAttachmentEntryId(bankStatementImportFileId)
.orElseThrow(() -> new AdempiereException(MSG_NO_ATTACHMENT)
.markAsUserValidationError());
return attachmentEntryService.retrieveDataResource(attachmentEntryId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\process\C_BankStatement_Import_File_Camt53_ImportAttachment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class NarcoticShipmentDeclarationVetoer implements ShipmentDeclarationVetoer
{
private final PharmaShipmentConfigRepository pharmaShipmentDeclarationConfigRepo;
private final PharmaProductRepository pharmaProductRepo;
private NarcoticShipmentDeclarationVetoer(
@NonNull final PharmaShipmentConfigRepository pharmaShipmentDeclarationConfigRepo,
@NonNull final PharmaProductRepository pharmaProductRepo)
{
this.pharmaShipmentDeclarationConfigRepo = pharmaShipmentDeclarationConfigRepo;
this.pharmaProductRepo = pharmaProductRepo;
}
@Override
public OnShipmentDeclarationConfig foundShipmentLineForConfig(
final InOutAndLineId shipmentLineId, | final ShipmentDeclarationConfig shipmentDeclarationConfig)
{
if (!pharmaShipmentDeclarationConfigRepo.isOnlyNarcoticProducts(shipmentDeclarationConfig))
{
return OnShipmentDeclarationConfig.I_DONT_CARE;
}
if (pharmaProductRepo.isLineForNarcoticProduct(shipmentLineId))
{
return OnShipmentDeclarationConfig.I_VETO;
}
return OnShipmentDeclarationConfig.I_DONT_CARE;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\shipment\NarcoticShipmentDeclarationVetoer.java | 2 |
请完成以下Java代码 | 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 setPriceList (final @Nullable java.lang.String PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
@Override
public java.lang.String getPriceList()
{
return get_ValueAsString(COLUMNNAME_PriceList);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setProductValue (final java.lang.String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setProjectValue (final @Nullable java.lang.String ProjectValue)
{
set_Value (COLUMNNAME_ProjectValue, ProjectValue);
}
@Override
public java.lang.String getProjectValue()
{
return get_ValueAsString(COLUMNNAME_ProjectValue);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCalculated (final @Nullable BigDecimal QtyCalculated)
{
set_Value (COLUMNNAME_QtyCalculated, QtyCalculated);
}
@Override
public BigDecimal getQtyCalculated()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCalculated);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUOM (final java.lang.String UOM)
{
set_Value (COLUMNNAME_UOM, UOM);
}
@Override
public java.lang.String getUOM()
{
return get_ValueAsString(COLUMNNAME_UOM);
}
@Override
public void setWarehouseValue (final java.lang.String WarehouseValue)
{
set_Value (COLUMNNAME_WarehouseValue, WarehouseValue);
}
@Override
public java.lang.String getWarehouseValue()
{
return get_ValueAsString(COLUMNNAME_WarehouseValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Forecast.java | 1 |
请完成以下Java代码 | public I_M_AttributeInstance retrieveAttributeInstance(
@Nullable final AttributeSetInstanceId attributeSetInstanceId,
@NonNull final AttributeId attributeId)
{
if (attributeSetInstanceId == null || attributeSetInstanceId.isNone())
{
return null;
}
return queryBL.createQueryBuilder(I_M_AttributeInstance.class)
.addEqualsFilter(I_M_AttributeInstance.COLUMNNAME_M_AttributeSetInstance_ID, attributeSetInstanceId)
.addEqualsFilter(I_M_AttributeInstance.COLUMNNAME_M_Attribute_ID, attributeId)
.create()
.firstOnly(I_M_AttributeInstance.class);
}
@Override
public Stream<I_M_AttributeInstance> streamAttributeInstances(
@NonNull final AttributeSetInstanceId asiId,
@NonNull final Set<AttributeId> attributeIds)
{
if (asiId.isNone() || attributeIds.isEmpty())
{
return Stream.of();
}
return queryBL.createQueryBuilder(I_M_AttributeInstance.class)
.addEqualsFilter(I_M_AttributeInstance.COLUMNNAME_M_AttributeSetInstance_ID, asiId)
.addInArrayFilter(I_M_AttributeInstance.COLUMNNAME_M_Attribute_ID, attributeIds)
.stream();
}
@Override
public I_M_AttributeInstance createNewAttributeInstance(
final Properties ctx,
final I_M_AttributeSetInstance asi,
@NonNull final AttributeId attributeId,
final String trxName)
{
final I_M_AttributeInstance ai = InterfaceWrapperHelper.create(ctx, I_M_AttributeInstance.class, trxName);
ai.setAD_Org_ID(asi.getAD_Org_ID());
ai.setM_AttributeSetInstance(asi);
ai.setM_Attribute_ID(attributeId.getRepoId()); | return ai;
}
@Override
public void save(@NonNull final I_M_AttributeSetInstance asi)
{
saveRecord(asi);
}
@Override
public void save(@NonNull final I_M_AttributeInstance ai)
{
saveRecord(ai);
}
@Override
public Set<AttributeId> getAttributeIdsByAttributeSetInstanceId(@NonNull final AttributeSetInstanceId attributeSetInstanceId)
{
return queryBL
.createQueryBuilderOutOfTrx(I_M_AttributeInstance.class)
.addEqualsFilter(I_M_AttributeInstance.COLUMN_M_AttributeSetInstance_ID, attributeSetInstanceId)
.create()
.listDistinct(I_M_AttributeInstance.COLUMNNAME_M_Attribute_ID, Integer.class)
.stream()
.map(AttributeId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetInstanceDAO.java | 1 |
请完成以下Java代码 | public void setC_Activity_ID (final int C_Activity_ID)
{
if (C_Activity_ID < 1)
set_Value (COLUMNNAME_C_Activity_ID, null);
else
set_Value (COLUMNNAME_C_Activity_ID, C_Activity_ID);
}
@Override
public int getC_Activity_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Activity_ID);
}
@Override
public void setC_CompensationGroup_Schema_ID (final int C_CompensationGroup_Schema_ID)
{
if (C_CompensationGroup_Schema_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_ID, C_CompensationGroup_Schema_ID);
} | @Override
public int getC_CompensationGroup_Schema_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_Schema.java | 1 |
请完成以下Java代码 | public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricIdentityLinkLogDto fromHistoricIdentityLink(HistoricIdentityLinkLog historicIdentityLink) {
HistoricIdentityLinkLogDto dto = new HistoricIdentityLinkLogDto();
fromHistoricIdentityLink(dto, historicIdentityLink);
return dto;
}
public static void fromHistoricIdentityLink(HistoricIdentityLinkLogDto dto, | HistoricIdentityLinkLog historicIdentityLink) {
dto.id = historicIdentityLink.getId();
dto.assignerId = historicIdentityLink.getAssignerId();
dto.groupId = historicIdentityLink.getGroupId();
dto.operationType = historicIdentityLink.getOperationType();
dto.taskId = historicIdentityLink.getTaskId();
dto.time = historicIdentityLink.getTime();
dto.type = historicIdentityLink.getType();
dto.processDefinitionId = historicIdentityLink.getProcessDefinitionId();
dto.processDefinitionKey = historicIdentityLink.getProcessDefinitionKey();
dto.userId = historicIdentityLink.getUserId();
dto.tenantId = historicIdentityLink.getTenantId();
dto.removalTime = historicIdentityLink.getRemovalTime();
dto.rootProcessInstanceId = historicIdentityLink.getRootProcessInstanceId();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogDto.java | 1 |
请完成以下Java代码 | public class CustomsInvoiceLine
{
@NonFinal
CustomsInvoiceLineId id;
@NonFinal
@Setter(AccessLevel.PACKAGE)
int lineNo;
@NonNull
ProductId productId;
@NonNull
Quantity quantity;
@NonNull
OrgId orgId;
@NonNull
Money lineNetAmt;
@Getter(AccessLevel.NONE)
@Default
private final ArrayList<CustomsInvoiceLineAlloc> allocations = new ArrayList<>();
public ImmutableList<CustomsInvoiceLineAlloc> getAllocations()
{
return ImmutableList.copyOf(allocations);
}
public void addAllocation(CustomsInvoiceLineAlloc alloc)
{ | allocations.add(alloc);
}
public void removeAllocation(@NonNull final CustomsInvoiceLineAlloc alloc)
{
allocations.remove(alloc);
}
public Optional<CustomsInvoiceLineAlloc> getAllocationByInOutLineId(@NonNull final InOutAndLineId inoutAndLineId)
{
return allocations.stream()
.filter(alloc -> alloc.getInoutAndLineId().equals(inoutAndLineId))
.findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\CustomsInvoiceLine.java | 1 |
请完成以下Java代码 | public Long sadd(final String key, final String... members) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.sadd(key, members);
} catch (Exception ex) {
log.error("Exception caught in sadd", ex);
}
return null;
}
public Set<String> smembers(final String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.smembers(key);
} catch (Exception ex) {
log.error("Exception caught in smembers", ex);
}
return new HashSet<String>();
}
public Long zadd(final String key, final Map<String, Double> scoreMembers) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.zadd(key, scoreMembers);
} catch (Exception ex) {
log.error("Exception caught in zadd", ex);
}
return 0L;
}
public List<String> zrange(final String key, final long start, final long stop) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.zrange(key, start, stop);
} catch (Exception ex) {
log.error("Exception caught in zrange", ex);
}
return new ArrayList<>();
}
public String mset(final HashMap<String, String> keysValues) {
try (Jedis jedis = jedisPool.getResource()) {
ArrayList<String> keysValuesArrayList = new ArrayList<>();
keysValues.forEach((key, value) -> {
keysValuesArrayList.add(key);
keysValuesArrayList.add(value);
});
return jedis.mset((keysValuesArrayList.toArray(new String[keysValues.size()])));
} catch (Exception ex) {
log.error("Exception caught in mset", ex);
} | return null;
}
public Set<String> keys(final String pattern) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.keys(pattern);
} catch (Exception ex) {
log.error("Exception caught in keys", ex);
}
return new HashSet<String>();
}
public RedisIterator iterator(int initialScanCount, String pattern, ScanStrategy strategy) {
return new RedisIterator(jedisPool, initialScanCount, pattern, strategy);
}
public void flushAll() {
try (Jedis jedis = jedisPool.getResource()) {
jedis.flushAll();
} catch (Exception ex) {
log.error("Exception caught in flushAll", ex);
}
}
public void destroyInstance() {
jedisPool = null;
instance = null;
}
} | repos\tutorials-master\persistence-modules\redis\src\main\java\com\baeldung\redis_scan\client\RedisClient.java | 1 |
请完成以下Java代码 | public class SymLinkExample {
public void createSymbolicLink(Path link, Path target) throws IOException {
if (Files.exists(link)) {
Files.delete(link);
}
Files.createSymbolicLink(link, target);
}
public void createHardLink(Path link, Path target) throws IOException {
if (Files.exists(link)) {
Files.delete(link);
}
Files.createLink(link, target);
}
public Path createTextFile() throws IOException {
byte[] content = IntStream.range(0, 10000)
.mapToObj(i -> i + System.lineSeparator())
.reduce("", String::concat)
.getBytes(StandardCharsets.UTF_8);
Path filePath = Paths.get(".", "target_link.txt");
Files.write(filePath, content, CREATE, TRUNCATE_EXISTING); | return filePath;
}
public void printLinkFiles(Path path) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path file : stream) {
if (Files.isDirectory(file)) {
printLinkFiles(file);
} else if (Files.isSymbolicLink(file)) {
System.out.format("File link '%s' with target '%s'%n", file, Files.readSymbolicLink(file));
}
}
}
}
public static void main(String[] args) throws IOException {
new SymLinkExample().printLinkFiles(Paths.get("."));
}
} | repos\tutorials-master\core-java-modules\core-java-nio-2\src\main\java\com\baeldung\symlink\SymLinkExample.java | 1 |
请完成以下Java代码 | public class UserEventListenerImpl extends EventListenerImpl implements UserEventListener {
protected static AttributeReferenceCollection<Role> authorizedRoleRefCollection;
public UserEventListenerImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<Role> getAuthorizedRoles() {
return authorizedRoleRefCollection.getReferenceTargetElements(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(UserEventListener.class, CMMN_ELEMENT_USER_EVENT_LISTENER)
.namespaceUri(CMMN11_NS) | .extendsType(EventListener.class)
.instanceProvider(new ModelTypeInstanceProvider<UserEventListener>() {
public UserEventListener newInstance(ModelTypeInstanceContext instanceContext) {
return new UserEventListenerImpl(instanceContext);
}
});
authorizedRoleRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_AUTHORIZED_ROLE_REFS)
.idAttributeReferenceCollection(Role.class, CmmnAttributeElementReferenceCollection.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\UserEventListenerImpl.java | 1 |
请完成以下Java代码 | private static boolean authorizationCodeGrant(Map<String, Object> parameters) {
if (!AuthorizationGrantType.AUTHORIZATION_CODE.getValue()
.equals(parameters.get(OAuth2ParameterNames.GRANT_TYPE))) {
return false;
}
if (!StringUtils.hasText((String) parameters.get(OAuth2ParameterNames.CODE))) {
throwInvalidGrant(OAuth2ParameterNames.CODE);
}
return true;
}
private boolean codeVerifierValid(String codeVerifier, String codeChallenge, String codeChallengeMethod) {
if (!StringUtils.hasText(codeVerifier)) {
return false;
}
else if ("S256".equals(codeChallengeMethod)) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(codeVerifier.getBytes(StandardCharsets.US_ASCII));
String encodedVerifier = Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
return encodedVerifier.equals(codeChallenge);
}
catch (NoSuchAlgorithmException ex) {
// It is unlikely that SHA-256 is not available on the server. If it is | // not available,
// there will likely be bigger issues as well. We default to SERVER_ERROR.
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.SERVER_ERROR);
}
}
return false;
}
private static void throwInvalidGrant(String parameterName) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT,
"Client authentication failed: " + parameterName, null);
throw new OAuth2AuthenticationException(error);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\CodeVerifierAuthenticator.java | 1 |
请完成以下Java代码 | public static void logDocActionAccess(final RoleId roleId, final DocTypeId docTypeId, final String docAction, final Boolean access)
{
logAccess(roleId, COLUMNNAME_C_DocType_ID, docTypeId.getRepoId(), COLUMNNAME_DocAction, docAction, access, null);
}
private static void logAccess(
@NonNull final RoleId roleId,
final String type,
final Object value,
final String type2,
final Object value2,
final Boolean access,
final String description)
{
final String permLogLevel = getPermLogLevel();
if (PERMLOGLEVEL_Disabled.equals(permLogLevel))
{
return;
}
final boolean isPermissionGranted = access != null;
if (isPermissionGranted && !PERMLOGLEVEL_Full.equals(permLogLevel))
{
// Permission granted, and there is no need to log all requests => nothing to do
return;
}
if (value instanceof Integer && ((Integer)value).intValue() <= 0)
{
// Skip invalid permissions request
return;
}
final Properties ctx = Env.getCtx();
final String trxName = null;
final boolean isReadWrite = access != null && access.booleanValue() == true;
final ArrayList<Object> params = new ArrayList<>();
final StringBuilder whereClause = new StringBuilder(COLUMNNAME_AD_Role_ID + "=? AND " + type + "=?");
params.add(roleId);
params.add(value);
if (type2 != null)
{
whereClause.append(" AND " + type2 + "=?");
params.add(value2);
}
MRolePermRequest req = new Query(ctx, Table_Name, whereClause.toString(), trxName)
.setParameters(params)
.setOrderBy(COLUMNNAME_AD_Role_PermRequest_ID + " DESC")
.first(); | if (req == null)
{
req = new MRolePermRequest(ctx, 0, trxName);
req.setAD_Role_ID(roleId.getRepoId());
req.set_ValueOfColumn(type, value);
if (type2 != null)
{
req.set_ValueOfColumn(type2, value2);
}
}
req.setIsActive(true);
req.setIsReadWrite(isReadWrite);
req.setIsPermissionGranted(isPermissionGranted);
req.setDescription(description);
savePermissionRequestAndHandleException(type, value, req);
}
private static void savePermissionRequestAndHandleException(
@NonNull final String type,
@NonNull final Object value,
@NonNull final MRolePermRequest req)
{
try
{
req.saveEx();
}
catch (final DBForeignKeyConstraintException e)
{
throw new NoSuchForeignKeyException(type + "=" + value + " is not a valid foreign key", e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\model\MRolePermRequest.java | 1 |
请完成以下Java代码 | private static void printfChar() {
System.out.printf("%c%n", 's');
System.out.printf("%C%n", 's');
}
private static void printfNumber() {
System.out.printf("simple integer: %d%n", 10000L);
System.out.printf(Locale.US, "%,d %n", 10000);
System.out.printf(Locale.ITALY, "%,d %n", 10000);
System.out.printf("%f%n", 5.1473);
System.out.printf("'%5.2f'%n", 5.1473);
System.out.printf("'%5.2e'%n", 5.1473);
}
private static void printfBoolean() {
System.out.printf("%b%n", null); | System.out.printf("%B%n", false);
System.out.printf("%B%n", 5.3);
System.out.printf("%b%n", "random text");
}
private static void printfDateTime() {
Date date = new Date();
System.out.printf("%tT%n", date);
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);
System.out.printf("%1$tA %1$tB %1$tY %n", date);
System.out.printf("%1$td.%1$tm.%1$ty %n", date);
}
} | repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\printf\PrintfExamples.java | 1 |
请完成以下Spring Boot application配置 | spring.application.name=forex-service
server.port=8000
# Enabling H2 Console
spring.h2.console.enabled=true
#Turn Statistics on
#spring.jpa.properties.hibernate.generate_statistics=true
#logging.level.org.hibernate.stat=debug
# Show all queries
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.type=trace
spring.datasource.url=jdbc:h2:mem:test | db
spring.data.jpa.repositories.bootstrap-mode=default
spring.jpa.defer-datasource-initialization=true
eureka.client.service-url.default-zone=http://localhost:8761/eureka | repos\spring-boot-examples-master\spring-boot-basic-microservice\spring-boot-microservice-forex-service\src\main\resources\application.properties | 2 |
请完成以下Java代码 | 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代码 | public class AsyncInlineCachingConfiguration {
protected static final String GOLFERS_REGION_NAME = "Golfers";
// tag::queue-batch-size[]
@Bean
@Profile("queue-batch-size")
AsyncInlineCachingRegionConfigurer<Golfer, String> batchSizeAsyncInlineCachingConfigurer(
@Value("${spring.geode.sample.async-inline-caching.queue.batch-size:25}") int queueBatchSize,
GolferRepository golferRepository) {
return AsyncInlineCachingRegionConfigurer.create(golferRepository, GOLFERS_REGION_NAME)
.withQueueBatchConflationEnabled()
.withQueueBatchSize(queueBatchSize)
.withQueueBatchTimeInterval(Duration.ofMinutes(15))
.withQueueDispatcherThreadCount(1);
}
// end::queue-batch-size[] | // tag::queue-batch-time-interval[]
@Bean
@Profile("queue-batch-time-interval")
AsyncInlineCachingRegionConfigurer<Golfer, String> batchTimeIntervalAsyncInlineCachingConfigurer(
@Value("${spring.geode.sample.async-inline-caching.queue.batch-time-interval-ms:5000}") int queueBatchTimeIntervalMilliseconds,
GolferRepository golferRepository) {
return AsyncInlineCachingRegionConfigurer.create(golferRepository, GOLFERS_REGION_NAME)
.withQueueBatchSize(1000000)
.withQueueBatchTimeInterval(Duration.ofMillis(queueBatchTimeIntervalMilliseconds))
.withQueueDispatcherThreadCount(1);
}
// end::queue-batch-time-interval[]
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\config\AsyncInlineCachingConfiguration.java | 2 |
请完成以下Java代码 | public class PaymentsToReconcileView extends AbstractCustomView<PaymentToReconcileRow>
{
public static PaymentsToReconcileView cast(final IView view)
{
return (PaymentsToReconcileView)view;
}
@Getter
private final ViewId bankStatementViewId;
private final ImmutableList<RelatedProcessDescriptor> processes;
@Builder
private PaymentsToReconcileView(
final ViewId bankStatementViewId,
@NonNull final PaymentToReconcileRows rows,
@NonNull final List<RelatedProcessDescriptor> processes)
{
super(
bankStatementViewId.withWindowId(PaymentsToReconcileViewFactory.WINDOW_ID),
TranslatableStrings.empty(),
rows,
NullDocumentFilterDescriptorsProvider.instance);
this.bankStatementViewId = bankStatementViewId;
this.processes = processes != null ? ImmutableList.copyOf(processes) : ImmutableList.of();
}
@Override | public String getTableNameOrNull(final DocumentId documentId)
{
return null;
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return processes;
}
@Override
protected PaymentToReconcileRows getRowsData()
{
return PaymentToReconcileRows.cast(super.getRowsData());
}
@Override
public ViewId getParentViewId()
{
return getBankStatementViewId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentsToReconcileView.java | 1 |
请完成以下Java代码 | protected List<Task> executeTaskQuery(Integer firstResult, Integer maxResults, TaskQuery query) {
// enable initialization of form key:
query.initializeFormKeys();
return QueryUtil.list(query, firstResult, maxResults);
}
@Override
public CountResultDto getTasksCount(UriInfo uriInfo) {
TaskQueryDto queryDto = new TaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryTasksCount(queryDto);
}
@Override
public CountResultDto queryTasksCount(TaskQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
TaskQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
@Override
public TaskResource getTask(String id,
boolean withCommentAttachmentInfo,
boolean withTaskVariablesInReturn,
boolean withTaskLocalVariablesInReturn) {
return new TaskResourceImpl(getProcessEngine(), id, relativeRootResourcePath, getObjectMapper(),
withCommentAttachmentInfo, withTaskVariablesInReturn, withTaskLocalVariablesInReturn);
}
@Override
public void createTask(TaskDto taskDto) {
ProcessEngine engine = getProcessEngine();
TaskService taskService = engine.getTaskService();
Task newTask = taskService.newTask(taskDto.getId());
taskDto.updateTask(newTask);
try {
taskService.saveTask(newTask);
} catch (NotValidException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e, "Could not save task: " + e.getMessage());
}
}
@Override | public TaskReportResource getTaskReportResource() {
return new TaskReportResourceImpl(getProcessEngine());
}
private List<TaskDto> getVariablesForTasks(ProcessEngine engine,
List<Task> matchingTasks,
boolean withTaskVariablesInReturn,
boolean withCommentAndAttachments) {
TaskService taskService = engine.getTaskService();
List<TaskDto> tasks = new ArrayList<TaskDto>();
for (Task task : matchingTasks) {
VariableMap taskVariables;
if (withTaskVariablesInReturn) {
taskVariables = taskService.getVariablesTyped(task.getId(), true);
} else {
taskVariables = taskService.getVariablesLocalTyped(task.getId(), true);
}
Map<String, VariableValueDto> taskVariablesDto = VariableValueDto.fromMap(taskVariables);
if (withCommentAndAttachments) {
tasks.add(TaskWithAttachmentAndCommentDto.fromEntity(task, taskVariablesDto));
} else {
tasks.add(TaskWithVariablesDto.fromEntity(task, taskVariablesDto));
}
}
return tasks;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\TaskRestServiceImpl.java | 1 |
请完成以下Java代码 | public int getPP_Order_Weighting_Run_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_Run_ID);
}
@Override
public org.eevolution.model.I_PP_Weighting_Spec getPP_Weighting_Spec()
{
return get_ValueAsPO(COLUMNNAME_PP_Weighting_Spec_ID, org.eevolution.model.I_PP_Weighting_Spec.class);
}
@Override
public void setPP_Weighting_Spec(final org.eevolution.model.I_PP_Weighting_Spec PP_Weighting_Spec)
{
set_ValueFromPO(COLUMNNAME_PP_Weighting_Spec_ID, org.eevolution.model.I_PP_Weighting_Spec.class, PP_Weighting_Spec);
}
@Override
public void setPP_Weighting_Spec_ID (final int PP_Weighting_Spec_ID)
{
if (PP_Weighting_Spec_ID < 1)
set_Value (COLUMNNAME_PP_Weighting_Spec_ID, null);
else
set_Value (COLUMNNAME_PP_Weighting_Spec_ID, PP_Weighting_Spec_ID);
}
@Override
public int getPP_Weighting_Spec_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Weighting_Spec_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setTargetWeight (final BigDecimal TargetWeight)
{
set_Value (COLUMNNAME_TargetWeight, TargetWeight); | }
@Override
public BigDecimal getTargetWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TargetWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTolerance_Perc (final BigDecimal Tolerance_Perc)
{
set_Value (COLUMNNAME_Tolerance_Perc, Tolerance_Perc);
}
@Override
public BigDecimal getTolerance_Perc()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Tolerance_Perc);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeightChecksRequired (final int WeightChecksRequired)
{
set_Value (COLUMNNAME_WeightChecksRequired, WeightChecksRequired);
}
@Override
public int getWeightChecksRequired()
{
return get_ValueAsInt(COLUMNNAME_WeightChecksRequired);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_Run.java | 1 |
请完成以下Java代码 | protected ParameterValueProvider createParameterValueProvider(Object value, ExpressionManager expressionManager) {
if (value == null) {
return new NullValueProvider();
} else if (value instanceof String) {
Expression expression = expressionManager.createExpression((String) value);
return new ElValueProvider(expression);
} else {
return new ConstantValueProvider(value);
}
}
protected void addTimeCycleWarning(Element timeCycleElement, String type, String timerElementId) {
String warning = "It is not recommended to use a " + type + " timer event with a time cycle.";
addWarning(warning, timeCycleElement, timerElementId);
} | protected void ensureNoExpressionInMessageStartEvent(Element element,
EventSubscriptionDeclaration messageStartEventSubscriptionDeclaration,
String parentElementId) {
boolean eventNameContainsExpression = false;
if(messageStartEventSubscriptionDeclaration.hasEventName()) {
eventNameContainsExpression = !messageStartEventSubscriptionDeclaration.isEventNameLiteralText();
}
if (eventNameContainsExpression) {
String messageStartName = messageStartEventSubscriptionDeclaration.getUnresolvedEventName();
addError("Invalid message name '" + messageStartName + "' for element '" +
element.getTagName() + "': expressions in the message start event name are not allowed!", element, parentElementId);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\BpmnParse.java | 1 |
请完成以下Java代码 | 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 setOrg_ID (final int Org_ID)
{
if (Org_ID < 1)
set_Value (COLUMNNAME_Org_ID, null);
else
set_Value (COLUMNNAME_Org_ID, Org_ID);
}
@Override
public int getOrg_ID()
{
return get_ValueAsInt(COLUMNNAME_Org_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
@Override
public void setUserElementString2 (final @Nullable java.lang.String UserElementString2)
{
set_Value (COLUMNNAME_UserElementString2, UserElementString2);
}
@Override
public java.lang.String getUserElementString2()
{
return get_ValueAsString(COLUMNNAME_UserElementString2);
}
@Override
public void setUserElementString3 (final @Nullable java.lang.String UserElementString3)
{ | set_Value (COLUMNNAME_UserElementString3, UserElementString3);
}
@Override
public java.lang.String getUserElementString3()
{
return get_ValueAsString(COLUMNNAME_UserElementString3);
}
@Override
public void setUserElementString4 (final @Nullable java.lang.String UserElementString4)
{
set_Value (COLUMNNAME_UserElementString4, UserElementString4);
}
@Override
public java.lang.String getUserElementString4()
{
return get_ValueAsString(COLUMNNAME_UserElementString4);
}
@Override
public void setUserElementString5 (final @Nullable java.lang.String UserElementString5)
{
set_Value (COLUMNNAME_UserElementString5, UserElementString5);
}
@Override
public java.lang.String getUserElementString5()
{
return get_ValueAsString(COLUMNNAME_UserElementString5);
}
@Override
public void setUserElementString6 (final @Nullable java.lang.String UserElementString6)
{
set_Value (COLUMNNAME_UserElementString6, UserElementString6);
}
@Override
public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_Element.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Foo> findAll() {
return service.findAll();
}
@GetMapping(params = { "page", "size" })
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size,
final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
final Page<Foo> resultPage = service.findPaginated(page, size);
if (page > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page,
resultPage.getTotalPages(), size));
return resultPage.getContent();
}
@GetMapping("/pageable")
public List<Foo> findPaginatedWithPageable(Pageable pageable, final UriComponentsBuilder uriBuilder,
final HttpServletResponse response) {
final Page<Foo> resultPage = service.findPaginated(pageable);
if (pageable.getPageNumber() > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException();
}
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response,
pageable.getPageNumber(), resultPage.getTotalPages(), pageable.getPageSize()));
return resultPage.getContent();
}
// write
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { | Preconditions.checkNotNull(resource);
final Foo foo = service.create(resource);
final Long idOfCreatedResource = foo.getId();
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
return foo;
}
@PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
Preconditions.checkNotNull(resource);
RestPreconditions.checkFound(service.findById(resource.getId()));
service.update(resource);
}
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") final Long id) {
service.deleteById(id);
}
@ExceptionHandler({ CustomException1.class, CustomException2.class })
public void handleException(final Exception ex) {
final String error = "Application specific error handling";
logger.error(error, ex);
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\controller\FooController.java | 2 |
请完成以下Java代码 | public void onContextCreated(final Properties ctx)
{
activeContexts.add(ctx);
}
@Override
public void onChildContextCreated(final Properties ctx, final Properties childCtx)
{
activeContexts.add(childCtx);
}
@Override
public void onContextCheckOut(final Properties ctx)
{
final Thread thread = Thread.currentThread();
ctx.setProperty(CTXNAME_ThreadName, thread.getName());
ctx.setProperty(CTXNAME_ThreadId, String.valueOf(thread.getId()));
}
@Override
public void onContextCheckIn(final Properties ctxNew, final Properties ctxOld)
{
activeContexts.remove(ctxOld);
activeContexts.add(ctxNew);
}
public String[] getActiveContextsInfo()
{
final List<Properties> activeContextsCopy = new ArrayList<>(activeContexts);
final int count = activeContextsCopy.size();
final List<String> activeContextsInfo = new ArrayList<>(count);
int index = 1;
for (final Properties ctx : activeContextsCopy)
{
if (ctx == null)
{
continue;
}
final String ctxInfo = index + "/" + count + ". " + toInfoString(ctx);
activeContextsInfo.add(ctxInfo);
index++;
}
return activeContextsInfo.toArray(new String[activeContextsInfo.size()]);
} | private String toInfoString(final Properties ctx)
{
final String threadName = (String)ctx.get(CTXNAME_ThreadName);
final String threadId = (String)ctx.get(CTXNAME_ThreadId);
final int adClientId = Env.getAD_Client_ID(ctx);
final int adOrgId = Env.getAD_Org_ID(ctx);
final int adUserId = Env.getAD_User_ID(ctx);
final int adRoleId = Env.getAD_Role_ID(ctx);
final int adSessionId = Env.getAD_Session_ID(ctx);
return "Thread=" + threadName + "(" + threadId + ")"
//
+ "\n"
+ ", Client/Org=" + adClientId + "/" + adOrgId
+ ", User/Role=" + adUserId + "/" + adRoleId
+ ", SessionId=" + adSessionId
//
+ "\n"
+ ", id=" + System.identityHashCode(ctx)
+ ", " + ctx.getClass()
//
+ "\n"
+ ", " + ctx.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\TraceContextProviderListener.java | 1 |
请完成以下Java代码 | private Stream<AdArchive> streamArchivesForRows(final List<? extends IViewRow> rows)
{
final ImmutableList<DocOutboundLogId> logIds = rows.stream()
.map(row -> row.getId().toId(DocOutboundLogId::ofRepoId))
.collect(ImmutableList.toImmutableList());
return streamArchivesForLogIds(logIds);
}
private Stream<AdArchive> streamArchivesForLogIds(final ImmutableList<DocOutboundLogId> logIds)
{
return docOutboundDAO.streamByIdsInOrder(logIds)
.filter(I_C_Doc_Outbound_Log::isActive)
.map(log -> getLastArchive(log).orElse(null))
.filter(Objects::nonNull);
}
@NonNull
private Optional<AdArchive> getLastArchive(final I_C_Doc_Outbound_Log log)
{
return archiveBL.getLastArchive(TableRecordReference.ofReferenced(log));
}
private void appendCurrentPdf(final PdfCopy targetPdf, final AdArchive currentLog, final Collection<ArchiveId> printedIds, final AtomicInteger errorCount)
{
PdfReader pdfReaderToAdd = null;
try
{
pdfReaderToAdd = new PdfReader(currentLog.getArchiveStream());
for (int page = 0; page < pdfReaderToAdd.getNumberOfPages(); )
{
targetPdf.addPage(targetPdf.getImportedPage(pdfReaderToAdd, ++page)); | }
targetPdf.freeReader(pdfReaderToAdd);
}
catch (final BadPdfFormatException |
IOException e)
{
errorCount.incrementAndGet();
}
finally
{
if (pdfReaderToAdd != null)
{
pdfReaderToAdd.close();
}
printedIds.add(currentLog.getId());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.webui\src\main\java\de\metas\archive\process\MassConcatenateOutboundPdfs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public RedisCacheConfiguration cacheConfiguration() {
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.disableCachingNullValues();
return cacheConfig;
}
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager rcm = RedisCacheManager.builder(redisConnectionFactory())
.cacheDefaults(cacheConfiguration())
.transactionAware()
.build();
return rcm;
} | /**
* 自定义缓存key的生成类实现
*/
@Bean(name = "myKeyGenerator")
public KeyGenerator myKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... params) {
logger.info("自定义缓存,使用第一参数作为缓存key,params = " + Arrays.toString(params));
// 仅仅用于测试,实际不可能这么写
return params[0];
}
};
}
} | repos\SpringBootBucket-master\springboot-cache\src\main\java\com\xncoding\trans\config\RedisCacheConfig.java | 2 |
请完成以下Java代码 | public IInvoiceCandRecomputeTagger setTaggedWithAnyTag()
{
return setTaggedWith(null);
}
/* package */
@Nullable
InvoiceCandRecomputeTag getTaggedWith()
{
return _taggedWith;
}
@Override
public InvoiceCandRecomputeTagger setLimit(final int limit)
{
this._limit = limit;
return this;
} | /* package */int getLimit()
{
return _limit;
}
@Override
public void setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds)
{
this.onlyInvoiceCandidateIds = onlyInvoiceCandidateIds;
}
@Override
@Nullable
public final InvoiceCandidateIdsSelection getOnlyInvoiceCandidateIds()
{
return onlyInvoiceCandidateIds;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandRecomputeTagger.java | 1 |
请完成以下Java代码 | public void setCategory (final @Nullable java.lang.String Category)
{
set_Value (COLUMNNAME_Category, Category);
}
@Override
public java.lang.String getCategory()
{
return get_ValueAsString(COLUMNNAME_Category);
}
@Override
public void setM_Ingredients_ID (final int M_Ingredients_ID)
{
if (M_Ingredients_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Ingredients_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Ingredients_ID, M_Ingredients_ID);
}
@Override
public int getM_Ingredients_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Ingredients_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{ | if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Ingredients.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public IHUQRCode parse(@NonNull final String jsonString)
{
return parse(ScannedCode.ofString(jsonString));
}
public IHUQRCode parse(@NonNull final ScannedCode scannedCode)
{
final PickOnTheFlyQRCode pickOnTheFlyQRCode = PickOnTheFlyQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (pickOnTheFlyQRCode != null)
{
return pickOnTheFlyQRCode;
}
final GlobalQRCode globalQRCode = scannedCode.toGlobalQRCodeIfMatching().orNullIfError();
if (globalQRCode != null)
{
if (HUQRCode.isHandled(globalQRCode))
{
return HUQRCode.fromGlobalQRCode(globalQRCode);
}
else if (LMQRCode.isHandled(globalQRCode))
{
return LMQRCode.fromGlobalQRCode(globalQRCode);
}
}
final CustomHUQRCode customHUQRCode = scannableCodeFormatService.parse(scannedCode)
.map(CustomHUQRCode::ofParsedScannedCode)
.orElse(null);
if (customHUQRCode != null)
{
return customHUQRCode;
} | // M_HU.Value / ExternalBarcode attribute
{
final HuId huId = handlingUnitsBL.getHUIdByValueOrExternalBarcode(scannedCode).orElse(null);
if (huId != null)
{
return getFirstQRCodeByHuId(huId);
}
}
final GS1HUQRCode gs1HUQRCode = GS1HUQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (gs1HUQRCode != null)
{
return gs1HUQRCode;
}
final EAN13HUQRCode ean13HUQRCode = EAN13HUQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (ean13HUQRCode != null)
{
return ean13HUQRCode;
}
throw new AdempiereException("QR code is not handled: " + scannedCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesService.java | 2 |
请完成以下Java代码 | private static Map<String, Vector> loadVectorMap(String modelFileName, Map<String, Vector> storage) throws IOException
{
VectorsReader reader = new VectorsReader(modelFileName);
reader.readVectorFile();
for (int i = 0; i < reader.vocab.length; i++)
{
storage.put(reader.vocab[i], new Vector(reader.matrix[i]));
}
return storage;
}
/**
* 返回跟 A - B + C 最相似的词语,比如 中国 - 北京 + 东京 = 日本。输入顺序按照 中国 北京 东京
*
* @param A 做加法的词语
* @param B 做减法的词语
* @param C 做加法的词语
* @return 与(A - B + C)语义距离最近的词语及其相似度列表
*/
public List<Map.Entry<String, Float>> analogy(String A, String B, String C)
{
return analogy(A, B, C, 10);
}
/**
* 返回跟 A - B + C 最相似的词语,比如 中国 - 北京 + 东京 = 日本。输入顺序按照 中国 北京 东京
*
* @param A 做加法的词语
* @param B 做减法的词语
* @param C 做加法的词语
* @param size topN个
* @return 与(A - B + C)语义距离最近的词语及其相似度列表
*/
public List<Map.Entry<String, Float>> analogy(String A, String B, String C, int size)
{
Vector a = storage.get(A);
Vector b = storage.get(B);
Vector c = storage.get(C);
if (a == null || b == null || c == null)
{ | return Collections.emptyList();
}
List<Map.Entry<String, Float>> resultList = nearest(a.minus(b).add(c), size + 3);
ListIterator<Map.Entry<String, Float>> listIterator = resultList.listIterator();
while (listIterator.hasNext())
{
String key = listIterator.next().getKey();
if (key.equals(A) || key.equals(B) || key.equals(C))
{
listIterator.remove();
}
}
if (resultList.size() > size)
{
resultList = resultList.subList(0, size);
}
return resultList;
}
@Override
public Vector query(String query)
{
return vector(query);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\WordVectorModel.java | 1 |
请完成以下Java代码 | public <T extends CoreExecution> void performOperationSync(CoreAtomicOperation<T> operation) {
LOG.debugPerformingAtomicOperation(operation, this);
operation.execute((T) this);
}
// event handling ////////////////////////////////////////////////////////
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public CoreModelElement getEventSource() {
return eventSource;
}
public void setEventSource(CoreModelElement eventSource) {
this.eventSource = eventSource;
}
public int getListenerIndex() {
return listenerIndex;
}
public void setListenerIndex(int listenerIndex) {
this.listenerIndex = listenerIndex;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void invokeListener(DelegateListener listener) throws Exception {
listener.notify(this);
}
public boolean hasFailedOnEndListeners() {
return false;
}
// getters / setters /////////////////////////////////////////////////
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBusinessKeyWithoutCascade() {
return businessKeyWithoutCascade;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
this.businessKeyWithoutCascade = businessKey;
}
public String getTenantId() {
return tenantId;
} | public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMapping;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMapping = skipIoMappings;
}
public boolean isSkipSubprocesses() {
return skipSubprocesses;
}
public void setSkipSubprocesseses(boolean skipSubprocesses) {
this.skipSubprocesses = skipSubprocesses;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\instance\CoreExecution.java | 1 |
请完成以下Java代码 | public int getAD_NotificationGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_NotificationGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getAD_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setAD_User(org.compiere.model.I_AD_User AD_User)
{
set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User);
}
/** Set Ansprechpartner.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Notification Group.
@param AD_User_NotificationGroup_ID User Notification Group */
@Override
public void setAD_User_NotificationGroup_ID (int AD_User_NotificationGroup_ID)
{
if (AD_User_NotificationGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_NotificationGroup_ID, null);
else | set_ValueNoCheck (COLUMNNAME_AD_User_NotificationGroup_ID, Integer.valueOf(AD_User_NotificationGroup_ID));
}
/** Get User Notification Group.
@return User Notification Group */
@Override
public int getAD_User_NotificationGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_NotificationGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* NotificationType AD_Reference_ID=344
* Reference name: AD_User NotificationType
*/
public static final int NOTIFICATIONTYPE_AD_Reference_ID=344;
/** EMail = E */
public static final String NOTIFICATIONTYPE_EMail = "E";
/** Notice = N */
public static final String NOTIFICATIONTYPE_Notice = "N";
/** None = X */
public static final String NOTIFICATIONTYPE_None = "X";
/** EMailPlusNotice = B */
public static final String NOTIFICATIONTYPE_EMailPlusNotice = "B";
/** NotifyUserInCharge = O */
public static final String NOTIFICATIONTYPE_NotifyUserInCharge = "O";
/** Set Benachrichtigungs-Art.
@param NotificationType
Art der Benachrichtigung
*/
@Override
public void setNotificationType (java.lang.String NotificationType)
{
set_Value (COLUMNNAME_NotificationType, NotificationType);
}
/** Get Benachrichtigungs-Art.
@return Art der Benachrichtigung
*/
@Override
public java.lang.String getNotificationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_NotificationType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_NotificationGroup.java | 1 |
请完成以下Java代码 | public abstract class TenantQueryImpl extends AbstractQuery<TenantQuery, Tenant> implements TenantQuery {
private static final long serialVersionUID = 1L;
protected String id;
protected String[] ids;
protected String name;
protected String nameLike;
protected String userId;
protected String groupId;
protected boolean includingGroups = false;
public TenantQueryImpl() {
}
public TenantQueryImpl(CommandExecutor commandExecutor) {
super(commandExecutor);
}
public TenantQuery tenantId(String id) {
ensureNotNull("tenant ud", id);
this.id = id;
return this;
}
public TenantQuery tenantIdIn(String... ids) {
ensureNotNull("tenant ids", (Object[]) ids);
this.ids = ids;
return this;
}
public TenantQuery tenantName(String name) {
ensureNotNull("tenant name", name);
this.name = name;
return this;
}
public TenantQuery tenantNameLike(String nameLike) {
ensureNotNull("tenant name like", nameLike);
this.nameLike = nameLike;
return this;
}
public TenantQuery userMember(String userId) {
ensureNotNull("user id", userId);
this.userId = userId;
return this;
}
public TenantQuery groupMember(String groupId) {
ensureNotNull("group id", groupId);
this.groupId = groupId;
return this;
} | public TenantQuery includingGroupsOfUser(boolean includingGroups) {
this.includingGroups = includingGroups;
return this;
}
//sorting ////////////////////////////////////////////////////////
public TenantQuery orderByTenantId() {
return orderBy(TenantQueryProperty.GROUP_ID);
}
public TenantQuery orderByTenantName() {
return orderBy(TenantQueryProperty.NAME);
}
//getters ////////////////////////////////////////////////////////
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String[] getIds() {
return ids;
}
public String getUserId() {
return userId;
}
public String getGroupId() {
return groupId;
}
public boolean isIncludingGroups() {
return includingGroups;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TenantQueryImpl.java | 1 |
请完成以下Java代码 | public BigDecimal getBalance() {
return balance;
}
/** 支付宝账户余额 **/
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
/** 购买人帐号 **/
public String getBuyerAccount() {
return buyerAccount;
}
/** 购买人帐号 **/
public void setBuyerAccount(String buyerAccount) {
this.buyerAccount = buyerAccount;
}
/** 商品名称 **/
public String getGoodsTitle() {
return goodsTitle;
}
/** 商品名称 **/
public void setGoodsTitle(String goodsTitle) {
this.goodsTitle = goodsTitle;
}
/** 平台账户入账金额 **/
public BigDecimal getIncome() {
return income;
}
/** 平台账户入账金额 **/
public void setIncome(BigDecimal income) {
this.income = income;
}
/** 平台账户出款金额 **/
public BigDecimal getOutcome() {
return outcome;
}
/** 平台账户出款金额 **/
public void setOutcome(BigDecimal outcome) {
this.outcome = outcome;
}
/** 商户订单号 **/
public String getMerchantOrderNo() {
return merchantOrderNo;
}
/** 商户订单号 **/
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo;
}
/** 银行费率 **/
public BigDecimal getBankRate() {
return bankRate;
} | /** 银行费率 **/
public void setBankRate(BigDecimal bankRate) {
this.bankRate = bankRate;
}
/** 订单金额 **/
public BigDecimal getTotalFee() {
return totalFee;
}
/** 订单金额 **/
public void setTotalFee(BigDecimal totalFee) {
this.totalFee = totalFee;
}
/** 银行流水 **/
public String getTradeNo() {
return tradeNo;
}
/** 银行流水 **/
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
/** 交易类型 **/
public String getTransType() {
return transType;
}
/** 交易类型 **/
public void setTransType(String transType) {
this.transType = transType;
}
/** 交易时间 **/
public Date getTransDate() {
return transDate;
}
/** 交易时间 **/
public void setTransDate(Date transDate) {
this.transDate = transDate;
}
/** 银行(支付宝)该笔订单收取的手续费 **/
public BigDecimal getBankFee() {
return bankFee;
}
/** 银行(支付宝)该笔订单收取的手续费 **/
public void setBankFee(BigDecimal bankFee) {
this.bankFee = bankFee;
}
} | repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\vo\AlipayAccountLogVO.java | 1 |
请完成以下Java代码 | public void setIsMainVAT (final boolean IsMainVAT)
{
set_ValueNoCheck (COLUMNNAME_IsMainVAT, IsMainVAT);
}
@Override
public boolean isMainVAT()
{
return get_ValueAsBoolean(COLUMNNAME_IsMainVAT);
}
@Override
public void setIsTaxExempt (final boolean IsTaxExempt)
{
set_ValueNoCheck (COLUMNNAME_IsTaxExempt, IsTaxExempt);
}
@Override
public boolean isTaxExempt()
{
return get_ValueAsBoolean(COLUMNNAME_IsTaxExempt);
}
@Override
public void setRate (final @Nullable BigDecimal Rate)
{
set_Value (COLUMNNAME_Rate, Rate);
}
@Override
public BigDecimal getRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSurchargeAmt (final BigDecimal SurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_SurchargeAmt, SurchargeAmt);
}
@Override
public BigDecimal getSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxAmt (final @Nullable BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxAmtWithSurchargeAmt (final BigDecimal TaxAmtWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxAmtWithSurchargeAmt, TaxAmtWithSurchargeAmt);
}
@Override
public BigDecimal getTaxAmtWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxBaseAmt (final @Nullable BigDecimal TaxBaseAmt)
{
set_Value (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
@Override
public BigDecimal getTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxBaseAmtWithSurchargeAmt (final BigDecimal TaxBaseAmtWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxBaseAmtWithSurchargeAmt, TaxBaseAmtWithSurchargeAmt);
}
@Override
public BigDecimal getTaxBaseAmtWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmtWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalAmt (final @Nullable BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
@Override
public BigDecimal getTotalAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_901_991_v.java | 1 |
请完成以下Java代码 | public class LastUpdatedInspector implements IRecordInspector
{
public static LastUpdatedInspector INSTANCE = new LastUpdatedInspector();
private LastUpdatedInspector()
{
}
@Override
public int inspectRecord(final Object model)
{
final Timestamp value;
final Optional<Timestamp> updated = InterfaceWrapperHelper.getValue(model, I_AD_Column.COLUMNNAME_Updated);
if (updated.isPresent())
{
value = updated.get();
}
else
{
final Optional<Timestamp> created = InterfaceWrapperHelper.getValue(model, I_AD_Column.COLUMNNAME_Created);
Check.errorUnless(created.isPresent(), "model={} does not have an {}-value ", model, I_AD_Column.COLUMNNAME_Created);
value = created.get(); | }
final boolean modelIsOld = TimeUtil.addMonths(value, 1).after(SystemTime.asDate());
return modelIsOld ? IMigratorService.DLM_Level_ARCHIVE : IMigratorService.DLM_Level_LIVE;
}
/**
* Returns <code>true</code> if the given model has an <code>Updated</code> column.
*/
@Override
public boolean isApplicableFor(final Object model)
{
return InterfaceWrapperHelper.hasModelColumnName(model, I_AD_Column.COLUMNNAME_Updated)
|| InterfaceWrapperHelper.hasModelColumnName(model, I_AD_Column.COLUMNNAME_Created);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\coordinator\impl\LastUpdatedInspector.java | 1 |
请完成以下Java代码 | protected void parseRootElement() {
List<ProcessEngineXml> processEngines = new ArrayList<ProcessEngineXml>();
List<ProcessArchiveXml> processArchives = new ArrayList<ProcessArchiveXml>();
for (Element element : rootElement.elements()) {
if(PROCESS_ENGINE.equals(element.getTagName())) {
parseProcessEngine(element, processEngines);
} else if(PROCESS_ARCHIVE.equals(element.getTagName())) {
parseProcessArchive(element, processArchives);
}
}
processesXml = new ProcessesXmlImpl(processEngines, processArchives);
}
/**
* parse a <code><process-archive .../></code> element and add it to the list of parsed elements
*/
protected void parseProcessArchive(Element element, List<ProcessArchiveXml> parsedProcessArchives) {
ProcessArchiveXmlImpl processArchive = new ProcessArchiveXmlImpl();
processArchive.setName(element.attribute(NAME));
processArchive.setTenantId(element.attribute(TENANT_ID));
List<String> processResourceNames = new ArrayList<String>();
Map<String, String> properties = new HashMap<String, String>();
for (Element childElement : element.elements()) {
if(PROCESS_ENGINE.equals(childElement.getTagName())) {
processArchive.setProcessEngineName(childElement.getText()); | } else if(PROCESS.equals(childElement.getTagName()) || RESOURCE.equals(childElement.getTagName())) {
processResourceNames.add(childElement.getText());
} else if(PROPERTIES.equals(childElement.getTagName())) {
parseProperties(childElement, properties);
}
}
// set properties
processArchive.setProperties(properties);
// add collected resource names.
processArchive.setProcessResourceNames(processResourceNames);
// add process archive to list of parsed archives.
parsedProcessArchives.add(processArchive);
}
public ProcessesXml getProcessesXml() {
return processesXml;
}
@Override
public ProcessesXmlParse sourceUrl(URL url) {
super.sourceUrl(url);
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\metadata\ProcessesXmlParse.java | 1 |
请完成以下Java代码 | private static UUID constructType5UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++) {
msb = (msb << 8) | (data[i] & 0xff);
}
for (int i = 8; i < 16; i++) {
lsb = (lsb << 8) | (data[i] & 0xff);
}
return new UUID(msb, lsb);
}
private static byte[] bytesFromUUID(String uuidHexString) {
final String normalizedUUIDHexString = uuidHexString.replace("-", "");
assert normalizedUUIDHexString.length() == 32;
final byte[] bytes = new byte[16];
for (int i = 0; i < 16; i++) {
final byte b = hexToByte(normalizedUUIDHexString.substring(i * 2, i * 2 + 2));
bytes[i] = b;
}
return bytes;
}
public static byte hexToByte(String hexString) {
final int firstDigit = Character.digit(hexString.charAt(0), 16);
final int secondDigit = Character.digit(hexString.charAt(1), 16);
return (byte) ((firstDigit << 4) + secondDigit);
}
public static byte[] joinBytes(byte[] byteArray1, byte[] byteArray2) {
final int finalLength = byteArray1.length + byteArray2.length;
final byte[] result = new byte[finalLength];
System.arraycopy(byteArray1, 0, result, 0, byteArray1.length);
System.arraycopy(byteArray2, 0, result, byteArray1.length, byteArray2.length);
return result;
}
public static UUID generateType5UUID(String name) { | try {
final byte[] bytes = name.getBytes(StandardCharsets.UTF_8);
final MessageDigest md = MessageDigest.getInstance("SHA-1");
final byte[] hash = md.digest(bytes);
long msb = getLeastAndMostSignificantBitsVersion5(hash, 0);
long lsb = getLeastAndMostSignificantBitsVersion5(hash, 8);
// Set the version field
msb &= ~(0xfL << 12);
msb |= 5L << 12;
// Set the variant field to 2
lsb &= ~(0x3L << 62);
lsb |= 2L << 62;
return new UUID(msb, lsb);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static long getLeastAndMostSignificantBitsVersion5(final byte[] src, final int offset) {
long ans = 0;
for (int i = offset + 7; i >= offset; i -= 1) {
ans <<= 8;
ans |= src[i] & 0xffL;
}
return ans;
}
} | repos\tutorials-master\core-java-modules\core-java-uuid-generation\src\main\java\com\baeldung\uuid\UUIDGenerator.java | 1 |
请完成以下Java代码 | public class ProcessDefinitionResource extends AbstractPluginResource {
protected String id;
public ProcessDefinitionResource(String engineName, String id) {
super(engineName);
this.id = id;
}
@GET
@Path("/called-process-definitions")
@Produces(MediaType.APPLICATION_JSON)
public List<ProcessDefinitionDto> getCalledProcessDefinitions(@Context UriInfo uriInfo) {
ProcessDefinitionQueryDto queryParameter = new ProcessDefinitionQueryDto(uriInfo.getQueryParameters());
return queryCalledProcessDefinitions(queryParameter);
}
@POST
@Path("/called-process-definitions")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<ProcessDefinitionDto> queryCalledProcessDefinitions(ProcessDefinitionQueryDto queryParameter) {
return getCommandExecutor().executeCommand(new QueryCalledProcessDefinitionsCmd(queryParameter));
}
private void injectEngineConfig(ProcessDefinitionQueryDto parameter) {
ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl) getProcessEngine()).getProcessEngineConfiguration();
if (processEngineConfiguration.getHistoryLevel().equals(HistoryLevel.HISTORY_LEVEL_NONE)) {
parameter.setHistoryEnabled(false);
}
parameter.initQueryVariableValues(processEngineConfiguration.getVariableSerializers(), processEngineConfiguration.getDatabaseType());
}
protected void configureExecutionQuery(ProcessDefinitionQueryDto query) { | configureAuthorizationCheck(query);
configureTenantCheck(query);
addPermissionCheck(query, PROCESS_INSTANCE, "EXEC2.PROC_INST_ID_", READ);
addPermissionCheck(query, PROCESS_DEFINITION, "PROCDEF.KEY_", READ_INSTANCE);
}
protected class QueryCalledProcessDefinitionsCmd implements Command<List<ProcessDefinitionDto>> {
protected ProcessDefinitionQueryDto queryParameter;
public QueryCalledProcessDefinitionsCmd(ProcessDefinitionQueryDto queryParameter) {
this.queryParameter = queryParameter;
}
@Override
public List<ProcessDefinitionDto> execute(CommandContext commandContext) {
queryParameter.setParentProcessDefinitionId(id);
injectEngineConfig(queryParameter);
configureExecutionQuery(queryParameter);
queryParameter.disableMaxResultsLimit();
return getQueryService().executeQuery("selectCalledProcessDefinitions", queryParameter);
}
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\sub\resources\ProcessDefinitionResource.java | 1 |
请完成以下Java代码 | public long iterateKeysUsingKeySetAndEnhanceForLoop(Map<Integer, Integer> map) {
long sum = 0;
for (Integer key : map.keySet()) {
sum += map.get(key);
}
return sum;
}
public long iterateValuesUsingValuesMethodAndEnhanceForLoop(Map<Integer, Integer> map) {
long sum = 0;
for (Integer value : map.values()) {
sum += value;
}
return sum;
}
public long iterateUsingMapIteratorApacheCollection(IterableMap<Integer, Integer> map) {
long sum = 0;
MapIterator<Integer, Integer> iterate = map.mapIterator();
while (iterate.hasNext()) {
iterate.next();
sum += iterate.getValue();
}
return sum; | }
public long iterateEclipseMap(MutableMap<Integer, Integer> mutableMap) throws IOException {
AtomicLong sum = new AtomicLong(0);
mutableMap.forEachKeyValue((key, value) -> {
sum.addAndGet(value);
});
return sum.get();
}
public long iterateMapUsingParallelStreamApi(Map<Integer, Integer> map) throws IOException {
return map.entrySet()
.parallelStream()
.mapToLong(Map.Entry::getValue)
.sum();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\iteration\MapIteration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RolePermissionReq extends AbsReq {
/** 角色ID */
private String roleId;
/** 权限ID列表 */
private List<String> permissionIdList;
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public List<String> getPermissionIdList() { | return permissionIdList;
}
public void setPermissionIdList(List<String> permissionIdList) {
this.permissionIdList = permissionIdList;
}
@Override
public String toString() {
return "RolePermissionReq{" +
"roleId='" + roleId + '\'' +
", permissionIdList=" + permissionIdList +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\RolePermissionReq.java | 2 |
请完成以下Java代码 | protected void checkAssignedEntityViewsToEdge(TenantId tenantId, EntityId entityId, EdgeId edgeId) {
List<EntityView> entityViews = entityViewService.findEntityViewsByTenantIdAndEntityId(tenantId, entityId);
if (entityViews != null && !entityViews.isEmpty()) {
EntityView entityView = entityViews.get(0);
boolean relationExists = relationService.checkRelation(
tenantId, edgeId, entityView.getId(),
EntityRelation.CONTAINS_TYPE, RelationTypeGroup.EDGE
);
if (relationExists) {
throw new DataValidationException("Can't unassign device/asset from edge that is related to entity view and entity view is assigned to edge!");
}
}
}
protected void updateDebugSettings(TenantId tenantId, HasDebugSettings entity, long now) {
if (entity.getDebugSettings() != null) {
entity.setDebugSettings(entity.getDebugSettings().copy(getMaxDebugAllUntil(tenantId, now)));
} else if (entity.isDebugMode()) {
entity.setDebugSettings(DebugSettings.failuresOrUntil(getMaxDebugAllUntil(tenantId, now)));
entity.setDebugMode(false);
}
}
private long getMaxDebugAllUntil(TenantId tenantId, long now) {
return now + TimeUnit.MINUTES.toMillis(DebugModeUtil.getMaxDebugAllDuration(tbTenantProfileCache.get(tenantId).getDefaultProfileConfiguration().getMaxDebugModeDurationMinutes(), defaultDebugDurationMinutes));
}
protected <E extends HasId<?> & HasTenantId & HasName> void uniquifyEntityName(E entity, E oldEntity, Consumer<String> setName, EntityType entityType, NameConflictStrategy strategy) {
Dao<?> dao = entityDaoRegistry.getDao(entityType);
List<EntityInfo> existingEntities = dao.findEntityInfosByNamePrefix(entity.getTenantId(), entity.getName());
Set<String> existingNames = existingEntities.stream()
.filter(e -> (oldEntity == null || !e.getId().equals(oldEntity.getId())))
.map(EntityInfo::getName)
.collect(Collectors.toSet());
if (existingNames.contains(entity.getName())) {
String uniqueName = generateUniqueName(entity.getName(), existingNames, strategy);
setName.accept(uniqueName); | }
}
private String generateUniqueName(String baseName, Set<String> existingNames, NameConflictStrategy strategy) {
String newName;
int index = 1;
String separator = strategy.separator();
boolean isRandom = strategy.uniquifyStrategy() == RANDOM;
do {
String suffix = isRandom ? StringUtils.randomAlphanumeric(6) : String.valueOf(index++);
newName = baseName + separator + suffix;
} while (existingNames.contains(newName));
return newName;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\entity\AbstractEntityService.java | 1 |
请完成以下Java代码 | public Builder setCustomProcessApplyPredicate(@Nullable final BiPredicate<HUEditorRow, ProcessDescriptor> processApplyPredicate)
{
this.customProcessApplyPredicate = processApplyPredicate;
return this;
}
@Nullable
private BiPredicate<HUEditorRow, ProcessDescriptor> getCustomProcessApplyPredicate()
{
return this.customProcessApplyPredicate;
}
/**
* @param currentRow the row that is currently constructed using this builder
*/
private ImmutableMultimap<OrderLineId, HUEditorRow> prepareIncludedOrderLineReservations(@NonNull final HUEditorRow currentRow)
{
final ImmutableMultimap.Builder<OrderLineId, HUEditorRow> includedOrderLineReservationsBuilder = ImmutableMultimap.builder();
for (final HUEditorRow includedRow : buildIncludedRows())
{
includedOrderLineReservationsBuilder.putAll(includedRow.getIncludedOrderLineReservations());
}
if (orderLineReservation != null)
{
includedOrderLineReservationsBuilder.put(orderLineReservation, currentRow); | }
return includedOrderLineReservationsBuilder.build();
}
}
@lombok.Builder
@lombok.Value
public static class HUEditorRowHierarchy
{
@NonNull HUEditorRow cuRow;
@Nullable
HUEditorRow parentRow;
@Nullable
HUEditorRow topLevelRow;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRow.java | 1 |
请完成以下Java代码 | public String getName() {
return wrappedQueryValue.getName();
}
public String getTextValue() {
return textValue;
}
public void setTextValue(String textValue) {
this.textValue = textValue;
}
public String getTextValue2() {
return textValue2;
}
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
public Long getLongValue() {
return longValue;
}
public void setLongValue(Long longValue) {
this.longValue = longValue;
}
public Double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
} | public byte[] getByteArrayValue() {
return null;
}
public void setByteArrayValue(byte[] bytes) {
}
public String getType() {
return type;
}
public boolean getFindNulledEmptyStrings() {
return findNulledEmptyStrings;
}
public void setFindNulledEmptyStrings(boolean findNulledEmptyStrings) {
this.findNulledEmptyStrings = findNulledEmptyStrings;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\SingleQueryVariableValueCondition.java | 1 |
请完成以下Java代码 | public void setAD_WF_Node_Template_ID (final int AD_WF_Node_Template_ID)
{
if (AD_WF_Node_Template_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Template_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Template_ID, AD_WF_Node_Template_ID);
}
@Override
public int getAD_WF_Node_Template_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Node_Template_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);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node_Template.java | 1 |
请完成以下Java代码 | public void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<V> processor)
{
LongestSearcher searcher = getLongestSearcher(text, 0);
while (searcher.next())
{
processor.hit(searcher.begin, searcher.begin + searcher.length, searcher.value);
}
}
/**
* 转移状态
*
* @param current
* @param c
* @return
*/
protected int transition(int current, char c)
{
int b = base[current];
int p;
p = b + c + 1;
if (b == check[p])
b = base[p];
else
return -1;
p = b;
return p;
}
/**
* 更新某个键对应的值
*
* @param key 键
* @param value 值
* @return 是否成功(失败的原因是没有这个键)
*/
public boolean set(String key, V value)
{
int index = exactMatchSearch(key);
if (index >= 0)
{
v[index] = value;
return true;
}
return false;
}
/**
* 从值数组中提取下标为index的值<br> | * 注意为了效率,此处不进行参数校验
*
* @param index 下标
* @return 值
*/
public V get(int index)
{
return v[index];
}
/**
* 释放空闲的内存
*/
private void shrink()
{
// if (HanLP.Config.DEBUG)
// {
// System.err.printf("释放内存 %d bytes\n", base.length - size - 65535);
// }
int nbase[] = new int[size + 65535];
System.arraycopy(base, 0, nbase, 0, size);
base = nbase;
int ncheck[] = new int[size + 65535];
System.arraycopy(check, 0, ncheck, 0, size);
check = ncheck;
}
/**
* 打印统计信息
*/
// public void report()
// {
// System.out.println("size: " + size);
// int nonZeroIndex = 0;
// for (int i = 0; i < base.length; i++)
// {
// if (base[i] != 0) nonZeroIndex = i;
// }
// System.out.println("BaseUsed: " + nonZeroIndex);
// nonZeroIndex = 0;
// for (int i = 0; i < check.length; i++)
// {
// if (check[i] != 0) nonZeroIndex = i;
// }
// System.out.println("CheckUsed: " + nonZeroIndex);
// }
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\DoubleArrayTrie.java | 1 |
请完成以下Java代码 | 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 Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public void setSourceAmt (final @Nullable BigDecimal SourceAmt) | {
set_Value (COLUMNNAME_SourceAmt, SourceAmt);
}
@Override
public BigDecimal getSourceAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SourceAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSource_Currency_ID (final int Source_Currency_ID)
{
if (Source_Currency_ID < 1)
set_Value (COLUMNNAME_Source_Currency_ID, null);
else
set_Value (COLUMNNAME_Source_Currency_ID, Source_Currency_ID);
}
@Override
public int getSource_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Currency_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostDetail.java | 1 |
请完成以下Java代码 | private List<PrimeNumbers> subTasks() {
List<PrimeNumbers> subTasks = new ArrayList<>();
for (int i = 1; i <= this.upperBound / granularity; i++) {
int upper = i * granularity;
int lower = (upper - granularity) + 1;
subTasks.add(new PrimeNumbers(lower, upper, noOfPrimeNumbers));
}
return subTasks;
}
@Override
protected void compute() {
if (((upperBound + 1) - lowerBound) > granularity) {
ForkJoinTask.invokeAll(subTasks());
} else {
findPrimeNumbers();
}
}
void findPrimeNumbers() {
for (int num = lowerBound; num <= upperBound; num++) {
if (isPrime(num)) {
noOfPrimeNumbers.getAndIncrement();
}
}
} | private boolean isPrime(int number) {
if (number == 2) {
return true;
}
if (number == 1 || number % 2 == 0) {
return false;
}
int noOfNaturalNumbers = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
noOfNaturalNumbers++;
}
}
return noOfNaturalNumbers == 2;
}
public int noOfPrimeNumbers() {
return noOfPrimeNumbers.intValue();
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\workstealing\PrimeNumbers.java | 1 |
请完成以下Java代码 | public void setCandidateStarterUsers(List<String> candidateStarterUsers) {
this.candidateStarterUsers = candidateStarterUsers;
}
public List<String> getCandidateStarterGroups() {
return candidateStarterGroups;
}
public void setCandidateStarterGroups(List<String> candidateStarterGroups) {
this.candidateStarterGroups = candidateStarterGroups;
}
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public Map<String, CaseElement> getAllCaseElements() {
return allCaseElements;
}
public void setAllCaseElements(Map<String, CaseElement> allCaseElements) {
this.allCaseElements = allCaseElements;
}
public <T extends PlanItemDefinition> List<T> findPlanItemDefinitionsOfType(Class<T> type) {
return planModel.findPlanItemDefinitionsOfType(type, true);
} | public ReactivateEventListener getReactivateEventListener() {
return reactivateEventListener;
}
public void setReactivateEventListener(ReactivateEventListener reactivateEventListener) {
this.reactivateEventListener = reactivateEventListener;
}
@Override
public List<FlowableListener> getLifecycleListeners() {
return this.lifecycleListeners;
}
@Override
public void setLifecycleListeners(List<FlowableListener> lifecycleListeners) {
this.lifecycleListeners = lifecycleListeners;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Case.java | 1 |
请完成以下Spring Boot application配置 | quarkus.datasource.db-kind=mysql
quarkus.datasource.username=root
quarkus.datasource.password=root
quarkus.datasource.reactive.url=${DB_URL:mysql://localhost:3306/baeldung?useSSL=true&requireSSL=true}
quarkus.datasource.reactive.max-size=95
quarkus.datasource.reactive.mysql.ssl-mode=required
#quarkus.hibernate-orm.log.sql=true |
quarkus.hibernate-orm.database.generation=drop-and-create
quarkus.native.enable-vm-inspection=true
quarkus.datasource.reactive.trust-all=true | repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\quarkus-project\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public static void assertTrue(String message, boolean condition) {
if (!condition) {
throw new JeecgBootAssertException(message);
}
}
/**
* 验证 condition是否为false
*
* @param message
* @param condition
*/
public static void assertFalse(String message, boolean condition) {
assertTrue(message, !condition);
}
/**
* 验证是否存在
*
* @param message
* @param obj
* @param objs
* @param <T>
* @throws JeecgBootAssertException
* @author chenrui
* @date 2018/1/31 22:14
*/
public static <T> void assertIn(String message, T obj, T... objs) {
assertNotEmpty(message, obj);
assertNotEmpty(message, objs);
if (!oConvertUtils.isIn(obj, objs)) {
throw new JeecgBootAssertException(message);
}
}
/**
* 验证是否不存在
*
* @param message
* @param obj
* @param objs
* @param <T>
* @throws JeecgBootAssertException
* @author chenrui
* @date 2018/1/31 22:14
*/
public static <T> void assertNotIn(String message, T obj, T... objs) {
assertNotEmpty(message, obj);
assertNotEmpty(message, objs);
if (oConvertUtils.isIn(obj, objs)) {
throw new JeecgBootAssertException(message);
}
}
/**
* 确保src大于des
*
* @param message
* @param src
* @param des
* @author chenrui | * @date 2018/9/19 15:30
*/
public static void assertGt(String message, Number src, Number des) {
if (oConvertUtils.isGt(src, des)) {
return;
}
throw new JeecgBootAssertException(message);
}
/**
* 确保src大于等于des
*
* @param message
* @param src
* @param des
* @author chenrui
* @date 2018/9/19 15:30
*/
public static void assertGe(String message, Number src, Number des) {
if (oConvertUtils.isGe(src, des)) {
return;
}
throw new JeecgBootAssertException(message);
}
/**
* 确保src小于des
*
* @param message
* @param src
* @param des
* @author chenrui
* @date 2018/9/19 15:30
*/
public static void assertLt(String message, Number src, Number des) {
if (oConvertUtils.isGe(src, des)) {
throw new JeecgBootAssertException(message);
}
}
/**
* 确保src小于等于des
*
* @param message
* @param src
* @param des
* @author chenrui
* @date 2018/9/19 15:30
*/
public static void assertLe(String message, Number src, Number des) {
if (oConvertUtils.isGt(src, des)) {
throw new JeecgBootAssertException(message);
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\AssertUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class KafkaStreamsDefaultConfiguration {
/**
* The bean name for the {@link org.apache.kafka.streams.StreamsConfig} to be used for the default
* {@link StreamsBuilderFactoryBean} bean definition.
*/
public static final String DEFAULT_STREAMS_CONFIG_BEAN_NAME = "defaultKafkaStreamsConfig";
/**
* The bean name for auto-configured default {@link StreamsBuilderFactoryBean}.
*/
public static final String DEFAULT_STREAMS_BUILDER_BEAN_NAME = "defaultKafkaStreamsBuilder";
/**
* Bean for the default {@link StreamsBuilderFactoryBean}.
* @param streamsConfigProvider the streams config.
* @param configurerProvider the configurer.
*
* @return the factory bean.
*/
@Bean(name = DEFAULT_STREAMS_BUILDER_BEAN_NAME)
public StreamsBuilderFactoryBean defaultKafkaStreamsBuilder( | @Qualifier(DEFAULT_STREAMS_CONFIG_BEAN_NAME)
ObjectProvider<KafkaStreamsConfiguration> streamsConfigProvider,
ObjectProvider<StreamsBuilderFactoryBeanConfigurer> configurerProvider) {
KafkaStreamsConfiguration streamsConfig = streamsConfigProvider.getIfAvailable();
if (streamsConfig != null) {
StreamsBuilderFactoryBean fb = new StreamsBuilderFactoryBean(streamsConfig);
configurerProvider.orderedStream().forEach(configurer -> configurer.configure(fb));
return fb;
}
else {
throw new UnsatisfiedDependencyException(KafkaStreamsDefaultConfiguration.class.getName(),
DEFAULT_STREAMS_BUILDER_BEAN_NAME, "streamsConfig", "There is no '" +
DEFAULT_STREAMS_CONFIG_BEAN_NAME + "' " + KafkaStreamsConfiguration.class.getName() +
" bean in the application context.\n" +
"Consider declaring one or don't use @EnableKafkaStreams.");
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\annotation\KafkaStreamsDefaultConfiguration.java | 2 |
请完成以下Java代码 | public static WFProcess toWFProcess(final ManufacturingJob job)
{
return WFProcess.builder()
.id(WFProcessId.ofIdPart(ManufacturingMobileApplication.APPLICATION_ID, job.getPpOrderId()))
.responsibleId(job.getResponsibleId())
.document(job)
.activities(job.getActivities()
.stream()
.map(ManufacturingRestService::toWFActivity)
.collect(ImmutableList.toImmutableList()))
.build();
}
public ManufacturingJob processEvent(final ManufacturingJob job, final JsonManufacturingOrderEvent event)
{
job.assertUserReporting();
if (event.getIssueTo() != null)
{
final JsonManufacturingOrderEvent.IssueTo issueTo = event.getIssueTo();
return manufacturingJobService.issueRawMaterials(job, PPOrderIssueScheduleProcessRequest.builder()
.activityId(PPOrderRoutingActivityId.ofRepoId(job.getPpOrderId(), event.getWfActivityId()))
.issueScheduleId(PPOrderIssueScheduleId.ofString(issueTo.getIssueStepId()))
.huWeightGrossBeforeIssue(issueTo.getHuWeightGrossBeforeIssue())
.qtyIssued(issueTo.getQtyIssued())
.qtyRejected(issueTo.getQtyRejected())
.qtyRejectedReasonCode(QtyRejectedReasonCode.ofNullableCode(issueTo.getQtyRejectedReasonCode()).orElse(null))
// Manual issues from mobile UI shall fail for IssueOnlyForReceived lines
.failIfIssueOnlyForReceived(true) | .build());
}
else if (event.getReceiveFrom() != null)
{
final JsonManufacturingOrderEvent.ReceiveFrom receiveFrom = event.getReceiveFrom();
return manufacturingJobService.receiveGoods(receiveFrom, job, SystemTime.asZonedDateTime());
}
else
{
throw new AdempiereException("Cannot handle: " + event);
}
}
public QueryLimit getLaunchersLimit()
{
return manufacturingJobService.getLaunchersLimit();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\ManufacturingRestService.java | 1 |
请完成以下Java代码 | public Set<AdWindowId> retrieveWindowIdsWithMissingADElements()
{
return queryBL.createQueryBuilder(I_AD_Window.class)
.addEqualsFilter(I_AD_Window.COLUMN_AD_Element_ID, null)
.create()
.idsAsSet(AdWindowId::ofRepoId);
}
@Override
public I_AD_Window getById(@NonNull final AdWindowId adWindowId)
{
return loadOutOfTrx(adWindowId, I_AD_Window.class);
}
@Override
public I_AD_Window getWindowByIdInTrx(@NonNull final AdWindowId windowId)
{
// use the load with ITrx.TRXNAME_ThreadInherited because the window may not yet be saved in DB when it's needed
return load(windowId, I_AD_Window.class);
}
@Override
public I_AD_Tab getTabByIdInTrx(@NonNull final AdTabId tabId)
{
// use the load with ITrx.TRXNAME_ThreadInherited because the tab may not yet be saved in DB when it's needed
return load(tabId, I_AD_Tab.class);
}
@Override
public void deleteUIElementsByFieldId(@NonNull final AdFieldId adFieldId)
{
queryBL.createQueryBuilder(I_AD_UI_Element.class)
.addEqualsFilter(I_AD_UI_Element.COLUMN_AD_Field_ID, adFieldId)
.create()
.delete();
}
@Override
public void deleteUISectionsByTabId(@NonNull final AdTabId adTabId)
{
queryBL.createQueryBuilder(I_AD_UI_Section.class)
.addEqualsFilter(I_AD_UI_Section.COLUMN_AD_Tab_ID, adTabId)
.create()
.delete();
}
@Override
public AdWindowId getAdWindowId( | @NonNull final String tableName,
@NonNull final SOTrx soTrx,
@NonNull final AdWindowId defaultValue)
{
final I_AD_Table adTableRecord = adTableDAO.retrieveTable(tableName);
switch (soTrx)
{
case SALES:
return CoalesceUtil.coalesce(AdWindowId.ofRepoIdOrNull(adTableRecord.getAD_Window_ID()), defaultValue);
case PURCHASE:
return CoalesceUtil.coalesce(AdWindowId.ofRepoIdOrNull(adTableRecord.getPO_Window_ID()), defaultValue);
default:
throw new AdempiereException("Param 'soTrx' has an unspupported value; soTrx=" + soTrx);
}
}
@Override
public ImmutableSet<AdWindowId> retrieveAllAdWindowIdsByTableId(final AdTableId adTableId)
{
final List<AdWindowId> adWindowIds = queryBL.createQueryBuilder(I_AD_Tab.class)
.addEqualsFilter(I_AD_Tab.COLUMNNAME_AD_Table_ID, adTableId)
.create()
.listDistinct(I_AD_Tab.COLUMNNAME_AD_Window_ID, AdWindowId.class);
return ImmutableSet.copyOf(adWindowIds);
}
@Override
public ImmutableSet<AdWindowId> retrieveAllActiveAdWindowIds()
{
return queryBL.createQueryBuilder(I_AD_Window.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_Window.COLUMNNAME_AD_Window_ID)
.create()
.idsAsSet(AdWindowId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\api\impl\ADWindowDAO.java | 1 |
请完成以下Java代码 | public void cacheInvalidate()
{
// nothing
}
@Override
public LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return this;
}
@Override
public boolean isHighVolume()
{
return true;
}
@Override
public LookupSource getLookupSourceType()
{
return LookupSource.lookup;
}
@Override
public boolean hasParameters()
{
return true;
}
@Override
public boolean isNumericKey()
{
return true;
} | @Override
public Set<String> getDependsOnFieldNames()
{
return null;
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
@Override
public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression()
{
return sqlLookupDescriptor != null ? sqlLookupDescriptor.getSqlForFetchingLookupByIdExpression() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\FullTextSearchLookupDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setManagerDn(String managerDn) {
this.managerDn = managerDn;
}
/**
* The password for the manager DN. This is required if the
* {@link #setManagerDn(String)} is specified.
* @param managerPassword password for the manager DN
*/
public void setManagerPassword(String managerPassword) {
this.managerPassword = managerPassword;
}
@Override
public DefaultSpringSecurityContextSource getObject() throws Exception {
if (!unboundIdPresent) {
throw new IllegalStateException("Embedded LDAP server is not provided");
}
this.container = getContainer();
this.port = this.container.getPort();
DefaultSpringSecurityContextSource contextSourceFromProviderUrl = new DefaultSpringSecurityContextSource(
"ldap://127.0.0.1:" + this.port + "/" + this.root);
if (this.managerDn != null) {
contextSourceFromProviderUrl.setUserDn(this.managerDn);
if (this.managerPassword == null) {
throw new IllegalStateException("managerPassword is required if managerDn is supplied");
}
contextSourceFromProviderUrl.setPassword(this.managerPassword);
}
contextSourceFromProviderUrl.afterPropertiesSet();
return contextSourceFromProviderUrl;
}
@Override
public Class<?> getObjectType() {
return DefaultSpringSecurityContextSource.class;
}
@Override
public void destroy() {
if (this.container instanceof Lifecycle) {
((Lifecycle) this.container).stop();
} | }
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
private EmbeddedLdapServerContainer getContainer() {
if (!unboundIdPresent) {
throw new IllegalStateException("Embedded LDAP server is not provided");
}
UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif);
unboundIdContainer.setApplicationContext(this.context);
unboundIdContainer.setPort(getEmbeddedServerPort());
unboundIdContainer.afterPropertiesSet();
return unboundIdContainer;
}
private int getEmbeddedServerPort() {
if (this.port == null) {
this.port = getDefaultEmbeddedServerPort();
}
return this.port;
}
private int getDefaultEmbeddedServerPort() {
try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) {
return serverSocket.getLocalPort();
}
catch (IOException ex) {
return RANDOM_PORT;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\EmbeddedLdapServerContextSourceFactoryBean.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class GatewayMetricsProperties {
/**
* Default metrics prefix.
*/
public static final String DEFAULT_PREFIX = "spring.cloud.gateway";
/**
* Enables the collection of metrics data.
*/
private boolean enabled;
/**
* The prefix of all metrics emitted by gateway.
*/
private String prefix = DEFAULT_PREFIX;
/**
* Tags map that added to metrics.
*/
@NotNull
private Map<String, String> tags = new HashMap<>();
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix; | }
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", enabled)
.append("prefix", prefix)
.append("tags", tags)
.toString();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayMetricsProperties.java | 2 |
请完成以下Java代码 | public void setDtAndPlcOfBirth(DateAndPlaceOfBirth value) {
this.dtAndPlcOfBirth = value;
}
/**
* Gets the value of the othr property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the othr property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getOthr().add(newItem); | * </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link GenericPersonIdentification1 }
*
*
*/
public List<GenericPersonIdentification1> getOthr() {
if (othr == null) {
othr = new ArrayList<GenericPersonIdentification1>();
}
return this.othr;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PersonIdentification5.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setSUMUP_LastSync_Status (final @Nullable java.lang.String SUMUP_LastSync_Status)
{
set_Value (COLUMNNAME_SUMUP_LastSync_Status, SUMUP_LastSync_Status);
}
@Override
public java.lang.String getSUMUP_LastSync_Status()
{
return get_ValueAsString(COLUMNNAME_SUMUP_LastSync_Status);
}
@Override
public void setSUMUP_LastSync_Timestamp (final @Nullable java.sql.Timestamp SUMUP_LastSync_Timestamp)
{
set_Value (COLUMNNAME_SUMUP_LastSync_Timestamp, SUMUP_LastSync_Timestamp);
}
@Override
public java.sql.Timestamp getSUMUP_LastSync_Timestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_SUMUP_LastSync_Timestamp);
}
@Override
public void setSUMUP_merchant_code (final java.lang.String SUMUP_merchant_code)
{
set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code);
}
@Override
public java.lang.String getSUMUP_merchant_code()
{
return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code);
}
@Override
public void setSUMUP_Transaction_ID (final int SUMUP_Transaction_ID)
{
if (SUMUP_Transaction_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, null);
else | set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, SUMUP_Transaction_ID);
}
@Override
public int getSUMUP_Transaction_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_Transaction_ID);
}
@Override
public void setTimestamp (final java.sql.Timestamp Timestamp)
{
set_Value (COLUMNNAME_Timestamp, Timestamp);
}
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Transaction.java | 2 |
请完成以下Java代码 | private ITranslatableString getSalesOrderDocumentNo(final OrderId orderId)
{
return salesOrderDocumentNos.computeIfAbsent(orderId, this::retrieveOrderDocumentNo);
}
private ITranslatableString retrieveOrderDocumentNo(final OrderId orderId)
{
return TranslatableStrings.anyLanguage(sourceDocService.getDocumentNoById(orderId));
}
private ITranslatableString getManufacturingOrderDocumentNo(final PPOrderId manufacturingOrderId)
{
return manufacturingOrderDocumentNos.computeIfAbsent(manufacturingOrderId, this::retrieveManufacturingOrderDocumentNo);
}
private ITranslatableString retrieveManufacturingOrderDocumentNo(final PPOrderId manufacturingOrderId)
{
return TranslatableStrings.anyLanguage(sourceDocService.getDocumentNoById(manufacturingOrderId));
}
private ITranslatableString getProductName(final ProductId productId)
{
return productNames.computeIfAbsent(productId, this::retrieveProductName);
}
private ITranslatableString retrieveProductName(final ProductId productId)
{
return TranslatableStrings.anyLanguage(productService.getProductValueAndName(productId));
}
@NonNull
public static Quantity extractQtyEntered(final I_DD_OrderLine ddOrderLine)
{
return Quantitys.of(ddOrderLine.getQtyEntered(), UomId.ofRepoId(ddOrderLine.getC_UOM_ID()));
}
private void processPendingRequests()
{
if (!pendingCollectProductsFromDDOrderIds.isEmpty())
{ | ddOrderService.getProductIdsByDDOrderIds(pendingCollectProductsFromDDOrderIds)
.forEach(this::collectProduct);
pendingCollectProductsFromDDOrderIds.clear();
}
if (!pendingCollectQuantitiesFromDDOrderIds.isEmpty())
{
ddOrderService.streamLinesByDDOrderIds(pendingCollectQuantitiesFromDDOrderIds)
.forEach(this::collectQuantity);
pendingCollectQuantitiesFromDDOrderIds.clear();
}
}
private ITranslatableString getPlantName(final ResourceId resourceId)
{
return resourceNames.computeIfAbsent(resourceId, id -> TranslatableStrings.constant(sourceDocService.getPlantName(id)));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetsCollector.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeliveryAddressUpsertProcessor implements Processor
{
@Override
public void process(final Exchange exchange)
{
final Order order = exchange.getIn().getBody(Order.class);
if (order == null)
{
throw new RuntimeException("Empty body!");
}
if (order.getDeliveryAddress() == null)
{
throw new RuntimeException("Missing delivery address! OrderId: " + order.getId());
}
final String orgCode = ProcessorHelper.getPropertyOrThrowError(exchange, GetOrdersRouteConstants.ROUTE_PROPERTY_ORG_CODE, String.class);
final JsonRequestLocationUpsert locationUpsert = getDeliveryAddressUpsertRequest(order.getDeliveryAddress(), order.getPatientId());
final BPLocationCamelRequest camelRequest = BPLocationCamelRequest.builder()
.jsonRequestLocationUpsert(locationUpsert)
.bPartnerIdentifier(ExternalIdentifierFormat.formatExternalId(order.getPatientId()))
.orgCode(orgCode)
.build();
exchange.getIn().setBody(camelRequest);
exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_CURRENT_ORDER, order);
}
@NonNull
private JsonRequestLocationUpsert getDeliveryAddressUpsertRequest(
@NonNull final OrderDeliveryAddress orderDeliveryAddress,
@NonNull final String patientId)
{
final BPartnerLocationCandidate bPartnerLocationCandidate = BPartnerLocationCandidate.fromDeliveryAddress(orderDeliveryAddress);
final String locationHash = computeHashKey(bPartnerLocationCandidate);
final String bPartnerLocationIdentifier = ExternalIdentifierFormat.formatDeliveryAddressExternalIdHash(patientId, locationHash);
final JsonRequestLocation deliveryAddressRequest = bPartnerLocationCandidate.toJsonRequestLocation();
return JsonRequestLocationUpsert.builder()
.requestItem(JsonRequestLocationUpsertItem.builder()
.locationIdentifier(bPartnerLocationIdentifier)
.location(deliveryAddressRequest)
.build()) | .syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.build();
}
@VisibleForTesting
@NonNull
public static String computeHashKey(@NonNull final BPartnerLocationCandidate bPartnerLocationCandidate)
{
try
{
final String bpartnerLocationString = JsonObjectMapperHolder
.sharedJsonObjectMapper()
.writeValueAsString(bPartnerLocationCandidate);
final String hashedValue = StringUtils.createHash(StringUtils.removeWhitespaces(bpartnerLocationString).toLowerCase(), null);
Check.assumeNotNull(hashedValue, "hashedValue cannot be null! bPartnerLocationCandidate: {}", bPartnerLocationCandidate);
return hashedValue;
}
catch (final Exception e)
{
throw new RuntimeException("Fail to process hashed value for " + bPartnerLocationCandidate + "; error: " + e);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\DeliveryAddressUpsertProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class DockerComposeConnectionSource {
private final RunningService runningService;
private final Environment environment;
/**
* Create a new {@link DockerComposeConnectionSource} instance.
* @param runningService the running Docker Compose service
* @param environment environment in which the current application is running
*/
DockerComposeConnectionSource(RunningService runningService, Environment environment) {
this.runningService = runningService;
this.environment = environment;
}
/**
* Return the running Docker Compose service. | * @return the running service
*/
public RunningService getRunningService() {
return this.runningService;
}
/**
* Environment in which the current application is running.
* @return the environment
* @since 3.5.0
*/
public Environment getEnvironment() {
return this.environment;
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\service\connection\DockerComposeConnectionSource.java | 2 |
请完成以下Java代码 | public void setC_Currency_To_ID (final int C_Currency_To_ID)
{
if (C_Currency_To_ID < 1)
set_Value (COLUMNNAME_C_Currency_To_ID, null);
else
set_Value (COLUMNNAME_C_Currency_To_ID, C_Currency_To_ID);
}
@Override
public int getC_Currency_To_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_To_ID);
}
@Override
public void setMultiplyRate_Max (final @Nullable BigDecimal MultiplyRate_Max)
{
set_Value (COLUMNNAME_MultiplyRate_Max, MultiplyRate_Max);
}
@Override
public BigDecimal getMultiplyRate_Max()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Max); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMultiplyRate_Min (final @Nullable BigDecimal MultiplyRate_Min)
{
set_Value (COLUMNNAME_MultiplyRate_Min, MultiplyRate_Min);
}
@Override
public BigDecimal getMultiplyRate_Min()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Min);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionRate_Rule.java | 1 |
请完成以下Java代码 | public Void call() throws Exception {
// Note: we can't cache the result of the expression, because the
// execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}'
Object delegate = expression.getValue(execution);
applyFieldDeclaration(fieldDeclarations, delegate);
if (delegate instanceof ActivityBehavior) {
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new ActivityBehaviorInvocation((ActivityBehavior) delegate, execution));
} else if (delegate instanceof JavaDelegate) {
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new JavaDelegateInvocation((JavaDelegate) delegate, execution));
leave(execution);
} else {
throw LOG.resolveDelegateExpressionException(expression, ActivityBehavior.class, JavaDelegate.class);
}
return null; | }
};
executeWithErrorPropagation(execution, callable);
}
protected ActivityBehavior getActivityBehaviorInstance(ActivityExecution execution, Object delegateInstance) {
if (delegateInstance instanceof ActivityBehavior) {
return new CustomActivityBehavior((ActivityBehavior) delegateInstance);
} else if (delegateInstance instanceof JavaDelegate) {
return new ServiceTaskJavaDelegateActivityBehavior((JavaDelegate) delegateInstance);
} else {
throw LOG.missingDelegateParentClassException(delegateInstance.getClass().getName(),
JavaDelegate.class.getName(), ActivityBehavior.class.getName());
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ServiceTaskDelegateExpressionActivityBehavior.java | 1 |
请完成以下Java代码 | public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
/**
* 本函数输出将作为默认的<shiro:principal/>输出.
*/
@Override
public String toString() {
return loginName;
}
/**
* 重载hashCode,只计算loginName;
*/
@Override
public int hashCode() {
return Objects.hashCode(loginName);
}
/**
* 重载equals,只计算loginName;
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false; | }
if (getClass() != obj.getClass()) {
return false;
}
ShiroUser other = (ShiroUser) obj;
if (loginName == null) {
if (other.loginName != null) {
return false;
}
} else if (!loginName.equals(other.loginName)) {
return false;
}
return true;
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroUser.java | 1 |
请完成以下Java代码 | private static Integer convertToInteger(final Object valueObj)
{
if (valueObj == null)
{
return null;
}
else if (valueObj instanceof Integer)
{
return (Integer)valueObj;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
}
else if (valueObj instanceof IntegerLookupValue)
{
return ((IntegerLookupValue)valueObj).getIdAsInt();
}
else
{
final String valueStr = valueObj.toString().trim();
if (valueStr.isEmpty())
{
return null;
}
return Integer.parseInt(valueStr);
}
}
private static BigDecimal convertToBigDecimal(final Object valueObj)
{
if (valueObj == null)
{
return null;
} | else if (valueObj instanceof BigDecimal)
{
return (BigDecimal)valueObj;
}
else
{
final String valueStr = valueObj.toString().trim();
if (valueStr.isEmpty())
{
return null;
}
return new BigDecimal(valueStr);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentEvaluatee.java | 1 |
请完成以下Java代码 | public Object getValue(final String columnName)
{
final Document document = getDocument();
return InterfaceWrapperHelper.getValueOrNull(document, columnName);
}
@Override
public String setValue(final String columnName, final Object value)
{
final Document document = getDocument();
document.setValue(columnName, value, REASON_Value_DirectSetOnCalloutRecord);
return "";
}
@Override
public void dataRefresh()
{
final Document document = getDocument();
document.refreshFromRepository();
}
@Override
public void dataRefreshAll()
{
// NOTE: there is no "All" concept here, so we are just refreshing this document
final Document document = getDocument();
document.refreshFromRepository();
}
@Override
public void dataRefreshRecursively()
{
// TODO dataRefreshRecursively: refresh document and it's children | throw new UnsupportedOperationException();
}
@Override
public boolean dataSave(final boolean manualCmd)
{
// TODO dataSave: save document but also update the DocumentsCollection!
throw new UnsupportedOperationException();
}
@Override
public boolean isLookupValuesContainingId(@NonNull final String columnName, @NonNull final RepoIdAware id)
{
//Querying all values because getLookupValueById doesn't take validation rul into consideration.
// TODO: Implement possibility to fetch sqllookupbyid with validation rule considered.
return getDocument().getFieldLookupValues(columnName).containsId(id);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentAsCalloutRecord.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public R<IPage<Tenant>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> tenant, Query query, BladeUser bladeUser) {
QueryWrapper<Tenant> queryWrapper = Condition.getQueryWrapper(tenant, Tenant.class);
IPage<Tenant> pages = tenantService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Tenant::getTenantId, bladeUser.getTenantId()) : queryWrapper);
return R.data(pages);
}
/**
* 下拉数据源
*/
@GetMapping("/select")
@Operation(summary = "下拉数据源", description = "传入tenant")
public R<List<Tenant>> select(Tenant tenant, BladeUser bladeUser) {
QueryWrapper<Tenant> queryWrapper = Condition.getQueryWrapper(tenant);
List<Tenant> list = tenantService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Tenant::getTenantId, bladeUser.getTenantId()) : queryWrapper);
return R.data(list);
}
/**
* 自定义分页
*/
@GetMapping("/page")
@Operation(summary = "分页", description = "传入tenant")
public R<IPage<Tenant>> page(Tenant tenant, Query query) {
IPage<Tenant> pages = tenantService.selectTenantPage(Condition.getPage(query), tenant);
return R.data(pages);
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@Operation(summary = "新增或修改", description = "传入tenant")
public R submit(@Valid @RequestBody Tenant tenant) {
return R.status(tenantService.saveTenant(tenant));
} | /**
* 删除
*/
@PostMapping("/remove")
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(tenantService.deleteLogic(Func.toLongList(ids)));
}
/**
* 根据域名查询信息
*
* @param domain 域名
*/
@GetMapping("/info")
@Operation(summary = "配置信息", description = "传入domain")
public R<Kv> info(String domain) {
Tenant tenant = tenantService.getOne(Wrappers.<Tenant>query().lambda().eq(Tenant::getDomain, domain));
Kv kv = Kv.init();
if (tenant != null) {
kv.set("tenantId", tenant.getTenantId()).set("domain", tenant.getDomain());
}
return R.data(kv);
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\TenantController.java | 2 |
请完成以下Java代码 | public class X_M_CustomsTariff extends org.compiere.model.PO implements I_M_CustomsTariff, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 543378193L;
/** Standard Constructor */
public X_M_CustomsTariff (Properties ctx, int M_CustomsTariff_ID, String trxName)
{
super (ctx, M_CustomsTariff_ID, trxName);
/** if (M_CustomsTariff_ID == 0)
{
setM_CustomsTariff_ID (0);
setName (null);
setValue (null);
} */
}
/** Load Constructor */
public X_M_CustomsTariff (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** 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 Customs Tariff.
@param M_CustomsTariff_ID Customs Tariff */
@Override
public void setM_CustomsTariff_ID (int M_CustomsTariff_ID)
{
if (M_CustomsTariff_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CustomsTariff_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CustomsTariff_ID, Integer.valueOf(M_CustomsTariff_ID));
} | /** Get Customs Tariff.
@return Customs Tariff */
@Override
public int getM_CustomsTariff_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CustomsTariff_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CustomsTariff.java | 1 |
请完成以下Java代码 | private int retrieveSize(final String selectionId)
{
final SqlAndParams sqlCount = newSqlViewSelectionQueryBuilder().buildSqlRetrieveSize(selectionId);
final int size = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sqlCount.getSql(), sqlCount.getSqlParams());
return Math.max(size, 0);
}
@Override
public boolean containsAnyOfRowIds(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIds)
{
if (rowIds.isEmpty())
{
return false;
}
final SqlAndParams sqlCount = newSqlViewSelectionQueryBuilder().buildSqlCount(selection.getSelectionId(), rowIds);
final int count = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sqlCount.getSql(), sqlCount.getSqlParamsArray());
return count > 0;
}
@Override
public void deleteSelections(@NonNull final Set<String> selectionIds)
{
if (selectionIds.isEmpty())
{
return;
}
final SqlViewSelectionQueryBuilder viewQueryBuilder = newSqlViewSelectionQueryBuilder();
// Delete selection lines
{
final SqlAndParams sql = viewQueryBuilder.buildSqlDeleteSelectionLines(selectionIds);
final int countDeleted = DB.executeUpdateAndThrowExceptionOnFail(sql.getSql(), sql.getSqlParamsArray(), ITrx.TRXNAME_ThreadInherited);
logger.trace("Delete {} selection lines for {}", countDeleted, selectionIds);
}
// Delete selection rows
{
final SqlAndParams sql = viewQueryBuilder.buildSqlDeleteSelection(selectionIds);
final int countDeleted = DB.executeUpdateAndThrowExceptionOnFail(sql.getSql(), sql.getSqlParamsArray(), ITrx.TRXNAME_ThreadInherited);
logger.trace("Delete {} selection rows for {}", countDeleted, selectionIds);
}
}
@Override
public void scheduleDeleteSelections(@NonNull final Set<String> selectionIds)
{
SqlViewSelectionToDeleteHelper.scheduleDeleteSelections(selectionIds);
}
public static Set<DocumentId> retrieveRowIdsForLineIds( | @NonNull final SqlViewKeyColumnNamesMap keyColumnNamesMap,
final ViewId viewId,
final Set<Integer> lineIds)
{
final SqlAndParams sqlAndParams = SqlViewSelectionQueryBuilder.buildSqlSelectRowIdsForLineIds(keyColumnNamesMap, viewId.getViewId(), lineIds);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sqlAndParams.getSql(), ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, sqlAndParams.getSqlParams());
rs = pstmt.executeQuery();
final ImmutableSet.Builder<DocumentId> rowIds = ImmutableSet.builder();
while (rs.next())
{
final DocumentId rowId = keyColumnNamesMap.retrieveRowId(rs, "", false);
if (rowId != null)
{
rowIds.add(rowId);
}
}
return rowIds.build();
}
catch (final SQLException ex)
{
throw new DBException(ex, sqlAndParams.getSql(), sqlAndParams.getSqlParams());
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewRowIdsOrderedSelectionFactory.java | 1 |
请完成以下Java代码 | public void setIsAllowIssuingAnyHU (final @Nullable java.lang.String IsAllowIssuingAnyHU)
{
set_Value (COLUMNNAME_IsAllowIssuingAnyHU, IsAllowIssuingAnyHU);
}
@Override
public java.lang.String getIsAllowIssuingAnyHU()
{
return get_ValueAsString(COLUMNNAME_IsAllowIssuingAnyHU);
}
/**
* IsScanResourceRequired AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int ISSCANRESOURCEREQUIRED_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISSCANRESOURCEREQUIRED_Yes = "Y";
/** No = N */
public static final String ISSCANRESOURCEREQUIRED_No = "N";
@Override
public void setIsScanResourceRequired (final @Nullable java.lang.String IsScanResourceRequired)
{
set_Value (COLUMNNAME_IsScanResourceRequired, IsScanResourceRequired);
}
@Override
public java.lang.String getIsScanResourceRequired()
{ | return get_ValueAsString(COLUMNNAME_IsScanResourceRequired);
}
@Override
public void setMobileUI_UserProfile_MFG_ID (final int MobileUI_UserProfile_MFG_ID)
{
if (MobileUI_UserProfile_MFG_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_MFG_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_MFG_ID, MobileUI_UserProfile_MFG_ID);
}
@Override
public int getMobileUI_UserProfile_MFG_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_MFG_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_MFG.java | 1 |
请完成以下Java代码 | public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Remote Addr.
@param Remote_Addr
Remote Address
*/
public void setRemote_Addr (String Remote_Addr)
{
set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr);
}
/** Get Remote Addr.
@return Remote Address
*/
public String getRemote_Addr ()
{
return (String)get_Value(COLUMNNAME_Remote_Addr);
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Sales Volume in 1.000.
@param SalesVolume | Total Volume of Sales in Thousands of Currency
*/
public void setSalesVolume (int SalesVolume)
{
set_Value (COLUMNNAME_SalesVolume, Integer.valueOf(SalesVolume));
}
/** Get Sales Volume in 1.000.
@return Total Volume of Sales in Thousands of Currency
*/
public int getSalesVolume ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesVolume);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Implementation/Production.
@param StartProductionDate
The day you started the implementation (if implementing) - or production (went life) with Adempiere
*/
public void setStartProductionDate (Timestamp StartProductionDate)
{
set_Value (COLUMNNAME_StartProductionDate, StartProductionDate);
}
/** Get Start Implementation/Production.
@return The day you started the implementation (if implementing) - or production (went life) with Adempiere
*/
public Timestamp getStartProductionDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartProductionDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Registration.java | 1 |
请完成以下Java代码 | public void setIPP_URL (final @Nullable java.lang.String IPP_URL)
{
set_Value (COLUMNNAME_IPP_URL, IPP_URL);
}
@Override
public java.lang.String getIPP_URL()
{
return get_ValueAsString(COLUMNNAME_IPP_URL);
}
@Override
public void setName (final java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* OutputType AD_Reference_ID=540632
* Reference name: OutputType
*/
public static final int OUTPUTTYPE_AD_Reference_ID=540632;
/** Attach = Attach */
public static final String OUTPUTTYPE_Attach = "Attach";
/** Store = Store */
public static final String OUTPUTTYPE_Store = "Store"; | /** Queue = Queue */
public static final String OUTPUTTYPE_Queue = "Queue";
/** Frontend = Frontend */
public static final String OUTPUTTYPE_Frontend = "Frontend";
@Override
public void setOutputType (final java.lang.String OutputType)
{
set_Value (COLUMNNAME_OutputType, OutputType);
}
@Override
public java.lang.String getOutputType()
{
return get_ValueAsString(COLUMNNAME_OutputType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the models
*/
public List<CarModel> getModels() {
return models;
}
/**
* @param models the models to set
*/
public void setModels(List<CarModel> models) {
this.models = models;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((models == null) ? 0 : models.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object) | */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarMaker other = (CarMaker) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (models == null) {
if (other.models != null)
return false;
} else if (!models.equals(other.models))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
} | repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarMaker.java | 1 |
请完成以下Java代码 | public static SAPGLJournalLineId ofRepoIdOrNull(final int glJournalRepoId, final int repoId)
{
final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoIdOrNull(glJournalRepoId);
return ofRepoIdOrNull(glJournalId, repoId);
}
@NonNull SAPGLJournalId glJournalId;
int repoId;
private SAPGLJournalLineId(final @NonNull SAPGLJournalId glJournalId, final int repoId)
{
this.glJournalId = glJournalId;
this.repoId = Check.assumeGreaterThanZero(repoId, "SAP_GLJournalLine_ID");
}
@JsonValue
@Override | public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final SAPGLJournalLineId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(@Nullable final SAPGLJournalLineId id1, @Nullable final SAPGLJournalLineId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\acct\gljournal_sap\SAPGLJournalLineId.java | 1 |
请完成以下Java代码 | public TableDataManager getTableDataManager() {
return getSession(TableDataManager.class);
}
public CommentEntityManager getCommentEntityManager() {
return getSession(CommentEntityManager.class);
}
public PropertyEntityManager getPropertyEntityManager() {
return getSession(PropertyEntityManager.class);
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getSession(EventSubscriptionEntityManager.class);
}
public Map<Class<?>, SessionFactory> getSessionFactories() {
return sessionFactories;
}
public HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
// getters and setters //////////////////////////////////////////////////////
public TransactionContext getTransactionContext() {
return transactionContext;
}
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
} | public Throwable getException() {
return exception;
}
public FailedJobCommandFactory getFailedJobCommandFactory() {
return failedJobCommandFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public FlowableEventDispatcher getEventDispatcher() {
return processEngineConfiguration.getEventDispatcher();
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java | 1 |
请完成以下Java代码 | public static String stringify(Object value) {
return value != null ? JacksonUtil.toString(value) : "null";
}
public static Object parse(ExecutionContext ctx, String value) throws IOException {
if (value != null) {
JsonNode node = JacksonUtil.toJsonNode(value);
if (node.isObject()) {
return ArgsRepackUtil.repack(ctx, JacksonUtil.convertValue(node, Map.class));
} else if (node.isArray()) {
return ArgsRepackUtil.repack(ctx, JacksonUtil.convertValue(node, List.class));
} else if (node.isDouble()) {
return node.doubleValue();
} else if (node.isLong()) {
return node.longValue();
} else if (node.isInt()) { | return node.intValue();
} else if (node.isBoolean()) {
return node.booleanValue();
} else if (node.isTextual()) {
return node.asText();
} else if (node.isBinary()) {
return node.binaryValue();
} else if (node.isNull()) {
return null;
} else {
return node.asText();
}
} else {
return null;
}
}
} | repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\tbel\TbJson.java | 1 |
请完成以下Java代码 | public Book as(String alias) {
return new Book(DSL.name(alias), this);
}
@Override
public Book as(Name alias) {
return new Book(alias, this);
}
@Override
public Book as(Table<?> alias) {
return new Book(alias.getQualifiedName(), this);
}
/**
* Rename this table
*/
@Override
public Book rename(String name) {
return new Book(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Book rename(Name name) {
return new Book(name, null);
}
/**
* Rename this table
*/
@Override
public Book rename(Table<?> name) {
return new Book(name.getQualifiedName(), null);
}
/**
* Create an inline derived table from this table
*/
@Override
public Book where(Condition condition) {
return new Book(getQualifiedName(), aliased() ? this : null, null, condition);
}
/**
* Create an inline derived table from this table
*/
@Override
public Book where(Collection<? extends Condition> conditions) {
return where(DSL.and(conditions));
}
/**
* Create an inline derived table from this table
*/
@Override
public Book where(Condition... conditions) {
return where(DSL.and(conditions));
} | /**
* Create an inline derived table from this table
*/
@Override
public Book where(Field<Boolean> condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Book where(SQL condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Book where(@Stringly.SQL String condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Book where(@Stringly.SQL String condition, Object... binds) {
return where(DSL.condition(condition, binds));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Book where(@Stringly.SQL String condition, QueryPart... parts) {
return where(DSL.condition(condition, parts));
}
/**
* Create an inline derived table from this table
*/
@Override
public Book whereExists(Select<?> select) {
return where(DSL.exists(select));
}
/**
* Create an inline derived table from this table
*/
@Override
public Book whereNotExists(Select<?> select) {
return where(DSL.notExists(select));
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\Book.java | 1 |
请完成以下Java代码 | public class JpaRuleNodeDao extends JpaAbstractDao<RuleNodeEntity, RuleNode> implements RuleNodeDao, TenantEntityDao<RuleNode> {
@Autowired
private RuleNodeRepository ruleNodeRepository;
@Override
protected Class<RuleNodeEntity> getEntityClass() {
return RuleNodeEntity.class;
}
@Override
protected JpaRepository<RuleNodeEntity, UUID> getRepository() {
return ruleNodeRepository;
}
@Override
public List<RuleNode> findRuleNodesByTenantIdAndType(TenantId tenantId, String type, String configurationSearch) {
return DaoUtil.convertDataList(ruleNodeRepository.findRuleNodesByTenantIdAndType(tenantId.getId(), type, configurationSearch));
}
@Override
public PageData<RuleNode> findAllRuleNodesByType(String type, PageLink pageLink) {
return DaoUtil.toPageData(ruleNodeRepository
.findAllRuleNodesByType(
type,
Objects.toString(pageLink.getTextSearch(), ""),
DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<RuleNode> findAllRuleNodesByTypeAndVersionLessThan(String type, int version, PageLink pageLink) {
return DaoUtil.toPageData(ruleNodeRepository
.findAllRuleNodesByTypeAndVersionLessThan(
type,
version,
Objects.toString(pageLink.getTextSearch(), ""),
DaoUtil.toPageable(pageLink)));
}
@Override | public PageData<RuleNodeId> findAllRuleNodeIdsByTypeAndVersionLessThan(String type, int version, PageLink pageLink) {
return DaoUtil.pageToPageData(ruleNodeRepository
.findAllRuleNodeIdsByTypeAndVersionLessThan(
type,
version,
DaoUtil.toPageable(pageLink)))
.mapData(RuleNodeId::new);
}
@Override
public List<RuleNode> findAllRuleNodeByIds(List<RuleNodeId> ruleNodeIds) {
return DaoUtil.convertDataList(ruleNodeRepository.findAllById(
ruleNodeIds.stream().map(RuleNodeId::getId).collect(Collectors.toList())));
}
@Override
public List<RuleNode> findByExternalIds(RuleChainId ruleChainId, List<RuleNodeId> externalIds) {
return DaoUtil.convertDataList(ruleNodeRepository.findRuleNodesByRuleChainIdAndExternalIdIn(ruleChainId.getId(),
externalIds.stream().map(RuleNodeId::getId).collect(Collectors.toList())));
}
@Override
public void deleteByIdIn(List<RuleNodeId> ruleNodeIds) {
ruleNodeRepository.deleteAllById(ruleNodeIds.stream().map(RuleNodeId::getId).collect(Collectors.toList()));
}
@Override
public EntityType getEntityType() {
return EntityType.RULE_NODE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\rule\JpaRuleNodeDao.java | 1 |
请完成以下Java代码 | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
} | public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootEntityListener\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Spring Boot application配置 | spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.image.options.model=dall-e-3
spring.ai.openai.image.options.size=1024x1024
spring.ai.openai.image.options.style=vivid
spring.ai.opena | i.image.options.quality=standard
spring.ai.openai.image.options.response-format=url | repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\resources\application-imagegen.properties | 2 |
请完成以下Java代码 | public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
claimsConsumer.accept(this.claims);
return this;
}
/**
* Validate the claims and build the {@link OAuth2TokenIntrospection}.
* <p>
* The following claims are REQUIRED: {@code active}
* @return the {@link OAuth2TokenIntrospection}
*/
public OAuth2TokenIntrospection build() {
validate();
return new OAuth2TokenIntrospection(this.claims);
}
private void validate() {
Assert.notNull(this.claims.get(OAuth2TokenIntrospectionClaimNames.ACTIVE), "active cannot be null");
Assert.isInstanceOf(Boolean.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.ACTIVE),
"active must be of type boolean");
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.SCOPE)) {
Assert.isInstanceOf(List.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.SCOPE),
"scope must be of type List");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.EXP)) {
Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.EXP),
"exp must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.IAT)) {
Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.IAT),
"iat must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.NBF)) {
Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.NBF),
"nbf must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.AUD)) {
Assert.isInstanceOf(List.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.AUD),
"aud must be of type List"); | }
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.ISS)) {
validateURL(this.claims.get(OAuth2TokenIntrospectionClaimNames.ISS), "iss must be a valid URL");
}
}
@SuppressWarnings("unchecked")
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>());
((List<String>) this.claims.get(name)).add(value);
}
@SuppressWarnings("unchecked")
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>());
List<String> values = (List<String>) this.claims.get(name);
valuesConsumer.accept(values);
}
private static void validateURL(Object url, String errorMessage) {
if (URL.class.isAssignableFrom(url.getClass())) {
return;
}
try {
new URI(url.toString()).toURL();
}
catch (Exception ex) {
throw new IllegalArgumentException(errorMessage, ex);
}
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2TokenIntrospection.java | 1 |
请完成以下Java代码 | public void setCamundaResultVariable(String camundaResultVariable) {
camundaResultVariableAttribute.setValue(this, camundaResultVariable);
}
public String getCamundaDecisionBinding() {
return camundaDecisionBindingAttribute.getValue(this);
}
public void setCamundaDecisionBinding(String camundaDecisionBinding) {
camundaDecisionBindingAttribute.setValue(this, camundaDecisionBinding);
}
public String getCamundaDecisionVersion() {
return camundaDecisionVersionAttribute.getValue(this);
}
public void setCamundaDecisionVersion(String camundaDecisionVersion) {
camundaDecisionVersionAttribute.setValue(this, camundaDecisionVersion);
}
public String getCamundaDecisionTenantId() {
return camundaDecisionTenantIdAttribute.getValue(this);
}
public void setCamundaDecisionTenantId(String camundaDecisionTenantId) {
camundaDecisionTenantIdAttribute.setValue(this, camundaDecisionTenantId);
}
@Override
public String getCamundaMapDecisionResult() {
return camundaMapDecisionResultAttribute.getValue(this);
}
@Override
public void setCamundaMapDecisionResult(String camundaMapDecisionResult) {
camundaMapDecisionResultAttribute.setValue(this, camundaMapDecisionResult);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionTask.class, CMMN_ELEMENT_DECISION_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionTask>() {
public DecisionTask newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionTaskImpl(instanceContext);
}
});
decisionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DECISION_REF) | .build();
/** Camunda extensions */
camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_BINDING)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
camundaMapDecisionResultAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_MAP_DECISION_RESULT)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
decisionRefExpressionChild = sequenceBuilder.element(DecisionRefExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionTaskImpl.java | 1 |
请完成以下Java代码 | private HotelOffer toOffer(Hotel hotel, int nights, int guests) {
int perNight = hotel.basePricePerNight() + Math.max(0, guests - 1) * 25;
int total = Math.max(1, nights) * perNight;
return new HotelOffer(hotel.id(), hotel.name(), hotel.city(), perNight, total, hotel.maxGuests());
}
public record Hotel(String id, String name, String city, int basePricePerNight, int maxGuests) {
}
public record HotelOffer(
String hotelId,
String hotelName,
String city,
int pricePerNight,
int totalPrice,
int maxGuests | ) {
}
public record Booking(
String bookingId,
String hotelId,
String hotelName,
String city,
String checkIn,
int nights,
int guests,
String guestName,
int totalPrice,
String status
) {
}
} | repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\HotelService.java | 1 |
请完成以下Java代码 | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", couponId=").append(couponId);
sb.append(", orderSn=").append(orderSn);
sb.append(", createTime=").append(createTime);
sb.append(", memberUsername=").append(memberUsername);
sb.append(", totalAmount=").append(totalAmount);
sb.append(", payAmount=").append(payAmount);
sb.append(", freightAmount=").append(freightAmount);
sb.append(", promotionAmount=").append(promotionAmount);
sb.append(", integrationAmount=").append(integrationAmount);
sb.append(", couponAmount=").append(couponAmount);
sb.append(", discountAmount=").append(discountAmount);
sb.append(", payType=").append(payType);
sb.append(", sourceType=").append(sourceType);
sb.append(", status=").append(status);
sb.append(", orderType=").append(orderType);
sb.append(", deliveryCompany=").append(deliveryCompany);
sb.append(", deliverySn=").append(deliverySn);
sb.append(", autoConfirmDay=").append(autoConfirmDay);
sb.append(", integration=").append(integration);
sb.append(", growth=").append(growth);
sb.append(", promotionInfo=").append(promotionInfo);
sb.append(", billType=").append(billType);
sb.append(", billHeader=").append(billHeader);
sb.append(", billContent=").append(billContent);
sb.append(", billReceiverPhone=").append(billReceiverPhone);
sb.append(", billReceiverEmail=").append(billReceiverEmail);
sb.append(", receiverName=").append(receiverName);
sb.append(", receiverPhone=").append(receiverPhone);
sb.append(", receiverPostCode=").append(receiverPostCode); | sb.append(", receiverProvince=").append(receiverProvince);
sb.append(", receiverCity=").append(receiverCity);
sb.append(", receiverRegion=").append(receiverRegion);
sb.append(", receiverDetailAddress=").append(receiverDetailAddress);
sb.append(", note=").append(note);
sb.append(", confirmStatus=").append(confirmStatus);
sb.append(", deleteStatus=").append(deleteStatus);
sb.append(", useIntegration=").append(useIntegration);
sb.append(", paymentTime=").append(paymentTime);
sb.append(", deliveryTime=").append(deliveryTime);
sb.append(", receiveTime=").append(receiveTime);
sb.append(", commentTime=").append(commentTime);
sb.append(", modifyTime=").append(modifyTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrder.java | 1 |
请完成以下Java代码 | public void println(String string) {
write(string.toCharArray(), 0, string.length());
println();
}
/**
* Write a new line.
*/
public void println() {
String separator = System.lineSeparator();
try {
this.out.write(separator.toCharArray(), 0, separator.length());
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
this.prependIndent = true;
}
/**
* Increase the indentation level and execute the {@link Runnable}. Decrease the
* indentation level on completion.
* @param runnable the code to execute withing an extra indentation level
*/
public void indented(Runnable runnable) {
indent();
runnable.run();
outdent();
}
/**
* Increase the indentation level.
*/
private void indent() {
this.level++;
refreshIndent();
}
/**
* Decrease the indentation level.
*/
private void outdent() {
this.level--;
refreshIndent();
}
private void refreshIndent() {
this.indent = this.indentStrategy.apply(this.level);
}
@Override
public void write(char[] chars, int offset, int length) { | try {
if (this.prependIndent) {
this.out.write(this.indent.toCharArray(), 0, this.indent.length());
this.prependIndent = false;
}
this.out.write(chars, offset, length);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void flush() throws IOException {
this.out.flush();
}
@Override
public void close() throws IOException {
this.out.close();
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\IndentingWriter.java | 1 |
请完成以下Java代码 | public final void setBinaryStream(final int parameterIndex, final InputStream x) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setBinaryStream(parameterIndex, x);
}
@Override
public final void setCharacterStream(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setCharacterStream(parameterIndex, reader);
}
@Override
public final void setNCharacterStream(final int parameterIndex, final Reader value) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, value);
getStatementImpl().setNCharacterStream(parameterIndex, value);
}
@Override | public final void setClob(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setClob(parameterIndex, reader);
}
@Override
public final void setBlob(final int parameterIndex, final InputStream inputStream) throws SQLException
{
//logMigrationScript_SetParam(parameterIndex, inputStream);
getStatementImpl().setBlob(parameterIndex, inputStream);
}
@Override
public final void setNClob(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setNClob(parameterIndex, reader);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\CPreparedStatementProxy.java | 1 |
请完成以下Java代码 | public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTM_Product_ID (final int TM_Product_ID)
{
if (TM_Product_ID < 1)
set_Value (COLUMNNAME_TM_Product_ID, null);
else
set_Value (COLUMNNAME_TM_Product_ID, TM_Product_ID);
}
@Override
public int getTM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_TM_Product_ID);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
} | @Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_Product_BOMLine.java | 1 |
请完成以下Java代码 | public void setReferrer (String Referrer)
{
set_ValueNoCheck (COLUMNNAME_Referrer, Referrer);
}
/** Get Referrer.
@return Referring web address
*/
public String getReferrer ()
{
return (String)get_Value(COLUMNNAME_Referrer);
}
/** Set Remote Addr.
@param Remote_Addr
Remote Address
*/
public void setRemote_Addr (String Remote_Addr)
{
set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr);
}
/** Get Remote Addr.
@return Remote Address
*/
public String getRemote_Addr ()
{
return (String)get_Value(COLUMNNAME_Remote_Addr);
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Serial No.
@param SerNo
Product Serial Number
*/
public void setSerNo (String SerNo)
{
set_ValueNoCheck (COLUMNNAME_SerNo, SerNo); | }
/** Get Serial No.
@return Product Serial Number
*/
public String getSerNo ()
{
return (String)get_Value(COLUMNNAME_SerNo);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
public void setURL (String URL)
{
set_ValueNoCheck (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Delivery.java | 1 |
请完成以下Java代码 | public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
for (ProducerInterceptor<K, V> interceptor : this.delegates) {
try {
interceptor.onAcknowledgement(metadata, exception);
}
catch (Exception e) {
// do not propagate interceptor exceptions, just log
CompositeProducerInterceptor.this.logger.warn(e, () -> "Error executing interceptor onAcknowledgement callback: "
+ interceptor.toString());
}
}
}
@Override
public void close() {
for (ProducerInterceptor<K, V> interceptor : this.delegates) { | try {
interceptor.close();
}
catch (Exception e) {
CompositeProducerInterceptor.this.logger.warn(e, () -> "Failed to close producer interceptor: "
+ interceptor.toString());
}
}
}
@Override
public void configure(Map<String, ?> configs) {
this.delegates.forEach(delegate -> delegate.configure(configs));
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\CompositeProducerInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ChannelRequestMatcherRegistry withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
addObjectPostProcessor(objectPostProcessor);
return this;
}
/**
* Sets the {@link ChannelProcessor} instances to use in
* {@link ChannelDecisionManagerImpl}
* @param channelProcessors
* @return the {@link ChannelSecurityConfigurer} for further customizations
*/
public ChannelRequestMatcherRegistry channelProcessors(List<ChannelProcessor> channelProcessors) {
ChannelSecurityConfigurer.this.channelProcessors = channelProcessors;
return this;
}
/**
* Sets the {@link RedirectStrategy} instances to use in
* {@link RetryWithHttpEntryPoint} and {@link RetryWithHttpsEntryPoint}
* @param redirectStrategy
* @return the {@link ChannelSecurityConfigurer} for further customizations
*/
public ChannelRequestMatcherRegistry redirectStrategy(RedirectStrategy redirectStrategy) {
ChannelSecurityConfigurer.this.redirectStrategy = redirectStrategy;
return this;
}
} | /**
* @deprecated no replacement planned
*/
@Deprecated
public class RequiresChannelUrl {
protected List<? extends RequestMatcher> requestMatchers;
RequiresChannelUrl(List<? extends RequestMatcher> requestMatchers) {
this.requestMatchers = requestMatchers;
}
public ChannelRequestMatcherRegistry requiresSecure() {
return requires("REQUIRES_SECURE_CHANNEL");
}
public ChannelRequestMatcherRegistry requiresInsecure() {
return requires("REQUIRES_INSECURE_CHANNEL");
}
public ChannelRequestMatcherRegistry requires(String attribute) {
return addAttribute(attribute, this.requestMatchers);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\ChannelSecurityConfigurer.java | 2 |
请完成以下Java代码 | /* package */final class SingleParameterStringExpression implements IStringExpression
{
private final String expressionStr;
private final CtxName parameter;
private final Set<CtxName> parametersAsCtxName;
/* package */ SingleParameterStringExpression(final String expressionStr, final CtxName parameter)
{
super();
Check.assumeNotNull(expressionStr, "Parameter expressionStr is not null");
this.expressionStr = expressionStr;
Check.assumeNotNull(parameter, "Parameter parameter is not null");
this.parameter = parameter;
parametersAsCtxName = ImmutableSet.of(parameter);
}
@Override
public String toString()
{
return expressionStr;
}
@Override
public int hashCode()
{
return Objects.hash(parameter);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final SingleParameterStringExpression other = (SingleParameterStringExpression)obj;
return Objects.equals(parameter, other.parameter);
}
@Override
public String getExpressionString()
{
return expressionStr;
}
@Override
public String getFormatedExpressionString()
{
return parameter.toStringWithMarkers();
}
@Override
public Set<CtxName> getParameters()
{
return parametersAsCtxName;
} | @Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
try
{
return StringExpressionsHelper.evaluateParam(parameter, ctx, onVariableNotFound);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
@Override
public IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException
{
try
{
final String value = StringExpressionsHelper.evaluateParam(parameter, ctx, OnVariableNotFound.ReturnNoResult);
if (value == null || value == EMPTY_RESULT)
{
return this;
}
return ConstantStringExpression.of(value);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\SingleParameterStringExpression.java | 1 |
请完成以下Java代码 | public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final Logger logger = LoggerFactory.getLogger(PriceCalculationEnvironmentPostProcessor.class);
private static final String PREFIX = "com.baeldung.environmentpostprocessor.";
private static final String CALCUATION_MODE = "calculation_mode";
private static final String GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate";
private static final String CALCUATION_MODE_DEFAULT_VALUE = "NET";
private static final double GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE = 0;
List<String> names = Arrays.asList(CALCUATION_MODE, GROSS_CALCULATION_TAX_RATE);
private static Map<String, Object> defaults = new LinkedHashMap<>();
static {
defaults.put(CALCUATION_MODE, CALCUATION_MODE_DEFAULT_VALUE);
defaults.put(GROSS_CALCULATION_TAX_RATE, GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
PropertySource<?> system = environment.getPropertySources()
.get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
Map<String, Object> prefixed = new LinkedHashMap<>();
if (!hasOurPriceProperties(system)) {
// Baeldung-internal code so this doesn't break other examples
logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", CALCUATION_MODE_DEFAULT_VALUE,
GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
prefixed = names.stream()
.collect(Collectors.toMap(this::rename, this::getDefaultValue));
environment.getPropertySources()
.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));
return;
}
prefixed = names.stream()
.collect(Collectors.toMap(this::rename, system::getProperty));
environment.getPropertySources()
.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed)); | }
private Object getDefaultValue(String key) {
return defaults.get(key);
}
private String rename(String key) {
return PREFIX + key.replaceAll("\\_", ".");
}
private boolean hasOurPriceProperties(PropertySource<?> system) {
if (system.containsProperty(CALCUATION_MODE) && system.containsProperty(GROSS_CALCULATION_TAX_RATE)) {
return true;
} else
return false;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-environment\src\main\java\com\baeldung\environmentpostprocessor\PriceCalculationEnvironmentPostProcessor.java | 1 |
请完成以下Java代码 | class Manager {
@Id //
private String id;
private String name;
@DBRef //
private List<Employee> employees;
public Manager() {
}
public Manager(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id; | }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
} | repos\spring-data-examples-main\mongodb\linking\src\main\java\example\springdata\mongodb\linking\dbref\Manager.java | 1 |
请完成以下Java代码 | private List<Map.Entry<String, Double>> topN(Map<String, Double> tfidfs, int size)
{
MaxHeap<Map.Entry<String, Double>> heap = new MaxHeap<Map.Entry<String, Double>>(size, new Comparator<Map.Entry<String, Double>>()
{
@Override
public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2)
{
return o1.getValue().compareTo(o2.getValue());
}
});
heap.addAll(tfidfs.entrySet());
return heap.toList();
}
public Set<Object> documents()
{
return tfMap.keySet();
}
public Map<Object, Map<String, Double>> getTfMap()
{
return tfMap;
}
public List<Map.Entry<String, Double>> sortedAllTf()
{
return sort(allTf());
}
public List<Map.Entry<String, Integer>> sortedAllTfInt()
{
return doubleToInteger(sortedAllTf());
}
public Map<String, Double> allTf()
{
Map<String, Double> result = new HashMap<String, Double>();
for (Map<String, Double> d : tfMap.values())
{
for (Map.Entry<String, Double> tf : d.entrySet())
{
Double f = result.get(tf.getKey());
if (f == null)
{
result.put(tf.getKey(), tf.getValue());
}
else | {
result.put(tf.getKey(), f + tf.getValue());
}
}
}
return result;
}
private static List<Map.Entry<String, Double>> sort(Map<String, Double> map)
{
List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Double>>()
{
@Override
public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2)
{
return o2.getValue().compareTo(o1.getValue());
}
});
return list;
}
private static List<Map.Entry<String, Integer>> doubleToInteger(List<Map.Entry<String, Double>> list)
{
List<Map.Entry<String, Integer>> result = new ArrayList<Map.Entry<String, Integer>>(list.size());
for (Map.Entry<String, Double> entry : list)
{
result.add(new AbstractMap.SimpleEntry<String, Integer>(entry.getKey(), entry.getValue().intValue()));
}
return result;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TfIdfCounter.java | 1 |
请完成以下Java代码 | public Collection<PricingConditionsRow> getAllRows()
{
return getTopLevelRows();
}
@Override
public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs)
{
return DocumentIdsSelection.EMPTY;
}
@Override
public void invalidateAll()
{
}
private void changeRow(final DocumentId rowId, final UnaryOperator<PricingConditionsRow> mapper)
{
if (!rowIds.contains(rowId))
{
throw new EntityNotFoundException(rowId.toJson());
}
rowsById.compute(rowId, (key, oldRow) -> {
if (oldRow == null)
{
throw new EntityNotFoundException(rowId.toJson());
}
return mapper.apply(oldRow);
});
}
@Override
public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final PricingConditionsRowChangeRequest request = PricingConditionsRowActions.toChangeRequest(fieldChangeRequests, getDefaultCurrencyId());
changeRow(ctx.getRowId(), row -> PricingConditionsRowReducers.copyAndChange(request, row));
}
public void patchEditableRow(final PricingConditionsRowChangeRequest request)
{
changeRow(getEditableRowId(), editableRow -> PricingConditionsRowReducers.copyAndChange(request, editableRow));
}
public boolean hasEditableRow()
{
return editableRowId != null;
}
public DocumentId getEditableRowId()
{
if (editableRowId == null)
{
throw new AdempiereException("No editable row found");
} | return editableRowId;
}
public PricingConditionsRow getEditableRow()
{
return getById(getEditableRowId());
}
public DocumentFilterList getFilters()
{
return filters;
}
public PricingConditionsRowData filter(@NonNull final DocumentFilterList filters)
{
if (DocumentFilterList.equals(this.filters, filters))
{
return this;
}
if (filters.isEmpty())
{
return getAllRowsData();
}
return new PricingConditionsRowData(this, filters);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmailServer2 {
private String server;
private Integer port;
private String username;
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public Integer getPort() { | return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
} | repos\spring-boot-master\spring-boot-externalize-config-2\src\main\java\com\mkyong\global\EmailServer2.java | 2 |
请完成以下Java代码 | public class X_M_Warehouse_Group extends org.compiere.model.PO implements I_M_Warehouse_Group, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1409666171L;
/** Standard Constructor */
public X_M_Warehouse_Group (final Properties ctx, final int M_Warehouse_Group_ID, @Nullable final String trxName)
{
super (ctx, M_Warehouse_Group_ID, trxName);
}
/** Load Constructor */
public X_M_Warehouse_Group (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description); | }
@Override
public void setM_Warehouse_Group_ID (final int M_Warehouse_Group_ID)
{
if (M_Warehouse_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Group_ID, M_Warehouse_Group_ID);
}
@Override
public int getM_Warehouse_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_Group_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_Group.java | 1 |
请完成以下Java代码 | public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(widgetTypeDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.WIDGET_TYPE;
}
private final PaginatedRemover<TenantId, WidgetTypeInfo> tenantWidgetTypeRemover = new PaginatedRemover<>() {
@Override
protected PageData<WidgetTypeInfo> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return widgetTypeDao.findTenantWidgetTypesByTenantId(
WidgetTypeFilter.builder()
.tenantId(id)
.fullSearch(false)
.deprecatedFilter(DeprecatedFilter.ALL)
.widgetTypes(null).build(),
pageLink);
} | @Override
protected void removeEntity(TenantId tenantId, WidgetTypeInfo entity) {
deleteWidgetType(tenantId, new WidgetTypeId(entity.getUuidId()));
}
};
private final PaginatedRemover<WidgetsBundleId, WidgetTypeInfo> bundleWidgetTypesRemover = new PaginatedRemover<>() {
@Override
protected PageData<WidgetTypeInfo> findEntities(TenantId tenantId, WidgetsBundleId widgetsBundleId, PageLink pageLink) {
return findWidgetTypesInfosByWidgetsBundleId(tenantId, widgetsBundleId, false, DeprecatedFilter.ALL, null, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, WidgetTypeInfo widgetTypeInfo) {
deleteWidgetType(tenantId, widgetTypeInfo.getId());
}
};
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\widget\WidgetTypeServiceImpl.java | 1 |
请完成以下Java代码 | protected boolean shouldReleaseBeforeCompletion() {
return false;
}
@Override
protected void processResourceAfterCommit(KafkaResourceHolder<K, V> resourceHolder) {
resourceHolder.commit();
}
@Override
public void afterCompletion(int status) {
try {
if (status == TransactionSynchronization.STATUS_COMMITTED) {
this.resourceHolder.commit();
}
else { | this.resourceHolder.rollback();
}
}
finally {
super.afterCompletion(status);
}
}
@Override
protected void releaseResource(KafkaResourceHolder<K, V> holder, Object resourceKey) {
ProducerFactoryUtils.releaseResources(holder);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ProducerFactoryUtils.java | 1 |
请完成以下Java代码 | public void deleteAttributeValueByCode(@NonNull final AttributeId attributeId, @Nullable final String value)
{
queryBL.createQueryBuilder(I_M_AttributeValue.class)
.addEqualsFilter(I_M_AttributeValue.COLUMN_M_Attribute_ID, attributeId)
.addEqualsFilter(I_M_AttributeValue.COLUMNNAME_Value, value)
.create()
.delete();
}
@Override
public List<Attribute> retrieveAttributes(final AttributeSetId attributeSetId, final boolean isInstanceAttribute)
{
return getAttributesByAttributeSetId(attributeSetId)
.stream()
.filter(attribute -> attribute.isInstanceAttribute() == isInstanceAttribute)
.collect(ImmutableList.toImmutableList());
}
@Override
public boolean containsAttribute(@NonNull final AttributeSetId attributeSetId, @NonNull final AttributeId attributeId)
{
return getAttributeSetDescriptorById(attributeSetId).contains(attributeId);
}
@Override
@Nullable
public I_M_Attribute retrieveAttribute(final AttributeSetId attributeSetId, final AttributeId attributeId)
{
if (!containsAttribute(attributeSetId, attributeId))
{
return null;
}
return getAttributeRecordById(attributeId);
}
private static final class AttributeListValueMap
{
public static AttributeListValueMap ofList(final List<AttributeListValue> list)
{
if (list.isEmpty())
{
return EMPTY;
}
return new AttributeListValueMap(list);
}
private static final AttributeListValueMap EMPTY = new AttributeListValueMap();
private final ImmutableMap<String, AttributeListValue> map;
private AttributeListValueMap()
{
map = ImmutableMap.of();
} | private AttributeListValueMap(@NonNull final List<AttributeListValue> list)
{
map = Maps.uniqueIndex(list, AttributeListValue::getValue);
}
public List<AttributeListValue> toList()
{
return ImmutableList.copyOf(map.values());
}
@Nullable
public AttributeListValue getByIdOrNull(@NonNull final AttributeValueId id)
{
return map.values()
.stream()
.filter(av -> AttributeValueId.equals(av.getId(), id))
.findFirst()
.orElse(null);
}
public AttributeListValue getByValueOrNull(final String value)
{
return map.get(value);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeDAO.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.