instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getGroupId() { return this.groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getArtifactId() { return this.artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public String getBootVersion() { return this.bootVersion; } public void setBootVersion(String bootVersion) { this.bootVersion = bootVersion; } public String getPackaging() { return this.packaging; } public void setPackaging(String packaging) { this.packaging = packaging; } public String getApplicationName() { return this.applicationName; }
public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getConfigurationFileFormat() { return this.configurationFileFormat; } public void setConfigurationFileFormat(String configurationFileFormat) { this.configurationFileFormat = configurationFileFormat; } public String getPackageName() { if (StringUtils.hasText(this.packageName)) { return this.packageName; } if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) { return getGroupId() + "." + getArtifactId(); } return null; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getJavaVersion() { return this.javaVersion; } public void setJavaVersion(String javaVersion) { this.javaVersion = javaVersion; } public String getBaseDir() { return this.baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectRequest.java
1
请在Spring Boot框架中完成以下Java代码
private String getDefaultPrinterNameFromIni(final String propName) { log.debug("Looking for " + propName + " in ini file"); String printerName = Ini.getProperty(propName); if (!Check.isEmpty(printerName)) { log.debug("Found printerName: " + printerName); return printerName; } log.debug("Looking for machine's printers"); final PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); if (services == null || services.length == 0) { // t.schoeneberg@metas.de: so what? we don't need a printer to generate PDFs // log.warn("No default printer found on this machine"); return ""; } printerName = services[0].getName(); Ini.setProperty(propName, printerName); log.debug("Found printerName: " + printerName); return printerName;
} @Override public String findPrinterName(final Properties ctx, final int C_DocType_ID, final int AD_Process_ID, final int AD_Table_ID, final String printerType) { final IPrintingService printingService = findPrintingService(ctx, C_DocType_ID, AD_Process_ID, AD_Table_ID, printerType); return printingService.getPrinterName(); } @Override public String findPrinterName(final ProcessInfo pi) { final IPrintingService printingService = findPrintingService(pi); return printingService.getPrinterName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\PrinterRoutingBL.java
2
请在Spring Boot框架中完成以下Java代码
Configuration createConfiguration() { ConfigurationImpl configuration = new ConfigurationImpl(); configuration.setSecurityEnabled(false); configuration.setPersistenceEnabled(this.properties.isPersistent()); String dataDir = getDataDir(); configuration.setJournalDirectory(dataDir + "/journal"); if (this.properties.isPersistent()) { configuration.setJournalType(JournalType.NIO); configuration.setLargeMessagesDirectory(dataDir + "/largemessages"); configuration.setBindingsDirectory(dataDir + "/bindings"); configuration.setPagingDirectory(dataDir + "/paging"); } TransportConfiguration transportConfiguration = new TransportConfiguration(InVMAcceptorFactory.class.getName(), this.properties.generateTransportParameters()); configuration.getAcceptorConfigurations().add(transportConfiguration); if (this.properties.isDefaultClusterPassword() && logger.isDebugEnabled()) { logger.debug("Using default Artemis cluster password: " + this.properties.getClusterPassword()); } configuration.setClusterPassword(this.properties.getClusterPassword()); configuration.addAddressConfiguration(createAddressConfiguration("DLQ")); configuration.addAddressConfiguration(createAddressConfiguration("ExpiryQueue")); configuration.addAddressSetting("#", new AddressSettings().setDeadLetterAddress(SimpleString.of("DLQ")) .setExpiryAddress(SimpleString.of("ExpiryQueue"))); return configuration; }
private CoreAddressConfiguration createAddressConfiguration(String name) { return new CoreAddressConfiguration().setName(name) .addRoutingType(RoutingType.ANYCAST) .addQueueConfiguration(QueueConfiguration.of(name).setRoutingType(RoutingType.ANYCAST).setAddress(name)); } private String getDataDir() { if (this.properties.getDataDirectory() != null) { return this.properties.getDataDirectory(); } String tempDirectory = System.getProperty("java.io.tmpdir"); return new File(tempDirectory, "artemis-data").getAbsolutePath(); } }
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisEmbeddedConfigurationFactory.java
2
请在Spring Boot框架中完成以下Java代码
class PropertiesKafkaConnectionDetails implements KafkaConnectionDetails { private final KafkaProperties properties; private final @Nullable SslBundles sslBundles; PropertiesKafkaConnectionDetails(KafkaProperties properties, @Nullable SslBundles sslBundles) { this.properties = properties; this.sslBundles = sslBundles; } @Override public List<String> getBootstrapServers() { return this.properties.getBootstrapServers(); } @Override public Configuration getConsumer() { List<String> servers = this.properties.getConsumer().getBootstrapServers(); SslBundle sslBundle = getBundle(this.properties.getConsumer().getSsl()); String protocol = this.properties.getConsumer().getSecurity().getProtocol(); return Configuration.of((servers != null) ? servers : getBootstrapServers(), (sslBundle != null) ? sslBundle : getSslBundle(), (StringUtils.hasLength(protocol)) ? protocol : getSecurityProtocol()); } @Override public Configuration getProducer() { List<String> servers = this.properties.getProducer().getBootstrapServers(); SslBundle sslBundle = getBundle(this.properties.getProducer().getSsl()); String protocol = this.properties.getProducer().getSecurity().getProtocol(); return Configuration.of((servers != null) ? servers : getBootstrapServers(), (sslBundle != null) ? sslBundle : getSslBundle(), (StringUtils.hasLength(protocol)) ? protocol : getSecurityProtocol()); } @Override public Configuration getStreams() { List<String> servers = this.properties.getStreams().getBootstrapServers();
SslBundle sslBundle = getBundle(this.properties.getStreams().getSsl()); String protocol = this.properties.getStreams().getSecurity().getProtocol(); return Configuration.of((servers != null) ? servers : getBootstrapServers(), (sslBundle != null) ? sslBundle : getSslBundle(), (StringUtils.hasLength(protocol)) ? protocol : getSecurityProtocol()); } @Override public Configuration getAdmin() { SslBundle sslBundle = getBundle(this.properties.getAdmin().getSsl()); String protocol = this.properties.getAdmin().getSecurity().getProtocol(); return Configuration.of(getBootstrapServers(), (sslBundle != null) ? sslBundle : getSslBundle(), (StringUtils.hasLength(protocol)) ? protocol : getSecurityProtocol()); } @Override public @Nullable SslBundle getSslBundle() { return getBundle(this.properties.getSsl()); } @Override public @Nullable String getSecurityProtocol() { return this.properties.getSecurity().getProtocol(); } private @Nullable SslBundle getBundle(Ssl ssl) { if (StringUtils.hasLength(ssl.getBundle())) { Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context"); return this.sslBundles.getBundle(ssl.getBundle()); } return null; } }
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\PropertiesKafkaConnectionDetails.java
2
请完成以下Java代码
protected void ensureProcessInstanceExists(String processInstanceId, ExecutionEntity processInstance) { if (processInstance == null) { throw LOG.processInstanceDoesNotExist(processInstanceId); } } protected String getLogEntryOperation() { return UserOperationLogEntry.OPERATION_TYPE_MODIFY_PROCESS_INSTANCE; } protected void writeOperationLog(CommandContext commandContext) { commandContext.getOperationLogManager().logProcessInstanceOperation(getLogEntryOperation(), builder.getProcessInstanceId(), null, null,
Collections.singletonList(PropertyChange.EMPTY_CHANGE), builder.getAnnotation()); } public BatchConfiguration getConfiguration(String processDefinitionId, String deploymentId) { return new ModificationBatchConfiguration( Collections.singletonList(builder.getProcessInstanceId()), DeploymentMappings.of(new DeploymentMapping(deploymentId, 1)), processDefinitionId, builder.getModificationOperations(), builder.isSkipCustomListeners(), builder.isSkipIoMappings()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ModifyProcessInstanceAsyncCmd.java
1
请在Spring Boot框架中完成以下Java代码
protected static class MappingJackson2XmlHttpMessageConverterConfiguration { @Bean @ConditionalOnMissingBean(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter.class) Jackson2XmlMessageConvertersCustomizer mappingJackson2XmlHttpMessageConverter( Jackson2ObjectMapperBuilder builder) { return new Jackson2XmlMessageConvertersCustomizer(builder.createXmlMapper(true).build()); } } static class Jackson2JsonMessageConvertersCustomizer implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer { private final ObjectMapper objectMapper; Jackson2JsonMessageConvertersCustomizer(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void customize(ClientBuilder builder) { builder.withJsonConverter( new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter(this.objectMapper)); } @Override public void customize(ServerBuilder builder) { builder.withJsonConverter( new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter(this.objectMapper)); } } static class Jackson2XmlMessageConvertersCustomizer implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer { private final ObjectMapper objectMapper;
Jackson2XmlMessageConvertersCustomizer(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void customize(ClientBuilder builder) { builder.withXmlConverter(new org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter( this.objectMapper)); } @Override public void customize(ServerBuilder builder) { builder.withXmlConverter(new org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter( this.objectMapper)); } } private static class PreferJackson2OrJacksonUnavailableCondition extends AnyNestedCondition { PreferJackson2OrJacksonUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson2") static class Jackson2Preferred { } @ConditionalOnMissingBean(JacksonJsonHttpMessageConvertersCustomizer.class) static class JacksonUnavailable { } } }
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\Jackson2HttpMessageConvertersConfiguration.java
2
请完成以下Java代码
public static class DefaultRabbitListenerObservationConvention implements RabbitListenerObservationConvention { /** * A singleton instance of the convention. */ public static final DefaultRabbitListenerObservationConvention INSTANCE = new DefaultRabbitListenerObservationConvention(); @Override public KeyValues getLowCardinalityKeyValues(RabbitMessageReceiverContext context) { MessageProperties messageProperties = context.getCarrier().getMessageProperties(); String consumerQueue = Objects.requireNonNullElse(messageProperties.getConsumerQueue(), ""); return KeyValues.of( RabbitListenerObservation.ListenerLowCardinalityTags.LISTENER_ID.asString(), context.getListenerId(), RabbitListenerObservation.ListenerLowCardinalityTags.DESTINATION_NAME.asString(), consumerQueue); }
@Override public KeyValues getHighCardinalityKeyValues(RabbitMessageReceiverContext context) { return KeyValues.of(RabbitListenerObservation.ListenerHighCardinalityTags.DELIVERY_TAG.asString(), String.valueOf(context.getCarrier().getMessageProperties().getDeliveryTag())); } @Override public String getContextualName(RabbitMessageReceiverContext context) { return context.getSource() + " receive"; } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\micrometer\RabbitListenerObservation.java
1
请完成以下Java代码
private static class StubAclParent implements Acl { private final Long id; StubAclParent(Long id) { this.id = id; } Long getId() { return this.id; } @Override public List<AccessControlEntry> getEntries() { throw new UnsupportedOperationException("Stub only"); } @Override public ObjectIdentity getObjectIdentity() { throw new UnsupportedOperationException("Stub only"); } @Override public Sid getOwner() { throw new UnsupportedOperationException("Stub only"); } @Override public Acl getParentAcl() { throw new UnsupportedOperationException("Stub only"); } @Override
public boolean isEntriesInheriting() { throw new UnsupportedOperationException("Stub only"); } @Override public boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode) throws NotFoundException, UnloadedSidException { throw new UnsupportedOperationException("Stub only"); } @Override public boolean isSidLoaded(List<Sid> sids) { throw new UnsupportedOperationException("Stub only"); } } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\BasicLookupStrategy.java
1
请完成以下Java代码
public Integer getMaxQueueingTimeMs() { return maxQueueingTimeMs; } public void setMaxQueueingTimeMs(Integer maxQueueingTimeMs) { this.maxQueueingTimeMs = maxQueueingTimeMs; } public boolean isClusterMode() { return clusterMode; } public FlowRuleEntity setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; return this; } public ClusterFlowConfig getClusterConfig() { return clusterConfig; } public FlowRuleEntity setClusterConfig(ClusterFlowConfig clusterConfig) { this.clusterConfig = clusterConfig; return this; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public FlowRule toRule() { FlowRule flowRule = new FlowRule();
flowRule.setCount(this.count); flowRule.setGrade(this.grade); flowRule.setResource(this.resource); flowRule.setLimitApp(this.limitApp); flowRule.setRefResource(this.refResource); flowRule.setStrategy(this.strategy); if (this.controlBehavior != null) { flowRule.setControlBehavior(controlBehavior); } if (this.warmUpPeriodSec != null) { flowRule.setWarmUpPeriodSec(warmUpPeriodSec); } if (this.maxQueueingTimeMs != null) { flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs); } flowRule.setClusterMode(clusterMode); flowRule.setClusterConfig(clusterConfig); return flowRule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\FlowRuleEntity.java
1
请完成以下Java代码
public void save(@NonNull final ProductPlanningSchema schema) { final I_M_Product_PlanningSchema record; if (schema.getId() != null) { record = load(schema.getId(), I_M_Product_PlanningSchema.class); } else { record = newInstance(I_M_Product_PlanningSchema.class); } record.setM_ProductPlanningSchema_Selector(schema.getSelector().getCode()); record.setAD_Org_ID(schema.getOrgId().getRepoId()); record.setS_Resource_ID(ResourceId.toRepoId(schema.getPlantId())); record.setM_Warehouse_ID(WarehouseId.toRepoId(schema.getWarehouseId()));
record.setIsAttributeDependant(schema.isAttributeDependant()); record.setPlanner_ID(UserId.toRepoId(schema.getPlannerId())); record.setIsManufactured(StringUtils.ofBoolean(schema.getManufactured())); record.setIsCreatePlan(schema.isCreatePlan()); record.setIsDocComplete(schema.isCompleteGeneratedDocuments()); record.setIsPickDirectlyIfFeasible(schema.isPickDirectlyIfFeasible()); record.setAD_Workflow_ID(PPRoutingId.toRepoId(schema.getRoutingId())); record.setDD_NetworkDistribution_ID(DistributionNetworkId.toRepoId(schema.getDistributionNetworkId())); record.setOnMaterialReceiptWithDestWarehouse(schema.getOnMaterialReceiptWithDestWarehouse().getCode()); record.setC_Manufacturing_Aggregation_ID(schema.getManufacturingAggregationId() > 0 ? schema.getManufacturingAggregationId() : -1); saveRecord(record); schema.setId(ProductPlanningSchemaId.ofRepoId(record.getM_Product_PlanningSchema_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impl\ProductPlanningSchemaDAO.java
1
请完成以下Java代码
public class AsyncBatchListeners implements IAsyncBatchListeners { private final IAsyncBatchBL asyncBatchBL = Services.get(IAsyncBatchBL.class); private final Map<String, IAsyncBatchListener> listenersList = new HashMap<>(); @Override public void registerAsyncBatchNoticeListener(final IAsyncBatchListener l, final String asyncBatchType) { if (listenersList.containsKey(asyncBatchType)) { throw new IllegalStateException(l + " has already been added"); } else { listenersList.put(asyncBatchType, l); } } @Override public void applyListener(@NonNull final I_C_Async_Batch asyncBatch) { final String internalName = asyncBatchBL.getAsyncBatchTypeInternalName(asyncBatch).orElse(null); if(internalName != null) { final IAsyncBatchListener listener = getListener(internalName); listener.createNotice(asyncBatch); } }
private IAsyncBatchListener getListener(final String ascyncBatchType) { IAsyncBatchListener l = listenersList.get(ascyncBatchType); // retrieve default implementation if (l == null) { l = listenersList.get(AsyncBatchDAO.ASYNC_BATCH_TYPE_DEFAULT); } return l; } private final List<INotifyAsyncBatch> asycnBatchNotifiers = new ArrayList<>(); @Override public void registerAsyncBatchNotifier(INotifyAsyncBatch notifyAsyncBatch) { Check.assume(!asycnBatchNotifiers.contains(notifyAsyncBatch), "Every notifier is added only once"); asycnBatchNotifiers.add(notifyAsyncBatch); } @Override public void notify(I_C_Async_Batch asyncBatch) { for (INotifyAsyncBatch notifier : asycnBatchNotifiers) { notifier.sendNotifications(asyncBatch); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchListeners.java
1
请完成以下Java代码
private void setPhoneIfNotNull( @NonNull final InvoiceWithDetails.InvoiceWithDetailsBuilder invoiceWithDetails, @Nullable final XmlTelecom telecom, @NonNull final String detailItemLabel) { if (telecom != null) { final List<String> phones = telecom.getPhones(); if (phones != null && !phones.isEmpty()) { setIfNotBlank(invoiceWithDetails, phones.get(0), detailItemLabel); } } } private void setEmailIfNotNull( @NonNull final InvoiceWithDetails.InvoiceWithDetailsBuilder invoiceWithDetails, @Nullable final XmlOnline online, @NonNull final String detailItemLabel) { if (online != null) { final List<String> emails = online.getEmails(); if (emails != null && !emails.isEmpty()) { setIfNotBlank(invoiceWithDetails, emails.get(0), detailItemLabel); } } } private void setIfNotBlank( @NonNull final InvoiceWithDetails.InvoiceWithDetailsBuilder invoiceWithDetails, @Nullable final String description, @NonNull final String detailItemLabel)
{ createItemIfNotBlank(description, detailItemLabel).ifPresent(invoiceWithDetails::detailItem); } private Optional<InvoiceDetailItem> createItemIfNotBlank( @Nullable final String description, @NonNull final String detailItemLabel) { if (Check.isBlank(description)) { return Optional.empty(); } return Optional.of(InvoiceDetailItem.builder().label(detailItemLabel).description(description).build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\export\HealthcareXMLToInvoiceDetailPersister.java
1
请完成以下Java代码
public Date getSubmissionDateConverted(String timezone) throws ParseException { dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); return dateFormat.parse(this.date); } public void setSubmissionDate(Date date, String timezone) { dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); this.date = dateFormat.format(date); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() {
return url; } public void setUrl(String url) { this.url = url; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public UserDto getUser() { return user; } public void setUser(UserDto user) { this.user = user; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\dto\PostDto.java
1
请完成以下Java代码
public static void listFilesCommonsIO(File dir) { Iterator<File> fileIterator = FileUtils.iterateFiles(dir, null, true); while (fileIterator.hasNext()) { File file = fileIterator.next(); LOGGER.info("File: " + file.getAbsolutePath()); } } /** * List files in a directory using Java NIO * @param dir directory to list files */ public static void listFilesJavaNIO(Path dir) { try (Stream<Path> stream = Files.walk(dir)) { stream.filter(Files::isRegularFile).forEach(path -> LOGGER.info("File: " + path.toAbsolutePath())); } catch (IOException e) { LOGGER.severe(e.getMessage());
} } /** * List files in a directory using Java IO * @param dir directory to list files */ public static void listFilesJavaIO(File dir) { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { listFilesJavaIO(file); } else { LOGGER.info("File: " + file.getAbsolutePath()); } } } }
repos\tutorials-master\core-java-modules\core-java-io-6\src\main\java\com\baeldung\filelisting\FileListing.java
1
请完成以下Java代码
public String getMktInfrstrctrTxId() { return mktInfrstrctrTxId; } /** * Sets the value of the mktInfrstrctrTxId property. * * @param value * allowed object is * {@link String } * */ public void setMktInfrstrctrTxId(String value) { this.mktInfrstrctrTxId = value; } /** * Gets the value of the prcgId property. * * @return * possible object is * {@link String } * */ public String getPrcgId() { return prcgId; } /** * Sets the value of the prcgId property. * * @param value * allowed object is * {@link String } * */
public void setPrcgId(String value) { this.prcgId = value; } /** * Gets the value of the prtry 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 prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryReference1 } * * */ public List<ProprietaryReference1> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryReference1>(); } return this.prtry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionReferences3.java
1
请在Spring Boot框架中完成以下Java代码
public JasperEntry getByJrxmlFile(@NonNull final File jrxmlFile) { return JasperEntry.builder() .jrxmlFile(jrxmlFile) .jasperFile(getCompiledAssetFile(jrxmlFile, jasperExtension)) .hashFile(getCompiledAssetFile(jrxmlFile, ".hash")) .build(); } private File getCompiledAssetFile(@NonNull final File jrxmlFile, @NonNull final String extension) { final Path jrxmlPath = jrxmlFile.toPath().toAbsolutePath(); // 1. Get the path *relative* to the drive/volume root. // Example: For C:\workspaces\...\report.jrxml, this isolates: // "workspaces\dt204\metasfresh\backend\de.metas.fresh\...\report_lu.jrxml" // We use the full relative path to ensure no collisions. final Path relativePath = jrxmlPath.getRoot().relativize(jrxmlPath); // 2. Separate the directory structure (parent) from the file name.
final Path relativeDirPath = relativePath.getParent(); // 3. Resolve the cache directory path: compiledJaspersDir + relativeDirPath final Path cacheDir = compiledJaspersDir.resolve(relativeDirPath); // 4. Create the final compiled file name (only changes extension). final String compiledFileName = FileUtil.changeFileExtension(jrxmlFile.getName(), extension); // 5. Resolve the final cached path. final Path cachedPath = cacheDir.resolve(compiledFileName); return cachedPath.toFile(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\JasperCompileClassLoader.java
2
请完成以下Java代码
static DateTimeTranslatableString ofObject(@NonNull final Object obj) { return ofObject(obj, -1); } static DateTimeTranslatableString ofObject(@NonNull final Object obj, final int displayType) { if (obj instanceof java.util.Date) { final java.util.Date date = (java.util.Date)obj; if (displayType == DisplayType.Date) { return ofDate(date); } else if (displayType == DisplayType.DateTime) { return ofDateTime(date); } else // default: { return ofDateTime(date); } } else if (obj instanceof LocalDate) { return ofDate((LocalDate)obj); } else if (obj instanceof LocalTime) { return ofTime((LocalTime)obj); } else if (obj instanceof LocalDateTime) { return ofDateTime((LocalDateTime)obj); } else if (obj instanceof Instant) { return ofDateTime((Instant)obj); } else if (obj instanceof ZonedDateTime) { return ofDateTime((ZonedDateTime)obj); } else if (obj instanceof InstantAndOrgId) { return ofDateTime(((InstantAndOrgId)obj).toInstant()); } else if (obj instanceof LocalDateAndOrgId) { return ofDate(((LocalDateAndOrgId)obj).toLocalDate()); } else { throw new AdempiereException("Cannot create " + DateTimeTranslatableString.class + " from " + obj + " (" + obj.getClass() + ")"); } }
private final Instant instant; private final int displayType; private DateTimeTranslatableString(@NonNull final Instant instant, final boolean dateTime) { this(instant, dateTime ? DisplayType.DateTime : DisplayType.Date); } private DateTimeTranslatableString(@NonNull final Instant instant, final int displayType) { this.instant = instant; this.displayType = displayType; } @Override @Deprecated public String toString() { return getDefaultValue(); } @Override public String translate(final String adLanguage) { final Language language = Language.getLanguage(adLanguage); final SimpleDateFormat dateFormat = DisplayType.getDateFormat(displayType, language); dateFormat.setTimeZone(TimeZone.getTimeZone(SystemTime.zoneId())); return dateFormat.format(toDate()); } private java.util.Date toDate() { return java.util.Date.from(instant); } @Override public String getDefaultValue() { final SimpleDateFormat dateFormat = DisplayType.getDateFormat(displayType); dateFormat.setTimeZone(TimeZone.getTimeZone(SystemTime.zoneId())); return dateFormat.format(toDate()); } @Override public Set<String> getAD_Languages() { return ImmutableSet.of(); } @Override public boolean isTranslatedTo(final String adLanguage) { return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\DateTimeTranslatableString.java
1
请完成以下Java代码
public int getM_PromotionGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Promotion getM_Promotion() throws RuntimeException { return (I_M_Promotion)MTable.get(getCtx(), I_M_Promotion.Table_Name) .getPO(getM_Promotion_ID(), get_TrxName()); } /** Set Promotion. @param M_Promotion_ID Promotion */ public void setM_Promotion_ID (int M_Promotion_ID) { if (M_Promotion_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, Integer.valueOf(M_Promotion_ID)); } /** Get Promotion. @return Promotion */ public int getM_Promotion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Promotion_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Promotion Line.
@param M_PromotionLine_ID Promotion Line */ public void setM_PromotionLine_ID (int M_PromotionLine_ID) { if (M_PromotionLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionLine_ID, Integer.valueOf(M_PromotionLine_ID)); } /** Get Promotion Line. @return Promotion Line */ public int getM_PromotionLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionLine.java
1
请完成以下Java代码
public DeploymentQueryImpl deploymentNameLike(String nameLike) { ensureNotNull("deploymentNameLike", nameLike); this.nameLike = nameLike; return this; } public DeploymentQuery deploymentSource(String source) { sourceQueryParamEnabled = true; this.source = source; return this; } public DeploymentQuery deploymentBefore(Date before) { ensureNotNull("deploymentBefore", before); this.deploymentBefore = before; return this; } public DeploymentQuery deploymentAfter(Date after) { ensureNotNull("deploymentAfter", after); this.deploymentAfter = after; return this; } public DeploymentQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; isTenantIdSet = true; return this; } public DeploymentQuery withoutTenantId() { isTenantIdSet = true; this.tenantIds = null; return this; } public DeploymentQuery includeDeploymentsWithoutTenantId() { this.includeDeploymentsWithoutTenantId = true; return this; } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(deploymentAfter, deploymentBefore); } //sorting //////////////////////////////////////////////////////// public DeploymentQuery orderByDeploymentId() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_ID); } public DeploymentQuery orderByDeploymenTime() { return orderBy(DeploymentQueryProperty.DEPLOY_TIME); } public DeploymentQuery orderByDeploymentTime() { return orderBy(DeploymentQueryProperty.DEPLOY_TIME); } public DeploymentQuery orderByDeploymentName() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_NAME);
} public DeploymentQuery orderByTenantId() { return orderBy(DeploymentQueryProperty.TENANT_ID); } //results //////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getDeploymentManager() .findDeploymentCountByQueryCriteria(this); } @Override public List<Deployment> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getDeploymentManager() .findDeploymentsByQueryCriteria(this, page); } //getters //////////////////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public boolean isSourceQueryParamEnabled() { return sourceQueryParamEnabled; } public String getSource() { return source; } public Date getDeploymentBefore() { return deploymentBefore; } public Date getDeploymentAfter() { return deploymentAfter; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\DeploymentQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void pessimisticWriteDelete() throws InterruptedException { Thread tA = new Thread(() -> { template.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRES_NEW); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult( TransactionStatus status) { log.info("Starting first transaction ..."); Author author = authorRepository.findById(1L).orElseThrow(); try { log.info("Locking for 10s ..."); Thread.sleep(10000); log.info("Releasing lock ..."); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }); log.info("First transaction comitted!"); });
Thread tB = new Thread(() -> { template.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRES_NEW); template.setTimeout(15); // 15 seconds template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult( TransactionStatus status) { log.info("Starting second transaction ..."); authorRepository.deleteById(1L); } }); log.info("Second transaction comitted!"); }); tA.start(); Thread.sleep(2000); tB.start(); tA.join(); tB.join(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPessimisticLocksDelInsUpd\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
protected boolean calculateSize() { p_height = 0; for (int r = 0; r < m_rows; r++) { p_height += m_rowHeight[r]; if (m_rowHeight[r] > 0) p_height += m_rowGap; } p_height -= m_rowGap; // remove last p_width = 0; for (int c = 0; c < m_cols; c++) { p_width += m_colWidth[c]; if (m_colWidth[c] > 0) p_width += m_colGap; } p_width -= m_colGap; // remove last return true; } // calculateSize /** * Paint it * @param g2D Graphics * @param pageStart top left Location of page * @param pageNo page number for multi page support (0 = header/footer) - ignored * @param ctx print context * @param isView true if online view (IDs are links) */ public void paint(Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView) { Point2D.Double location = getAbsoluteLocation(pageStart); float y = (float)location.y; // for (int row = 0; row < m_rows; row++) { float x = (float)location.x; for (int col = 0; col < m_cols; col++) { if (m_textLayout[row][col] != null)
{ float yy = y + m_textLayout[row][col].getAscent(); // if (m_iterator[row][col] != null) // g2D.drawString(m_iterator[row][col], x, yy); // else m_textLayout[row][col].draw(g2D, x, yy); } x += m_colWidth[col]; if (m_colWidth[col] > 0) x += m_colGap; } y += m_rowHeight[row]; if (m_rowHeight[row] > 0) y += m_rowGap; } } // paint } // GridElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\GridElement.java
1
请完成以下Java代码
public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Business Partner . @return Identifies a Business Partner */ public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Text Message.
@param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Fin.java
1
请完成以下Java代码
public int getBatchSize() { return events.size(); } }; } void safePutString(PreparedStatement ps, int parameterIdx, String value) throws SQLException { if (value != null) { ps.setString(parameterIdx, replaceNullChars(value)); } else { ps.setNull(parameterIdx, Types.VARCHAR); } } void safePutUUID(PreparedStatement ps, int parameterIdx, UUID value) throws SQLException { if (value != null) { ps.setObject(parameterIdx, value); } else { ps.setNull(parameterIdx, Types.OTHER); } } private void setCommonEventFields(PreparedStatement ps, Event event) throws SQLException {
ps.setObject(1, event.getId().getId()); ps.setObject(2, event.getTenantId().getId()); ps.setLong(3, event.getCreatedTime()); ps.setObject(4, event.getEntityId()); ps.setString(5, event.getServiceId()); } private String replaceNullChars(String strValue) { if (removeNullChars && strValue != null) { return PATTERN_THREAD_LOCAL.get().matcher(strValue).replaceAll(EMPTY_STR); } return strValue; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\event\EventInsertRepository.java
1
请完成以下Java代码
public boolean is1xxInformational() { return HttpStatus.Series.INFORMATIONAL.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link HttpStatus.Series#SUCCESSFUL}. * @return <code>true</code> if status code is in the SUCCESSFUL http series */ public boolean is2xxSuccessful() { return HttpStatus.Series.SUCCESSFUL.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link HttpStatus.Series#REDIRECTION}. * @return <code>true</code> if status code is in the REDIRECTION http series */ public boolean is3xxRedirection() { return HttpStatus.Series.REDIRECTION.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link HttpStatus.Series#CLIENT_ERROR}. * @return <code>true</code> if status code is in the CLIENT_ERROR http series */ public boolean is4xxClientError() { return HttpStatus.Series.CLIENT_ERROR.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link HttpStatus.Series#SERVER_ERROR}. * @return <code>true</code> if status code is in the SERVER_ERROR http series */ public boolean is5xxServerError() { return HttpStatus.Series.SERVER_ERROR.equals(getSeries()); } public HttpStatus.Series getSeries() { if (httpStatus != null) {
return HttpStatus.Series.valueOf(httpStatus.value()); } if (status != null) { return HttpStatus.Series.valueOf(status); } return null; } /** * Whether this status code is in the HTTP series * {@link HttpStatus.Series#CLIENT_ERROR} or {@link HttpStatus.Series#SERVER_ERROR}. * @return <code>true</code> if is either CLIENT_ERROR or SERVER_ERROR */ public boolean isError() { return is4xxClientError() || is5xxServerError(); } @Override public String toString() { return new ToStringCreator(this).append("httpStatus", httpStatus).append("status", status).toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\common\HttpStatusHolder.java
1
请完成以下Java代码
default String replaceTableNameWithTableAlias(final String sql) { final String tableName = getTableName(); final String tableAlias = getTableAlias(); return replaceTableNameWithTableAlias(sql, tableName, tableAlias); } default String replaceTableNameWithTableAlias(final String sql, @NonNull final String tableAlias) { final String tableName = getTableName(); return replaceTableNameWithTableAlias(sql, tableName, tableAlias); } default SqlAndParams replaceTableNameWithTableAlias(final SqlAndParams sql, @NonNull final String tableAlias) { return SqlAndParams.of(
replaceTableNameWithTableAlias(sql.getSql(), tableAlias), sql.getSqlParams()); } static String replaceTableNameWithTableAlias(final String sql, @NonNull final String tableName, @NonNull final String tableAlias) { if (sql == null || sql.isEmpty()) { return sql; } final String matchTableNameIgnoringCase = "(?i)" + Pattern.quote(tableName + "."); final String sqlFixed = sql.replaceAll(matchTableNameIgnoringCase, tableAlias + "."); return sqlFixed; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlEntityBinding.java
1
请完成以下Java代码
public Acl getAcl() { return this.acl; } @Override public Serializable getId() { return this.id; } @Override public Permission getPermission() { return this.permission; } @Override public Sid getSid() { return this.sid; } @Override public boolean isAuditFailure() { return this.auditFailure; } @Override public boolean isAuditSuccess() { return this.auditSuccess; } @Override public boolean isGranting() {
return this.granting; } void setAuditFailure(boolean auditFailure) { this.auditFailure = auditFailure; } void setAuditSuccess(boolean auditSuccess) { this.auditSuccess = auditSuccess; } void setPermission(Permission permission) { Assert.notNull(permission, "Permission required"); this.permission = permission; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AccessControlEntryImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("granting: ").append(this.granting).append("; "); sb.append("sid: ").append(this.sid).append("; "); sb.append("permission: ").append(this.permission).append("; "); sb.append("auditSuccess: ").append(this.auditSuccess).append("; "); sb.append("auditFailure: ").append(this.auditFailure); sb.append("]"); return sb.toString(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AccessControlEntryImpl.java
1
请完成以下Java代码
private void collectText(final String text, final ContentType contentType) { if (text == null || text.isEmpty()) { return; } if (contentType == null || contentType.match("text/plain")) { logger.debug("Collecting text: {}", text); this.text.append(text); } else if (contentType == null || contentType.match("text/html")) { logger.debug("Collecting html: {}", text); this.html.append(text); } else { collectUnknown(text, contentType);
} } private void collectMailContent(final MailContent mailContent) { text.append(mailContent.getText()); html.append(mailContent.getHtml()); attachments.addAll(mailContent.getAttachments()); } private void collectUnknown(@NonNull final Object contentObj, final ContentType contentType) { logger.debug("Ignore unknown content: contentType={}, contentObj={}, contentClass={}", contentType, contentObj, contentObj.getClass()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\MailContentCollector.java
1
请完成以下Java代码
private boolean startupEnvironment(final RunMode runMode) { final ADSystemInfo system = Services.get(ISystemBL.class).get(); // Initializes Base Context too // Initialize main cached Singletons ModelValidationEngine.get(); try { String className = null; if (className == null || className.length() == 0) { className = System.getProperty(SecureInterface.METASFRESH_SECURE); if (className != null && className.length() > 0 && !className.equals(SecureInterface.METASFRESH_SECURE_DEFAULT)) { SecureEngine.init(className); // test it } } SecureEngine.init(className); // if (runMode == RunMode.SWING_CLIENT) { // Login Client loaded later Services.get(IClientDAO.class).retriveClient(Env.getCtx(), IClientDAO.SYSTEM_CLIENT_ID); } else { // Load all clients (cache warm up) Services.get(IClientDAO.class).retrieveAllClients(Env.getCtx()); } } catch (Exception e) { logger.warn("Environment problems", e); } // Start Workflow Document Manager (in other package) for PO String className = null; try { // Initialize Archive Engine className = "org.compiere.print.ArchiveEngine"; Class.forName(className); } catch (Exception e) { logger.warn("Not started: {}", className, e); } return true; } // startupEnvironment // metas: private static void startAddOns() { final IAddonStarter addonStarter = new AddonStarter(); addonStarter.startAddons();
} /** * If enabled, everything will run database decoupled. Supposed to be called before an interface like org.compiere.model.I_C_Order is to be used in a unit test. */ public static void enableUnitTestMode() { unitTestMode = true; } public static boolean isUnitTestMode() { return unitTestMode; } public static void assertUnitTestMode() { if (!isUnitTestMode()) { throw new IllegalStateException("JUnit test mode shall be enabled"); } } private static boolean unitTestMode = false; public static boolean isJVMDebugMode() { Boolean jvmDebugMode = Adempiere._jvmDebugMode; if (jvmDebugMode == null) { jvmDebugMode = Adempiere._jvmDebugMode = computeJVMDebugMode(); } return jvmDebugMode; } private static boolean computeJVMDebugMode() { return java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("-agentlib:jdwp"); } } // Adempiere
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\Adempiere.java
1
请完成以下Java代码
public ITranslatableString getShipperName(@NonNull final ShipperId shipperId) { final I_M_Shipper shipper = getById(shipperId); return InterfaceWrapperHelper.getModelTranslationMap(shipper) .getColumnTrl(I_M_Shipper.COLUMNNAME_Name, shipper.getName()); } @Override public Optional<ShipperId> getShipperIdByValue(final String value, final OrgId orgId) { final ShipperId shipperId = queryBL.createQueryBuilderOutOfTrx(I_M_Shipper.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_Shipper.COLUMNNAME_Value, value) .addInArrayFilter(I_M_Shipper.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY) .orderByDescending(I_M_Shipper.COLUMNNAME_AD_Org_ID) .create() .firstIdOnly(ShipperId::ofRepoIdOrNull); return Optional.ofNullable(shipperId); } @Override public Optional<I_M_Shipper> getByName(@NonNull final String name) { return queryBL.createQueryBuilder(I_M_Shipper.class) .addEqualsFilter(I_M_Shipper.COLUMNNAME_Name, name) .create() .firstOnlyOptional(I_M_Shipper.class); } @NonNull public Map<ShipperId, I_M_Shipper> getByIds(@NonNull final Set<ShipperId> shipperIds) { if (Check.isEmpty(shipperIds)) { return ImmutableMap.of(); } final List<I_M_Shipper> shipperList = queryBL.createQueryBuilder(I_M_Shipper.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_M_Shipper.COLUMNNAME_M_Shipper_ID, shipperIds)
.create() .list(); return Maps.uniqueIndex(shipperList, (shipper) -> ShipperId.ofRepoId(shipper.getM_Shipper_ID())); } @NonNull public ImmutableMap<String, I_M_Shipper> getByInternalName(@NonNull final Set<String> internalNameSet) { if (Check.isEmpty(internalNameSet)) { return ImmutableMap.of(); } final List<I_M_Shipper> shipperList = queryBL.createQueryBuilder(I_M_Shipper.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_M_Shipper.COLUMNNAME_InternalName, internalNameSet) .create() .list(); return Maps.uniqueIndex(shipperList, I_M_Shipper::getInternalName); } @Override public ExplainedOptional<ShipperGatewayId> getShipperGatewayId(@NonNull final ShipperId shipperId) { final I_M_Shipper shipper = getById(shipperId); final ShipperGatewayId shipperGatewayId = ShipperGatewayId.ofNullableString(shipper.getShipperGateway()); return shipperGatewayId != null ? ExplainedOptional.of(shipperGatewayId) : ExplainedOptional.emptyBecause("Shipper " + shipper.getName() + " has no gateway configured"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\shipping\impl\ShipperDAO.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_HR_ListType[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Payroll List Type. @param HR_ListType_ID Payroll List Type */ public void setHR_ListType_ID (int HR_ListType_ID) { if (HR_ListType_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, Integer.valueOf(HR_ListType_ID)); } /** Get Payroll List Type. @return Payroll List Type */ public int getHR_ListType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); }
/** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListType.java
1
请在Spring Boot框架中完成以下Java代码
private class AlarmUpdateCallback implements FutureCallback<AlarmApiCallResult> { @Override public void onSuccess(@Nullable AlarmApiCallResult result) { onAlarmUpdated(result); } @Override public void onFailure(Throwable t) { log.warn("Failed to update alarm", t); } } private AlarmApiCallResult withWsCallback(AlarmApiCallResult result) { return withWsCallback(null, result); } private AlarmApiCallResult withWsCallback(AlarmModificationRequest request, AlarmApiCallResult result) { if (result.isSuccessful() && result.isModified()) { Futures.addCallback(Futures.immediateFuture(result), new AlarmUpdateCallback(), wsCallBackExecutor); if (result.isSeverityChanged()) { AlarmInfo alarm = result.getAlarm();
AlarmComment.AlarmCommentBuilder alarmComment = AlarmComment.builder() .alarmId(alarm.getId()) .type(AlarmCommentType.SYSTEM) .comment(JacksonUtil.newObjectNode() .put("text", String.format(SEVERITY_CHANGED.getText(), result.getOldSeverity(), alarm.getSeverity())) .put("subtype", SEVERITY_CHANGED.name()) .put("oldSeverity", result.getOldSeverity().name()) .put("newSeverity", alarm.getSeverity().name())); if (request != null && request.getUserId() != null) { alarmComment.userId(request.getUserId()); } try { alarmCommentService.saveAlarmComment(alarm, alarmComment.build(), null); } catch (ThingsboardException e) { log.error("Failed to save alarm comment", e); } } } return result; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\DefaultAlarmSubscriptionService.java
2
请完成以下Java代码
public Optional<LookupValue> getLookupValueById(@NonNull final RepoIdAware id) { final LookupDataSource lookupDataSource = getLookupDataSource(); final LookupValue value = lookupDataSource.findById(id); lookupValuesStaled = false; return Optional.ofNullable(value); } @Override public ICalloutField asCalloutField() { if (_calloutField == null) { _calloutField = new DocumentFieldAsCalloutField(this); } return _calloutField; } private void updateValid(final IDocumentChangesCollector changesCollector) { final DocumentValidStatus validStatusOld = _validStatus; final DocumentValidStatus validStatusNew = computeValidStatus(); _validStatus = validStatusNew; // Collect validStatus changed event if (!NullDocumentChangesCollector.isNull(changesCollector) && !Objects.equals(validStatusOld, validStatusNew)) { // logger.debug("updateValid: {}: {} <- {}", getFieldName(), validNew, validOld); changesCollector.collectValidStatus(this); } } /** * Computes field's validStatus. * IMPORTANT: this method is not updating the status, it's only computing it. */ private DocumentValidStatus computeValidStatus() { // Consider virtual fields as valid because there is nothing we can do about them if (isReadonlyVirtualField()) { return DocumentValidStatus.validField(getFieldName(), isInitialValue()); } // Check mandatory constraint if (isMandatory() && getValue() == null) { return DocumentValidStatus.invalidFieldMandatoryNotFilled(getFieldName(), isInitialValue()); } return DocumentValidStatus.validField(getFieldName(), isInitialValue()); } @Override public DocumentValidStatus getValidStatus() { return _validStatus; } @Override public DocumentValidStatus updateStatusIfInitialInvalidAndGet(final IDocumentChangesCollector changesCollector) { if (_validStatus.isInitialInvalid()) { updateValid(changesCollector); } return _validStatus;
} @Override public boolean hasChangesToSave() { if (isReadonlyVirtualField()) { return false; } return !isInitialValue(); } private boolean isInitialValue() { return DataTypes.equals(_value, _initialValue); } @Override public Optional<WindowId> getZoomIntoWindowId() { final LookupDataSource lookupDataSource = getLookupDataSourceOrNull(); if (lookupDataSource == null) { return Optional.empty(); } return lookupDataSource.getZoomIntoWindowId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentField.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public Date getStartTime() { return startTime; }
public void setStartTime(Date startTime) { this.startTime = startTime; } public List<IncidentStatisticsDto> getIncidents() { return incidents; } public void setIncidents(List<IncidentStatisticsDto> incidents) { this.incidents = incidents; } public boolean isSuspended() { return SuspensionState.SUSPENDED.getStateCode() == suspensionState; } protected void setSuspensionState(int state) { this.suspensionState = state; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\ProcessInstanceDto.java
1
请完成以下Java代码
public <X> JsonSerde<X> copyWithType(JavaType newTargetType) { return new JsonSerde<>(this.jsonSerializer.copyWithType(newTargetType), this.jsonDeserializer.copyWithType(newTargetType)); } // Fluent API /** * Designate this Serde for serializing/deserializing keys (default is values). * @return the serde. * @since 2.3 */ public JsonSerde<T> forKeys() { this.jsonSerializer.forKeys(); this.jsonDeserializer.forKeys(); return this; } /** * Configure the serializer to not add type information. * @return the serde. * @since 2.3 */ public JsonSerde<T> noTypeInfo() { this.jsonSerializer.noTypeInfo(); return this; } /** * Don't remove type information headers after deserialization. * @return the serde. * @since 2.3 */ public JsonSerde<T> dontRemoveTypeHeaders() { this.jsonDeserializer.dontRemoveTypeHeaders(); return this;
} /** * Ignore type information headers and use the configured target class. * @return the serde. * @since 2.3 */ public JsonSerde<T> ignoreTypeHeaders() { this.jsonDeserializer.ignoreTypeHeaders(); return this; } /** * Use the supplied {@link org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper}. * @param mapper the mapper. * @return the serde. * @since 2.3 */ public JsonSerde<T> typeMapper(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper mapper) { this.jsonSerializer.setTypeMapper(mapper); this.jsonDeserializer.setTypeMapper(mapper); return this; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JsonSerde.java
1
请完成以下Java代码
public Product manualDeepClone(Product original) { Product clone = new Product(); clone.setName(original.getName()); clone.setPrice(original.getPrice()); if (original.getCategory() != null) { Category categoryClone = new Category(); categoryClone.setName(original.getCategory() .getName()); clone.setCategory(categoryClone); } return clone; } public Product cloneUsingSerialization(Product original) throws IOException, ClassNotFoundException { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(original); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream in = new ObjectInputStream(byteIn); Product clone = (Product) in.readObject(); in.close(); clone.setId(null); return clone; // Return deep clone }
public Product cloneUsingBeanUtils(Product original) throws InvocationTargetException, IllegalAccessException { Product clone = new Product(); BeanUtils.copyProperties(original, clone); clone.setId(null); return clone; } public Product cloneUsingModelMapper(Product original) { ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration() .setDeepCopyEnabled(true); Product clone = modelMapper.map(original, Product.class); clone.setId(null); return clone; } }
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\cloneentity\ProductService.java
1
请完成以下Java代码
public void setHeader(String name, String value) { validateCrlf(name, value); super.setHeader(name, value); } @Override public void addHeader(String name, String value) { validateCrlf(name, value); super.addHeader(name, value); } @Override public void addCookie(Cookie cookie) { if (cookie != null) { validateCrlf(SET_COOKIE_HEADER, cookie.getName());
validateCrlf(SET_COOKIE_HEADER, cookie.getValue()); validateCrlf(SET_COOKIE_HEADER, cookie.getPath()); validateCrlf(SET_COOKIE_HEADER, cookie.getDomain()); } super.addCookie(cookie); } void validateCrlf(String name, String value) { Assert.isTrue(!hasCrlf(name) && !hasCrlf(value), () -> "Invalid characters (CR/LF) in header " + name); } private boolean hasCrlf(String value) { return value != null && (value.indexOf('\n') != -1 || value.indexOf('\r') != -1); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\FirewalledResponse.java
1
请完成以下Java代码
public void setUseBase64Encoding(boolean useBase64Encoding) { this.useBase64Encoding = useBase64Encoding; } /** * Set the request attribute name that indicates remember-me login. If specified, the * cookie will be written as Integer.MAX_VALUE. * @param rememberMeRequestAttribute the remember-me request attribute name * @since 1.3.0 */ public void setRememberMeRequestAttribute(String rememberMeRequestAttribute) { if (rememberMeRequestAttribute == null) { throw new IllegalArgumentException("rememberMeRequestAttribute cannot be null"); } this.rememberMeRequestAttribute = rememberMeRequestAttribute; } /** * Set the value for the {@code SameSite} cookie directive. The default value is * {@code Lax}. * @param sameSite the SameSite directive value * @since 2.1.0 */ public void setSameSite(String sameSite) { this.sameSite = sameSite; } private String getDomainName(HttpServletRequest request) { if (this.domainName != null) { return this.domainName; } if (this.domainNamePattern != null) { Matcher matcher = this.domainNamePattern.matcher(request.getServerName()); if (matcher.matches()) { return matcher.group(1); } } return null; } private String getCookiePath(HttpServletRequest request) { if (this.cookiePath == null) {
String contextPath = request.getContextPath(); return (contextPath != null && contextPath.length() > 0) ? contextPath : "/"; } return this.cookiePath; } /** * Gets the name of the request attribute that is checked to see if the cookie should * be written with {@link Integer#MAX_VALUE}. * @return the remember me request attribute * @since 3.2 */ public String getRememberMeRequestAttribute() { return this.rememberMeRequestAttribute; } /** * Allows defining whether the generated cookie carries the Partitioned attribute. * @param partitioned whether the generate cookie is partitioned * @since 3.4 */ public void setPartitioned(boolean partitioned) { this.partitioned = partitioned; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\DefaultCookieSerializer.java
1
请完成以下Java代码
public static <V> V getAndRemove(final Properties ctx, final String propertyName) { @SuppressWarnings("unchecked") final V value = (V)ctx.remove(propertyName); return value; } public static void put(final Properties ctx, final String propertyName, final Object value) { ctx.put(propertyName, value); } /** * Checks if given key is contained in context. * <p> * WARNING: this method is NOT checking the key exists in underlying "defaults". Before changing this please check the API which depends on this logic *
* @return true if given key is contained in context */ public static boolean containsKey(final Properties ctx, final String key) { return ctx.containsKey(key); } /** * Returns given <code>ctx</code> or {@link #getCtx()} if null. * * @return ctx or {@link #getCtx()}; never returns null */ public static Properties coalesce(@Nullable final Properties ctx) { return ctx == null ? getCtx() : ctx; } } // Env
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Env.java
1
请在Spring Boot框架中完成以下Java代码
public LegacyEndpointConverter infoLegacyEndpointConverter() { return LegacyEndpointConverters.info(); } @Bean @ConditionalOnMissingBean(name = "envLegacyEndpointConverter") public LegacyEndpointConverter envLegacyEndpointConverter() { return LegacyEndpointConverters.env(); } @Bean @ConditionalOnMissingBean(name = "httptraceLegacyEndpointConverter") public LegacyEndpointConverter httptraceLegacyEndpointConverter() { return LegacyEndpointConverters.httptrace(); } @Bean @ConditionalOnMissingBean(name = "threaddumpLegacyEndpointConverter") public LegacyEndpointConverter threaddumpLegacyEndpointConverter() { return LegacyEndpointConverters.threaddump(); } @Bean @ConditionalOnMissingBean(name = "liquibaseLegacyEndpointConverter") public LegacyEndpointConverter liquibaseLegacyEndpointConverter() { return LegacyEndpointConverters.liquibase(); } @Bean @ConditionalOnMissingBean(name = "flywayLegacyEndpointConverter") public LegacyEndpointConverter flywayLegacyEndpointConverter() { return LegacyEndpointConverters.flyway(); } @Bean @ConditionalOnMissingBean(name = "beansLegacyEndpointConverter") public LegacyEndpointConverter beansLegacyEndpointConverter() { return LegacyEndpointConverters.beans(); } @Bean @ConditionalOnMissingBean(name = "configpropsLegacyEndpointConverter") public LegacyEndpointConverter configpropsLegacyEndpointConverter() { return LegacyEndpointConverters.configprops(); } @Bean @ConditionalOnMissingBean(name = "mappingsLegacyEndpointConverter")
public LegacyEndpointConverter mappingsLegacyEndpointConverter() { return LegacyEndpointConverters.mappings(); } @Bean @ConditionalOnMissingBean(name = "startupLegacyEndpointConverter") public LegacyEndpointConverter startupLegacyEndpointConverter() { return LegacyEndpointConverters.startup(); } } @Configuration(proxyBeanMethods = false) protected static class CookieStoreConfiguration { /** * Creates a default {@link PerInstanceCookieStore} that should be used. * @return the cookie store */ @Bean @ConditionalOnMissingBean public PerInstanceCookieStore cookieStore() { return new JdkPerInstanceCookieStore(CookiePolicy.ACCEPT_ORIGINAL_SERVER); } /** * Creates a default trigger to cleanup the cookie store on deregistering of an * {@link de.codecentric.boot.admin.server.domain.entities.Instance}. * @param publisher publisher of {@link InstanceEvent}s events * @param cookieStore the store to inform about deregistration of an * {@link de.codecentric.boot.admin.server.domain.entities.Instance} * @return a new trigger */ @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean public CookieStoreCleanupTrigger cookieStoreCleanupTrigger(final Publisher<InstanceEvent> publisher, final PerInstanceCookieStore cookieStore) { return new CookieStoreCleanupTrigger(publisher, cookieStore); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerInstanceWebClientConfiguration.java
2
请完成以下Java代码
public static boolean isDark (Color color) { float r = color.getRed() / 255.0f; float g = color.getGreen() / 255.0f; float b = color.getBlue() / 255.0f; double whiteDistance = colorDistance (r, g, b, 1.0, 1.0, 1.0); double blackDistance = colorDistance (r, g, b, 0.0, 0.0, 0.0); boolean dark = blackDistance < whiteDistance; if (r+g+b == 1.0) dark = false; // log.info("r=" + r + ",g=" + g + ",b=" + b + " - black=" + blackDistance // + (dark ? " <dark " : " light> ") + "white=" + whiteDistance // + " - Alpha=" + color.getAlpha() + ", Trans=" + color.getTransparency()); return dark; } // isDark /** * Is Color more white or black? * @param r red * @param g green * @param b blue * @return true if dark */ public static boolean isDark (double r, double g, double b) { double whiteDistance = colorDistance (r, g, b, 1.0, 1.0, 1.0); double blackDistance = colorDistance (r, g, b, 0.0, 0.0, 0.0); boolean dark = blackDistance < whiteDistance; // log.trace("r=" + r + ",g=" + g + ",b=" + b + " - white=" + whiteDistance + ",black=" + blackDistance); return dark; } // isDark /** * Simple Color Distance. * (3d point distance) * @param r1 first red * @param g1 first green * @param b1 first blue * @param r2 second red * @param g2 second green * @param b2 second blue * @return 3d distance for relative comparison */ public static double colorDistance (double r1, double g1, double b1, double r2, double g2, double b2) { double a = (r2 - r1) + 0.1; double b = (g2 - g1) + 0.1; double c = (b2 - b1) + 0.1; return Math.sqrt (a*a + b*b + c*c); } // colorDistance /**
* Get darker color * @param color color * @param factor factor 0..1 (AWT 0.7) the smaller, the darker * @return darker color */ public static Color darker(Color color, double factor) { if (factor < 0.0) factor = 0.7; else if (factor > 1.0) factor = 0.7; return new Color( Math.max((int)(color.getRed() * factor), 0), Math.max((int)(color.getGreen() * factor), 0), Math.max((int)(color.getBlue() * factor), 0)); } // darker /** * Get brighter color * @param color color * @param factor factor 0..1 (AWT 0.7) the smaller, the lighter * @return brighter color */ public static Color brighter (Color color, double factor) { if (factor < 0.0) factor = 0.7; else if (factor > 1.0) factor = 0.7; return new Color( Math.min((int)(color.getRed() / factor), 255), Math.min((int)(color.getGreen() / factor), 255), Math.min((int)(color.getBlue() / factor), 255)); } // brighter } // GraphUtil
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\GraphUtil.java
1
请完成以下Java代码
private IAutoCloseable setupLoggerContext() { return logger.temporaryChangeContext(context -> context.moduleName(LOGGER_MODULE) .sourceRecordRef(sourceModelRef)); } private IAutoCloseable updateLoggerContextFrom(final ImmutableList<BusinessRuleAndTriggers> rulesAndTriggers) { final BusinessRuleLogLevel maxLogLevel = extractMaxLogLevel(rulesAndTriggers).orElse(null); return maxLogLevel != null ? logger.temporaryChangeContext(contextBuilder -> contextBuilder.logLevel(maxLogLevel)) : IAutoCloseable.NOP; } private static Optional<BusinessRuleLogLevel> extractMaxLogLevel(final ImmutableList<BusinessRuleAndTriggers> rulesAndTriggers) { return rulesAndTriggers.stream() .map(ruleAndTrigger -> ruleAndTrigger.getBusinessRule().getLogLevel()) .filter(Objects::nonNull) .max(Comparator.comparing(BusinessRuleLogLevel::ordinal)); } private IAutoCloseable updateLoggerContextFrom(final BusinessRule rule) { return logger.temporaryChangeContext(contextBuilder -> contextBuilder.businessRule(rule)); } private IAutoCloseable updateLoggerContextFrom(final BusinessRuleTrigger trigger) { return logger.temporaryChangeContext(contextBuilder -> contextBuilder.triggerId(trigger.getId())); } private ImmutableList<BusinessRuleAndTriggers> getRuleAndTriggers() { return rules.getByTriggerTableId(sourceModelRef.getAdTableId()); } private BooleanWithReason checkTriggerMatching(@NonNull final BusinessRule rule, @NonNull final BusinessRuleTrigger trigger) { final BusinessRuleStopwatch stopwatch = logger.newStopwatch(); BooleanWithReason matching = BooleanWithReason.FALSE;
try { if (!trigger.isChangeTypeMatching(timing)) { return BooleanWithReason.falseBecause("timing not matching"); } matching = checkConditionMatching(trigger.getCondition()); } catch (final Exception ex) { logger.debug("Failed evaluating trigger condition {}/{} for {}/{}", rule, trigger, sourceModel, timing, ex); matching = BooleanWithReason.falseBecause(ex); } finally { logger.debug(stopwatch, "Checked if trigger is matching source: {}", matching); } return matching; } private BooleanWithReason checkConditionMatching(@Nullable final Validation condition) { return condition == null || recordMatcher.isRecordMatching(sourceModelRef, condition) ? BooleanWithReason.TRUE : BooleanWithReason.FALSE; } private void enqueueToRecompute(@NonNull final BusinessRule rule, @NonNull final BusinessRuleTrigger trigger) { eventRepository.create(BusinessRuleEventCreateRequest.builder() .clientAndOrgId(clientAndOrgId) .triggeringUserId(triggeringUserId) .recordRef(sourceModelRef) .businessRuleId(rule.getId()) .triggerId(trigger.getId()) .build()); logger.debug("Enqueued event for re-computation"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\trigger\BusinessRuleFireTriggersCommand.java
1
请完成以下Java代码
public CamundaConstraint newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaConstraintImpl(instanceContext); } }); camundaNameAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_NAME) .namespace(CAMUNDA_NS) .build(); camundaConfigAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CONFIG) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } public CamundaConstraintImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); }
public String getCamundaName() { return camundaNameAttribute.getValue(this); } public void setCamundaName(String camundaName) { camundaNameAttribute.setValue(this, camundaName); } public String getCamundaConfig() { return camundaConfigAttribute.getValue(this); } public void setCamundaConfig(String camundaConfig) { camundaConfigAttribute.setValue(this, camundaConfig); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaConstraintImpl.java
1
请完成以下Java代码
public void setExportRole_ID (final int ExportRole_ID) { if (ExportRole_ID < 1) set_Value (COLUMNNAME_ExportRole_ID, null); else set_Value (COLUMNNAME_ExportRole_ID, ExportRole_ID); } @Override public int getExportRole_ID() { return get_ValueAsInt(COLUMNNAME_ExportRole_ID); } @Override public void setExportTime (final java.sql.Timestamp ExportTime) { set_Value (COLUMNNAME_ExportTime, ExportTime); } @Override public java.sql.Timestamp getExportTime() { return get_ValueAsTimestamp(COLUMNNAME_ExportTime); } @Override public void setExportUser_ID (final int ExportUser_ID) { if (ExportUser_ID < 1) set_Value (COLUMNNAME_ExportUser_ID, null); else set_Value (COLUMNNAME_ExportUser_ID, ExportUser_ID); } @Override public int getExportUser_ID() { return get_ValueAsInt(COLUMNNAME_ExportUser_ID); } @Override public void setExternalSystem_ExportAudit_ID (final int ExternalSystem_ExportAudit_ID) { if (ExternalSystem_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_ExportAudit_ID, ExternalSystem_ExportAudit_ID); } @Override public int getExternalSystem_ExportAudit_ID() {
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ExportAudit_ID); } @Override public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class); } @Override public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_ExportAudit.java
1
请在Spring Boot框架中完成以下Java代码
public class PickingRequestedEvent implements MaterialEvent { public static final String TYPE = "PickingRequestedEvent"; EventDescriptor eventDescriptor; int shipmentScheduleId; int pickingSlotId; Set<Integer> topLevelHuIdsToPick; @Builder @JsonCreator public PickingRequestedEvent( @JsonProperty("eventDescriptor") final EventDescriptor eventDescriptor, @JsonProperty("shipmentScheduleId") final int shipmentScheduleId, @JsonProperty("pickingSlotId") final int pickingSlotId, @JsonProperty("topLevelHuIdsToPick") final Set<Integer> topLevelHuIdsToPick) { this.eventDescriptor = eventDescriptor; this.shipmentScheduleId = shipmentScheduleId; this.pickingSlotId = pickingSlotId; this.topLevelHuIdsToPick = topLevelHuIdsToPick; }
public void assertValid() { Check.errorIf(eventDescriptor == null, "eventDescriptor may not be null"); Check.errorIf(topLevelHuIdsToPick == null, "topLevelHuIdsToPick may not be null"); Check.errorIf(topLevelHuIdsToPick.isEmpty(), "topLevelHuIdsToPick may not be empty"); checkIdGreaterThanZero("shipmentScheduleId", shipmentScheduleId); } @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, shipmentScheduleId); } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\picking\PickingRequestedEvent.java
2
请完成以下Java代码
public static void skipExchange(ServerWebExchange exchange) { exchange.getAttributes().put(SHOULD_NOT_FILTER, Boolean.TRUE); } private Mono<Void> validateToken(ServerWebExchange exchange) { return this.csrfTokenRepository.loadToken(exchange) .switchIfEmpty(Mono.defer(() -> Mono.error(new CsrfException("An expected CSRF token cannot be found")))) .filterWhen((expected) -> containsValidCsrfToken(exchange, expected)) .switchIfEmpty(Mono.defer(() -> Mono.error(new CsrfException("Invalid CSRF Token")))) .then(); } private Mono<Boolean> containsValidCsrfToken(ServerWebExchange exchange, CsrfToken expected) { return this.requestHandler.resolveCsrfTokenValue(exchange, expected) .map((actual) -> equalsConstantTime(actual, expected.getToken())); } private Mono<Void> continueFilterChain(ServerWebExchange exchange, WebFilterChain chain) { return Mono.defer(() -> { Mono<CsrfToken> csrfToken = csrfToken(exchange); this.requestHandler.handle(exchange, csrfToken); return chain.filter(exchange); }); } private Mono<CsrfToken> csrfToken(ServerWebExchange exchange) { return this.csrfTokenRepository.loadToken(exchange).switchIfEmpty(generateToken(exchange)); } /** * Constant time comparison to prevent against timing attacks. * @param expected * @param actual * @return */ private static boolean equalsConstantTime(String expected, String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes); } private Mono<CsrfToken> generateToken(ServerWebExchange exchange) {
return this.csrfTokenRepository.generateToken(exchange) .delayUntil((token) -> this.csrfTokenRepository.saveToken(exchange, token)) .cache(); } private static class DefaultRequireCsrfProtectionMatcher implements ServerWebExchangeMatcher { private static final Set<HttpMethod> ALLOWED_METHODS = new HashSet<>( Arrays.asList(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.TRACE, HttpMethod.OPTIONS)); @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()) .flatMap((r) -> Mono.justOrEmpty(r.getMethod())) .filter(ALLOWED_METHODS::contains) .flatMap((m) -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\CsrfWebFilter.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 setSupervisor_ID (final int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID); } @Override public int getSupervisor_ID() { return get_ValueAsInt(COLUMNNAME_Supervisor_ID); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { throw new IllegalArgumentException ("Timestamp is virtual column"); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() {
return get_ValueAsString(COLUMNNAME_Title); } @Override public void setUnlockAccount (final @Nullable java.lang.String UnlockAccount) { set_Value (COLUMNNAME_UnlockAccount, UnlockAccount); } @Override public java.lang.String getUnlockAccount() { return get_ValueAsString(COLUMNNAME_UnlockAccount); } @Override public void setUserPIN (final @Nullable java.lang.String UserPIN) { set_Value (COLUMNNAME_UserPIN, UserPIN); } @Override public java.lang.String getUserPIN() { return get_ValueAsString(COLUMNNAME_UserPIN); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User.java
1
请完成以下Java代码
public boolean isFailOnException() { return failOnException; } /** * @return true, if the event is an {@link FlowableEntityEvent} and (if needed) the entityClass set in this instance, is assignable from the entity class in the event. */ protected boolean isValidEvent(FlowableEvent event) { boolean valid = false; if (event instanceof FlowableEntityEvent) { if (entityClass == null) { valid = true; } else { valid = entityClass.isAssignableFrom(((FlowableEntityEvent) event).getEntity().getClass()); } } return valid; } /** * Called when an entity create event is received. */ protected void onCreate(FlowableEvent event) { // Default implementation is a NO-OP } /** * Called when an entity initialized event is received.
*/ protected void onInitialized(FlowableEvent event) { // Default implementation is a NO-OP } /** * Called when an entity delete event is received. */ protected void onDelete(FlowableEvent event) { // Default implementation is a NO-OP } /** * Called when an entity update event is received. */ protected void onUpdate(FlowableEvent event) { // Default implementation is a NO-OP } /** * Called when an event is received, which is not a create, an update or delete. */ protected void onEntityEvent(FlowableEvent event) { // Default implementation is a NO-OP } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\delegate\event\BaseEntityEventListener.java
1
请完成以下Java代码
private void registerWsSession(String httpSessionId, WebSocketSession wsSession) { Map<String, WebSocketSession> sessions = this.httpSessionIdToWsSessions.get(httpSessionId); if (sessions == null) { sessions = new ConcurrentHashMap<>(); this.httpSessionIdToWsSessions.putIfAbsent(httpSessionId, sessions); sessions = this.httpSessionIdToWsSessions.get(httpSessionId); } sessions.put(wsSession.getId(), wsSession); } private void closeWsSessions(String httpSessionId) { Map<String, WebSocketSession> sessionsToClose = this.httpSessionIdToWsSessions.remove(httpSessionId); if (sessionsToClose == null) { return; }
if (logger.isDebugEnabled()) { logger.debug("Closing WebSocket connections associated to expired HTTP Session " + httpSessionId); } for (WebSocketSession toClose : sessionsToClose.values()) { try { toClose.close(SESSION_EXPIRED_STATUS); } catch (IOException ex) { logger.debug("Failed to close WebSocketSession (this is nothing to worry about but for debugging only)", ex); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\handler\WebSocketRegistryListener.java
1
请在Spring Boot框架中完成以下Java代码
protected void processRestoredState(CalculatedFieldEntityCtxId id, CalculatedFieldState state, TopicPartitionInfo partition, TbCallback callback) { partition = partition.withTopic(DataConstants.CF_STATES_QUEUE_NAME); actorSystemContext.tellWithHighPriority(new CalculatedFieldStateRestoreMsg(id, state, partition, callback)); } @Override public void restore(QueueKey queueKey, Set<TopicPartitionInfo> partitions) { stateService.update(queueKey, partitions, new QueueStateService.RestoreCallback() { @Override public void onAllPartitionsRestored() { } @Override public void onPartitionRestored(TopicPartitionInfo partition) { partition = partition.withTopic(DataConstants.CF_STATES_QUEUE_NAME); actorSystemContext.tellWithHighPriority(new CalculatedFieldStatePartitionRestoreMsg(partition)); } }); } @Override
public void delete(Set<TopicPartitionInfo> partitions) { stateService.delete(partitions); } @Override public Set<TopicPartitionInfo> getPartitions() { return stateService.getPartitions().values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); } @Override public void stop() { stateService.stop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\AbstractCalculatedFieldStateService.java
2
请完成以下Java代码
public class CompoundWord implements IWord, Iterable<Word> { /** * 由这些词复合而来 */ public List<Word> innerList; /** * 标签,通常是词性 */ public String label; @Override public String getValue() { StringBuilder sb = new StringBuilder(); for (Word word : innerList) { sb.append(word.value); } return sb.toString(); } @Override public String getLabel() { return label; } @Override public void setLabel(String label) { this.label = label; } @Override public void setValue(String value) { innerList.clear(); innerList.add(new Word(value, label)); } @Override public int length() { return getValue().length(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); int i = 1; for (Word word : innerList) { sb.append(word.getValue()); String label = word.getLabel(); if (label != null) { sb.append('/').append(label); } if (i != innerList.size()) { sb.append(' '); } ++i; } sb.append("]/"); sb.append(label); return sb.toString(); } /**
* 转换为一个简单词 * @return */ public Word toWord() { return new Word(getValue(), getLabel()); } public CompoundWord(List<Word> innerList, String label) { this.innerList = innerList; this.label = label; } public static CompoundWord create(String param) { if (param == null) return null; int cutIndex = param.lastIndexOf(']'); if (cutIndex <= 2 || cutIndex == param.length() - 1) return null; String wordParam = param.substring(1, cutIndex); List<Word> wordList = new LinkedList<Word>(); for (String single : wordParam.split("\\s+")) { if (single.length() == 0) continue; Word word = Word.create(single); if (word == null) { Predefine.logger.warning("使用参数" + single + "构造单词时发生错误"); return null; } wordList.add(word); } String labelParam = param.substring(cutIndex + 1); if (labelParam.startsWith("/")) { labelParam = labelParam.substring(1); } return new CompoundWord(wordList, labelParam); } @Override public Iterator<Word> iterator() { return innerList.iterator(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\word\CompoundWord.java
1
请完成以下Java代码
static I_M_HU_PI_Item_Product extractHUPIItemProduct(@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration) { final I_M_HU_PI_Item_Product huPIItemProduct = extractHUPIItemProductOrNull(lutuConfiguration); if (huPIItemProduct == null) { throw new HUException("No PI Item Product set for " + lutuConfiguration); } return huPIItemProduct; } static I_M_HU_PI_Item_Product extractHUPIItemProductOrNull(@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration) { final HUPIItemProductId huPIItemProductId = HUPIItemProductId.ofRepoIdOrNull(lutuConfiguration.getM_HU_PI_Item_Product_ID()); return huPIItemProductId != null ? Services.get(IHUPIItemProductDAO.class).getRecordById(huPIItemProductId) : null; } @Value @Builder class CreateLUTUConfigRequest
{ @NonNull I_M_HU_LUTU_Configuration baseLUTUConfiguration; @NonNull BigDecimal qtyTU; @NonNull BigDecimal qtyCUsPerTU; @NonNull Integer tuHUPIItemProductID; @Nullable BigDecimal qtyLU; @Nullable Integer luHUPIID; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\ILUTUConfigurationFactory.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getResourceSuffixes() { return resourceSuffixes; } public void setResourceSuffixes(List<String> resourceSuffixes) { this.resourceSuffixes = resourceSuffixes; } public boolean isDeployResources() { return deployResources; } public void setDeployResources(boolean deployResources) { this.deployResources = deployResources; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnableSafeXml() { return enableSafeXml; } public void setEnableSafeXml(boolean enableSafeXml) { this.enableSafeXml = enableSafeXml; } public boolean isEventRegistryStartCaseInstanceAsync() { return eventRegistryStartCaseInstanceAsync; }
public void setEventRegistryStartCaseInstanceAsync(boolean eventRegistryStartCaseInstanceAsync) { this.eventRegistryStartCaseInstanceAsync = eventRegistryStartCaseInstanceAsync; } public boolean isEventRegistryUniqueCaseInstanceCheckWithLock() { return eventRegistryUniqueCaseInstanceCheckWithLock; } public void setEventRegistryUniqueCaseInstanceCheckWithLock(boolean eventRegistryUniqueCaseInstanceCheckWithLock) { this.eventRegistryUniqueCaseInstanceCheckWithLock = eventRegistryUniqueCaseInstanceCheckWithLock; } public Duration getEventRegistryUniqueCaseInstanceStartLockTime() { return eventRegistryUniqueCaseInstanceStartLockTime; } public void setEventRegistryUniqueCaseInstanceStartLockTime(Duration eventRegistryUniqueCaseInstanceStartLockTime) { this.eventRegistryUniqueCaseInstanceStartLockTime = eventRegistryUniqueCaseInstanceStartLockTime; } public FlowableServlet getServlet() { return servlet; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\cmmn\FlowableCmmnProperties.java
2
请完成以下Java代码
public BigDecimal getUOMToStockRatio() { return Optional.ofNullable(uomQty) .map(uomQuantity -> { if (uomQuantity.isZero() || stockQty.isZero()) { return BigDecimal.ZERO; } final UOMPrecision uomPrecision = UOMPrecision.ofInt(uomQuantity.getUOM().getStdPrecision()); return uomQuantity.toBigDecimal().setScale(uomPrecision.toInt(), uomPrecision.getRoundingMode()) .divide(stockQty.toBigDecimal(), uomPrecision.getRoundingMode()); }) .orElse(null); } @NonNull public static StockQtyAndUOMQty toZeroIfNegative(@NonNull final StockQtyAndUOMQty stockQtyAndUOMQty) { return stockQtyAndUOMQty.signum() < 0 ? stockQtyAndUOMQty.toZero() : stockQtyAndUOMQty; } @NonNull public static StockQtyAndUOMQty toZeroIfPositive(@NonNull final StockQtyAndUOMQty stockQtyAndUOMQty) { return stockQtyAndUOMQty.signum() > 0
? stockQtyAndUOMQty.toZero() : stockQtyAndUOMQty; } public Quantity getQtyInUOM(@NonNull final UomId uomId, @NonNull final QuantityUOMConverter converter) { if (uomQty != null) { if (UomId.equals(uomQty.getUomId(), uomId)) { return uomQty; } else if (UomId.equals(uomQty.getSourceUomId(), uomId)) { return uomQty.switchToSource(); } } if (UomId.equals(stockQty.getUomId(), uomId)) { return stockQty; } else if (UomId.equals(stockQty.getSourceUomId(), uomId)) { return stockQty.switchToSource(); } return converter.convertQuantityTo(stockQty, productId, uomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\StockQtyAndUOMQty.java
1
请完成以下Java代码
private final SideActionsGroupPanel createGroupComponent(final ISideActionsGroupModel group) { final SideActionsGroupPanel groupComp = new SideActionsGroupPanel(); groupComp.setModel(group); groupComp.addPropertyChangeListener(SideActionsGroupPanel.PROPERTY_Visible, groupPanelChangedListener); return groupComp; } private void destroyGroupComponent(final SideActionsGroupPanel groupComp) { groupComp.removePropertyChangeListener(SideActionsGroupPanel.PROPERTY_Visible, groupPanelChangedListener); } protected void refreshUI() { autoHideIfNeeded(); contentPanel.revalidate(); }
/** * Auto-hide if no groups or groups are not visible */ private final void autoHideIfNeeded() { boolean haveVisibleGroups = false; for (Component groupComp : contentPanel.getComponents()) { if (groupComp.isVisible()) { haveVisibleGroups = true; break; } } setVisible(haveVisibleGroups); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\SideActionsGroupsListPanel.java
1
请完成以下Java代码
private final Map<String, IAttributeStorage> retrieveChildrenAttributeStorages() { final IAttributeStorageFactory storageFactory = getAttributeStorageFactory(); final IHandlingUnitsDAO handlingUnitsDAO = getHandlingUnitsDAO(); final Map<String, IAttributeStorage> childrenAttributeSetStorages = new LinkedHashMap<>(); final I_M_HU hu = getM_HU(); if (hu == null) { return childrenAttributeSetStorages; } // Retrieve HU items and get children HUs final List<I_M_HU_Item> huItems = handlingUnitsDAO.retrieveItems(hu); final boolean saveOnChange = isSaveOnChange(); for (final I_M_HU_Item item : huItems) { final List<I_M_HU> childrenHU = handlingUnitsDAO.retrieveIncludedHUs(item); for (final I_M_HU childHU : childrenHU) { final IAttributeStorage childAttributeSetStorage = storageFactory.getAttributeStorage(childHU); childAttributeSetStorage.setSaveOnChange(saveOnChange); // propagate saveOnChange to child childrenAttributeSetStorages.put(childAttributeSetStorage.getId(), childAttributeSetStorage); } } return childrenAttributeSetStorages;
} /** * Add the given <code>childAttributeStorage</code> to this storage's children. If children were not yet loaded, then this method also loads them. * * @param childAttributeStorage */ @Override protected void addChildAttributeStorage(final IAttributeStorage childAttributeStorage) { final Map<String, IAttributeStorage> childrenAttributeStoragesMap = getInnerChildrenAttributeStoragesMap(true); childrenAttributeStoragesMap.put(childAttributeStorage.getId(), childAttributeStorage); } /** * Removes the given <code>childAttributeStorage</code> from this storage's children. If children were not yet loaded, then this method also loads them. * * @param childAttributeStorage */ @Override protected IAttributeStorage removeChildAttributeStorage(final IAttributeStorage childAttributeStorage) { final Map<String, IAttributeStorage> childrenAttributeStoragesMap = getInnerChildrenAttributeStoragesMap(true); return childrenAttributeStoragesMap.remove(childAttributeStorage.getId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\HUAttributeStorage.java
1
请完成以下Java代码
public class BBANStructureEntry { private BBANCodeEntryType codeType; private EntryCharacterType characterType; private int length; private String seqNo; public BBANStructureEntry() { super(); } public void setCharacterType(EntryCharacterType characterType) { this.characterType = characterType; } public EntryCharacterType getCharacterType() { return characterType; } public void setLength(int length) { this.length = length; } public int getLength() { return length; } public void setSeqNo(String seqNo) { this.seqNo = seqNo; } public String getSeqNo()
{ return seqNo; } public BBANCodeEntryType getCodeType() { return codeType; } public void setCodeType(BBANCodeEntryType codeType) { this.codeType = codeType; } /** * Basic Bank Account Number Entry Types. */ public enum BBANCodeEntryType { bank_code, branch_code, account_number, national_check_digit, account_type, owener_account_type, seqNo } public enum EntryCharacterType { n, // Digits (numeric characters 0 to 9 only) a, // Upper case letters (alphabetic characters A-Z only) c // upper and lower case alphanumeric characters (A-Z, a-z and 0-9) } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\wrapper\BBANStructureEntry.java
1
请完成以下Java代码
public Map<String, VariableValueDto> getVariables() { return variables; } public long getPriority() { return priority; } public String getErrorDetails() { return errorDetails; } public String getBusinessKey() { return businessKey; } public Map<String, String> getExtensionProperties(){ return extensionProperties; } public static LockedExternalTaskDto fromLockedExternalTask(LockedExternalTask task) { LockedExternalTaskDto dto = new LockedExternalTaskDto(); dto.activityId = task.getActivityId(); dto.activityInstanceId = task.getActivityInstanceId(); dto.errorMessage = task.getErrorMessage(); dto.errorDetails = task.getErrorDetails(); dto.executionId = task.getExecutionId(); dto.id = task.getId(); dto.lockExpirationTime = task.getLockExpirationTime(); dto.createTime = task.getCreateTime(); dto.processDefinitionId = task.getProcessDefinitionId(); dto.processDefinitionKey = task.getProcessDefinitionKey(); dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag(); dto.processInstanceId = task.getProcessInstanceId(); dto.retries = task.getRetries(); dto.topicName = task.getTopicName(); dto.workerId = task.getWorkerId(); dto.tenantId = task.getTenantId(); dto.variables = VariableValueDto.fromMap(task.getVariables()); dto.priority = task.getPriority(); dto.businessKey = task.getBusinessKey(); dto.extensionProperties = task.getExtensionProperties(); return dto; } public static List<LockedExternalTaskDto> fromLockedExternalTasks(List<LockedExternalTask> tasks) { List<LockedExternalTaskDto> dtos = new ArrayList<>(); for (LockedExternalTask task : tasks) { dtos.add(LockedExternalTaskDto.fromLockedExternalTask(task)); } return dtos; }
@Override public String toString() { return "LockedExternalTaskDto [activityId=" + activityId + ", activityInstanceId=" + activityInstanceId + ", errorMessage=" + errorMessage + ", errorDetails=" + errorDetails + ", executionId=" + executionId + ", id=" + id + ", lockExpirationTime=" + lockExpirationTime + ", createTime=" + createTime + ", processDefinitionId=" + processDefinitionId + ", processDefinitionKey=" + processDefinitionKey + ", processDefinitionVersionTag=" + processDefinitionVersionTag + ", processInstanceId=" + processInstanceId + ", retries=" + retries + ", suspended=" + suspended + ", workerId=" + workerId + ", topicName=" + topicName + ", tenantId=" + tenantId + ", variables=" + variables + ", priority=" + priority + ", businessKey=" + businessKey + "]"; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\LockedExternalTaskDto.java
1
请完成以下Java代码
public class ManagerDelomboked extends Employee { private String departmentName; private int uid; public ManagerDelomboked(String departmentName, int uid, String name, int id, int age) { super(name, id, age); this.departmentName = departmentName; this.uid = uid; } public boolean equals(final Object o) { if (o == this) return true; if (!(o instanceof com.baeldung.lombok.equalsandhashcode.inheritance.Manager)) return false; final com.baeldung.lombok.equalsandhashcode.inheritance.Manager other = (com.baeldung.lombok.equalsandhashcode.inheritance.Manager) o; if (!other.canEqual((Object) this)) return false; if (!super.equals(o)) return false;
if (this.getUid() != other.getUid()) return false; final Object this$departmentName = this.getDepartmentName(); final Object other$departmentName = other.getDepartmentName(); if (this$departmentName == null ? other$departmentName != null : !this$departmentName.equals(other$departmentName)) return false; return true; } public int hashCode() { final int PRIME = 59; int result = super.hashCode(); result = result * PRIME + this.getUid(); final Object $departmentName = this.getDepartmentName(); result = result * PRIME + ($departmentName == null ? 43 : $departmentName.hashCode()); return result; } }
repos\tutorials-master\lombok-modules\lombok\src\main\java\com\baeldung\lombok\equalsandhashcode\inheritance\ManagerDelomboked.java
1
请完成以下Java代码
private static Object decrypt(final Object encryptedValue) { if (encryptedValue == null) { return null; } return SecureEngine.decrypt(encryptedValue); } public static boolean isValueChanged(Object oldValue, Object value) { if (isNotNullAndIsEmpty(oldValue)) { oldValue = null; } if (isNotNullAndIsEmpty(value)) { value = null; } boolean bChanged = oldValue == null && value != null || oldValue != null && value == null; if (!bChanged && oldValue != null) { if (oldValue.getClass().equals(value.getClass())) { if (oldValue instanceof Comparable<?>) { bChanged = ((Comparable<Object>)oldValue).compareTo(value) != 0; } else
{ bChanged = !oldValue.equals(value); } } else if (value != null) { bChanged = !oldValue.toString().equals(value.toString()); } } return bChanged; } private static boolean isNotNullAndIsEmpty(final Object value) { if (value != null && value instanceof String && value.toString().equals("")) { return true; } else { return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTableUtils.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } public I_PA_ReportLine getPA_ReportLine() throws RuntimeException { return (I_PA_ReportLine)MTable.get(getCtx(), I_PA_ReportLine.Table_Name) .getPO(getPA_ReportLine_ID(), get_TrxName()); } /** Set Report Line. @param PA_ReportLine_ID Report Line */ public void setPA_ReportLine_ID (int PA_ReportLine_ID) { if (PA_ReportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID)); } /** Get Report Line. @return Report Line */ public int getPA_ReportLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID); if (ii == null) return 0; return ii.intValue(); } /** 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 Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_Report.java
1
请完成以下Java代码
protected String getClientSecret() { String clientSecret = oAuth2Properties.getWebClientConfiguration().getSecret(); if (clientSecret == null) { throw new InvalidClientException("no client-secret configured in application properties"); } return clientSecret; } protected String getClientId() { String clientId = oAuth2Properties.getWebClientConfiguration().getClientId(); if (clientId == null) { throw new InvalidClientException("no client-id configured in application properties"); } return clientId; }
/** * Returns the configured OAuth2 token endpoint URI. * * @return the OAuth2 token endpoint URI. */ protected String getTokenEndpoint() { String tokenEndpointUrl = jHipsterProperties.getSecurity().getClientAuthorization().getAccessTokenUri(); if (tokenEndpointUrl == null) { throw new InvalidClientException("no token endpoint configured in application properties"); } return tokenEndpointUrl; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\OAuth2TokenEndpointClientAdapter.java
1
请完成以下Spring Boot application配置
management: endpoint: # AuditEventsEndpoint 端点配置项 auditevents: enabled: true # 是否开启。默认为 true 开启 endpoints: # Actuator HTTP 配置项,对应 WebEndpointProperties 配置类 web: base-path: /actuator # Actuator 提供的 API 接口的根目录。默认为 /actuator exposure: include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 exclude: # 在 include 的基础上,需要排除的端点。通过设置 * ,可以排除所有端点。 s
pring: # Spring Security 配置项,对应 SecurityProperties 配置类 security: # 配置默认的 InMemoryUserDetailsManager 的用户账号与密码。 user: name: user # 账号 password: user # 密码
repos\SpringBoot-Labs-master\lab-34\lab-34-actuator-demo-auditevents\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
private ServiceRepairProjectTaskStatus computeStatusForSparePartsType() { if (getQtyToReserve().signum() <= 0) { return ServiceRepairProjectTaskStatus.COMPLETED; } else if (getQtyReservedOrConsumed().signum() == 0) { return ServiceRepairProjectTaskStatus.NOT_STARTED; } else { return ServiceRepairProjectTaskStatus.IN_PROGRESS; } } public ServiceRepairProjectTask withRepairOrderId(@NonNull final PPOrderId repairOrderId) { return toBuilder() .repairOrderId(repairOrderId) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withRepairOrderDone( @Nullable final String repairOrderSummary,
@Nullable final ProductId repairServicePerformedId) { return toBuilder() .isRepairOrderDone(true) .repairOrderSummary(repairOrderSummary) .repairServicePerformedId(repairServicePerformedId) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withRepairOrderNotDone() { return toBuilder() .isRepairOrderDone(false) .repairOrderSummary(null) .repairServicePerformedId(null) .build() .withUpdatedStatus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectTask.java
2
请在Spring Boot框架中完成以下Java代码
public EnableMemcachedServer.MemcachedProtocol getProtocol() { return this.protocol; } public void setProtocol(EnableMemcachedServer.MemcachedProtocol protocol) { this.protocol = protocol; } } public static class RedisServerProperties { public static final int DEFAULT_PORT = 6379; private int port = DEFAULT_PORT; private String bindAddress;
public String getBindAddress() { return this.bindAddress; } public void setBindAddress(String bindAddress) { this.bindAddress = bindAddress; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ServiceProperties.java
2
请完成以下Java代码
public void setTooltipIconName (java.lang.String TooltipIconName) { set_Value (COLUMNNAME_TooltipIconName, TooltipIconName); } /** Get Tooltip Icon Name. @return Tooltip Icon Name */ @Override public java.lang.String getTooltipIconName () { return (java.lang.String)get_Value(COLUMNNAME_TooltipIconName); } /** * Type AD_Reference_ID=540910 * Reference name: Type_AD_UI_ElementField */ public static final int TYPE_AD_Reference_ID=540910; /** widget = widget */ public static final String TYPE_Widget = "widget"; /** tooltip = tooltip */
public static final String TYPE_Tooltip = "tooltip"; /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementField.java
1
请完成以下Java代码
public class SingleResultReturningCollector<T> extends AbstractResultCollector<T, T> { @Override public void addResult(DistributedMember memberID, T resultOfSingleExecution) { setResult(extractSingleResult(resultOfSingleExecution)); } @SuppressWarnings("unchecked") private <T> T extractSingleResult(Object result) { return (T) Optional.ofNullable(result) .filter(this::isInstanceOfIterableOrIterator) .map(this::toIterator) .filter(Iterator::hasNext) .map(Iterator::next) .map(this::extractSingleResult) .orElseGet(() -> isInstanceOfIterableOrIterator(result) ? null : result);
} private boolean isInstanceOfIterableOrIterator(Object obj) { return obj instanceof Iterable || obj instanceof Iterator; } @SuppressWarnings("unchecked") private <T> Iterator<T> toIterator(Object obj) { return obj instanceof Iterator ? (Iterator<T>) obj : toIterator((Iterable<T>) obj); } private <T> Iterator<T> toIterator(Iterable<T> iterable) { return iterable != null ? iterable.iterator() : Collections.emptyIterator(); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\function\support\SingleResultReturningCollector.java
1
请完成以下Java代码
public HistoricJobLogQuery orderByExecutionId() { orderBy(HistoricJobLogQueryProperty.EXECUTION_ID); return this; } public HistoricJobLogQuery orderByProcessInstanceId() { orderBy(HistoricJobLogQueryProperty.PROCESS_INSTANCE_ID); return this; } public HistoricJobLogQuery orderByProcessDefinitionId() { orderBy(HistoricJobLogQueryProperty.PROCESS_DEFINITION_ID); return this; } public HistoricJobLogQuery orderByProcessDefinitionKey() { orderBy(HistoricJobLogQueryProperty.PROCESS_DEFINITION_KEY); return this; } public HistoricJobLogQuery orderByDeploymentId() { orderBy(HistoricJobLogQueryProperty.DEPLOYMENT_ID); return this; } public HistoricJobLogQuery orderPartiallyByOccurrence() { orderBy(HistoricJobLogQueryProperty.SEQUENCE_COUNTER); return this; } public HistoricJobLogQuery orderByTenantId() { return orderBy(HistoricJobLogQueryProperty.TENANT_ID); } @Override public HistoricJobLogQuery orderByHostname() { return orderBy(HistoricJobLogQueryProperty.HOSTNAME); } // results ////////////////////////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsCountByQueryCriteria(this); } public List<HistoricJobLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsByQueryCriteria(this, page); } // getter ////////////////////////////////// public boolean isTenantIdSet() { return isTenantIdSet; } public String getJobId() { return jobId; } public String getJobExceptionMessage() { return jobExceptionMessage; } public String getJobDefinitionId() { return jobDefinitionId; } public String getJobDefinitionType() { return jobDefinitionType; } public String getJobDefinitionConfiguration() { return jobDefinitionConfiguration; } public String[] getActivityIds() { return activityIds; }
public String[] getFailedActivityIds() { return failedActivityIds; } public String[] getExecutionIds() { return executionIds; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getDeploymentId() { return deploymentId; } public JobState getState() { return state; } public String[] getTenantIds() { return tenantIds; } public String getHostname() { return hostname; } // setter ////////////////////////////////// protected void setState(JobState state) { this.state = state; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricJobLogQueryImpl.java
1
请完成以下Java代码
public class TextFile extends GenericFile { private int wordCount; public TextFile(String name, String content, String version) { String[] words = content.split(" "); this.setWordCount(words.length > 0 ? words.length : 1); this.setContent(content.getBytes()); this.setName(name); this.setVersion(version); this.setExtension(".txt"); } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } public String getFileInfo() {
return "Text File Impl"; } public String read() { return this.getContent() .toString(); } public String read(int limit) { return this.getContent() .toString() .substring(0, limit); } public String read(int start, int stop) { return this.getContent() .toString() .substring(start, stop); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-inheritance-2\src\main\java\com\baeldung\polymorphism\TextFile.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringSecurityConfiguration { //LDAP or Database //In Memory //InMemoryUserDetailsManager //InMemoryUserDetailsManager(UserDetails... users) @Bean public InMemoryUserDetailsManager createUserDetailsManager() { UserDetails userDetails1 = createNewUser("in28minutes", "dummy"); UserDetails userDetails2 = createNewUser("ranga", "dummydummy"); return new InMemoryUserDetailsManager(userDetails1, userDetails2); } private UserDetails createNewUser(String username, String password) { Function<String, String> passwordEncoder = input -> passwordEncoder().encode(input); UserDetails userDetails = User.builder() .passwordEncoder(passwordEncoder) .username(username) .password(password) .roles("USER","ADMIN") .build(); return userDetails; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } //All URLs are protected //A login form is shown for unauthorized requests //CSRF disable //Frames @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests( auth -> auth.anyRequest().authenticated()); http.formLogin(withDefaults()); http.csrf(AbstractHttpConfigurer::disable); // OR // http.csrf(AbstractHttpConfigurer::disable); http.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)); // Starting from SB 3.1.x return http.build(); } }
repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\security\SpringSecurityConfiguration.java
2
请完成以下Java代码
public class SubscriptionTermEventListener extends FallbackFlatrateTermEventListener { public static final String TYPE_CONDITIONS_SUBSCRIPTION = X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription; private static final String MSG_TERM_ERROR_DELIVERY_ALREADY_HAS_SHIPMENT_SCHED_0P = "Term_Error_Delivery_Already_Has_Shipment_Sched"; @Override public void beforeFlatrateTermReactivate(@NonNull final I_C_Flatrate_Term term) { // Delete subscription progress entries final ISubscriptionDAO subscriptionBL = Services.get(ISubscriptionDAO.class); final List<I_C_SubscriptionProgress> entries = subscriptionBL.retrieveSubscriptionProgresses(SubscriptionProgressQuery.builder() .term(term).build()); for (final I_C_SubscriptionProgress entry : entries) { if (entry.getM_ShipmentSchedule_ID() > 0) { throw new AdempiereException("@" + MSG_TERM_ERROR_DELIVERY_ALREADY_HAS_SHIPMENT_SCHED_0P + "@"); } InterfaceWrapperHelper.delete(entry); } } @Override public void beforeSaveOfNextTermForPredecessor( @NonNull final I_C_Flatrate_Term next, @NonNull final I_C_Flatrate_Term predecessor) { final I_C_Flatrate_Conditions conditions = next.getC_Flatrate_Conditions(); if (X_C_Flatrate_Conditions.ONFLATRATETERMEXTEND_CalculatePrice.equals(conditions.getOnFlatrateTermExtend())) { final IPricingResult pricingInfo = FlatrateTermPricing.builder() .termRelatedProductId(ProductId.ofRepoIdOrNull(next.getM_Product_ID())) .term(next) .priceDate(TimeUtil.asLocalDate(next.getStartDate())) .qty(next.getPlannedQtyPerUnit()) .build() .computeOrThrowEx();
next.setPriceActual(pricingInfo.getPriceStd()); next.setC_Currency_ID(pricingInfo.getCurrencyRepoId()); next.setC_UOM_ID(UomId.toRepoId(pricingInfo.getPriceUomId())); next.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingInfo.getTaxCategoryId())); next.setIsTaxIncluded(pricingInfo.isTaxIncluded()); } else if (X_C_Flatrate_Conditions.ONFLATRATETERMEXTEND_CopyPrice.equals(conditions.getOnFlatrateTermExtend())) { next.setPriceActual(predecessor.getPriceActual()); next.setC_Currency_ID(predecessor.getC_Currency_ID()); next.setC_UOM_ID(predecessor.getC_UOM_ID()); next.setC_TaxCategory_ID(predecessor.getC_TaxCategory_ID()); next.setIsTaxIncluded(predecessor.isTaxIncluded()); } else { throw new AdempiereException("Unexpected OnFlatrateTermExtend=" + conditions.getOnFlatrateTermExtend()) .appendParametersToMessage() .setParameter("conditions", conditions) .setParameter("predecessor", predecessor) .setParameter("next", next); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\SubscriptionTermEventListener.java
1
请完成以下Java代码
public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ProcessDefinitionImpl that = (ProcessDefinitionImpl) o; return ( version == that.version && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(key, that.key) && Objects.equals(formKey, that.formKey) ); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id, name, description, version, key, formKey); }
@Override public String toString() { return ( "ProcessDefinition{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", key='" + key + '\'' + ", description='" + description + '\'' + ", formKey='" + formKey + '\'' + ", version=" + version + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessDefinitionImpl.java
1
请完成以下Java代码
public TbQueueProducer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsEventsProducer() { return TbKafkaProducerTemplate.<TbProtoQueueMsg<ToEdqsMsg>>builder() .clientId("edqs-events-producer-" + serviceInfoProvider.getServiceId()) .defaultTopic(topicService.buildTopicName(edqsConfig.getEventsTopic())) .settings(kafkaSettings) .admin(edqsEventsAdmin) .build(); } @Override public TbQueueRequestTemplate<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> createEdqsRequestTemplate() { throw new UnsupportedOperationException(); } @PreDestroy private void destroy() { if (coreAdmin != null) { coreAdmin.destroy(); } if (ruleEngineAdmin != null) { ruleEngineAdmin.destroy(); } if (jsExecutorRequestAdmin != null) { jsExecutorRequestAdmin.destroy();
} if (jsExecutorResponseAdmin != null) { jsExecutorResponseAdmin.destroy(); } if (notificationAdmin != null) { notificationAdmin.destroy(); } if (fwUpdatesAdmin != null) { fwUpdatesAdmin.destroy(); } if (cfAdmin != null) { cfAdmin.destroy(); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\KafkaTbRuleEngineQueueFactory.java
1
请在Spring Boot框架中完成以下Java代码
public JSONObject getAllRoles() { return userService.getAllRoles(); } /** * 角色列表 */ @RequiresPermissions("role:list") @GetMapping("/listRole") public JSONObject listRole() { return userService.listRole(); } /** * 查询所有权限, 给角色分配权限时调用 */ @RequiresPermissions("role:list") @GetMapping("/listAllPermission") public JSONObject listAllPermission() { return userService.listAllPermission(); } /** * 新增角色 */ @RequiresPermissions("role:add") @PostMapping("/addRole") public JSONObject addRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleName,permissions"); return userService.addRole(requestJson); } /** * 修改角色 */ @RequiresPermissions("role:update")
@PostMapping("/updateRole") public JSONObject updateRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleId,roleName,permissions"); return userService.updateRole(requestJson); } /** * 删除角色 */ @RequiresPermissions("role:delete") @PostMapping("/deleteRole") public JSONObject deleteRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleId"); return userService.deleteRole(requestJson); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\controller\UserController.java
2
请在Spring Boot框架中完成以下Java代码
public void delMember(Long memberId) { UmsMember umsMember = memberMapper.selectByPrimaryKey(memberId); if (umsMember != null) { String key = REDIS_DATABASE + ":" + REDIS_KEY_MEMBER + ":" + umsMember.getUsername(); redisService.del(key); } } @Override public UmsMember getMember(String username) { String key = REDIS_DATABASE + ":" + REDIS_KEY_MEMBER + ":" + username; return (UmsMember) redisService.get(key); } @Override public void setMember(UmsMember member) { String key = REDIS_DATABASE + ":" + REDIS_KEY_MEMBER + ":" + member.getUsername(); redisService.set(key, member, REDIS_EXPIRE);
} @CacheException @Override public void setAuthCode(String telephone, String authCode) { String key = REDIS_DATABASE + ":" + REDIS_KEY_AUTH_CODE + ":" + telephone; redisService.set(key,authCode,REDIS_EXPIRE_AUTH_CODE); } @CacheException @Override public String getAuthCode(String telephone) { String key = REDIS_DATABASE + ":" + REDIS_KEY_AUTH_CODE + ":" + telephone; return (String) redisService.get(key); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberCacheServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getKey() { return key; }
public boolean isLatest() { return latest; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentQueryImpl.java
2
请完成以下Java代码
public static List<SecurityFilterRule> createFilterRules(SecurityFilterConfig config, String applicationPath) { PathFilterConfig pathFilter = config.getPathFilter(); PathFilterRule rule = createPathFilterRule(pathFilter, applicationPath); return new ArrayList<>(Collections.singletonList(rule)); } protected static PathFilterRule createPathFilterRule(PathFilterConfig pathFilter, String applicationPath) { PathFilterRule pathFilterRule = new PathFilterRule(); for (PathMatcherConfig pathMatcherConfig : pathFilter.getDeniedPaths()) { pathFilterRule.getDeniedPaths().add(transformPathMatcher(pathMatcherConfig, applicationPath)); } for (PathMatcherConfig pathMatcherConfig : pathFilter.getAllowedPaths()) { pathFilterRule.getAllowedPaths().add(transformPathMatcher(pathMatcherConfig, applicationPath)); } return pathFilterRule; } protected static RequestMatcher transformPathMatcher(PathMatcherConfig pathMatcherConfig, String applicationPath) { RequestFilter requestMatcher = new RequestFilter( pathMatcherConfig.getPath(), applicationPath, pathMatcherConfig.getParsedMethods()); RequestAuthorizer requestAuthorizer = RequestAuthorizer.AUTHORIZE_ANNONYMOUS; if (pathMatcherConfig.getAuthorizer() != null) { String authorizeCls = pathMatcherConfig.getAuthorizer(); requestAuthorizer = (RequestAuthorizer) ReflectUtil.instantiate(authorizeCls); } return new RequestMatcher(requestMatcher, requestAuthorizer); } /** * Iterate over a number of filter rules and match them against
* the given request. * * @param requestMethod * @param requestUri * @param filterRules * * @return the checked request with authorization information attached */ public static Authorization authorize(String requestMethod, String requestUri, List<SecurityFilterRule> filterRules) { Authorization authorization; for (SecurityFilterRule filterRule : filterRules) { authorization = filterRule.authorize(requestMethod, requestUri); if (authorization != null) { return authorization; } } // grant if no filter disallows it return Authorization.granted(Authentication.ANONYMOUS); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\util\FilterRules.java
1
请完成以下Java代码
public List<NotificationRule> findEnabledNotificationRulesByTenantIdAndTriggerType(TenantId tenantId, NotificationRuleTriggerType triggerType) { return notificationRuleDao.findByTenantIdAndTriggerTypeAndEnabled(tenantId, triggerType, true); } @Override public void deleteNotificationRuleById(TenantId tenantId, NotificationRuleId id) { notificationRuleDao.removeById(tenantId, id.getId()); eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build()); } @Override public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteNotificationRuleById(tenantId, (NotificationRuleId) id); } @Override public void deleteNotificationRulesByTenantId(TenantId tenantId) { notificationRuleDao.removeByTenantId(tenantId); } @Override public void deleteByTenantId(TenantId tenantId) {
deleteNotificationRulesByTenantId(tenantId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findNotificationRuleById(tenantId, new NotificationRuleId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(notificationRuleDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_RULE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationRuleService.java
1
请在Spring Boot框架中完成以下Java代码
ClientCacheConfigurer clientCacheNameConfigurer(Environment environment) { return (beanName, clientCacheFactoryBean) -> configureCacheName(environment, clientCacheFactoryBean); } @Bean @Order(Ordered.HIGHEST_PRECEDENCE + 1) // apply next (e.g. after @UseMemberName) @ConditionalOnMissingProperty({ SPRING_DATA_GEMFIRE_CACHE_NAME_PROPERTY, SPRING_DATA_GEMFIRE_NAME_PROPERTY, SPRING_DATA_GEODE_CACHE_NAME_PROPERTY, SPRING_DATA_GEODE_NAME_PROPERTY, }) PeerCacheConfigurer peerCacheNameConfigurer(Environment environment) { return (beanName, peerCacheFactoryBean) -> configureCacheName(environment, peerCacheFactoryBean); } private void configureCacheName(Environment environment, CacheFactoryBean cacheFactoryBean) { String springApplicationName = resolveSpringApplicationName(environment);
if (StringUtils.hasText(springApplicationName)) { setGemFireName(cacheFactoryBean, springApplicationName); } } private String resolveSpringApplicationName(Environment environment) { return Optional.ofNullable(environment) .filter(it -> it.containsProperty(SPRING_APPLICATION_NAME_PROPERTY)) .map(it -> it.getProperty(SPRING_APPLICATION_NAME_PROPERTY)) .filter(StringUtils::hasText) .orElse(null); } private void setGemFireName(CacheFactoryBean cacheFactoryBean, String gemfireName) { cacheFactoryBean.getProperties().setProperty(GEMFIRE_NAME_PROPERTY, gemfireName); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\CacheNameAutoConfiguration.java
2
请完成以下Java代码
public ImportTableDescriptor getByTableId(@NonNull final AdTableId adTableId) { return importTableDescriptors.getOrLoad(adTableId, this::retrieveByTableId); } public ImportTableDescriptor getByTableName(@NonNull final String tableName) { final AdTableId adTableId = AdTableId.ofRepoId(adTablesRepo.retrieveTableId(tableName)); return getByTableId(adTableId); } private ImportTableDescriptor retrieveByTableId(@NonNull final AdTableId adTableId) { final POInfo poInfo = POInfo.getPOInfo(adTableId); Check.assumeNotNull(poInfo, "poInfo is not null for AD_Table_ID={}", adTableId); final String tableName = poInfo.getTableName(); final String keyColumnName = poInfo.getKeyColumnName(); if (keyColumnName == null) { throw new AdempiereException("Table " + tableName + " has not primary key"); } assertColumnNameExists(ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID, poInfo); assertColumnNameExists(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg, poInfo); return ImportTableDescriptor.builder() .tableName(tableName)
.keyColumnName(keyColumnName) // .dataImportConfigIdColumnName(columnNameIfExists(COLUMNNAME_C_DataImport_ID, poInfo)) .adIssueIdColumnName(columnNameIfExists(COLUMNNAME_AD_Issue_ID, poInfo)) .importLineContentColumnName(columnNameIfExists(COLUMNNAME_I_LineContent, poInfo)) .importLineNoColumnName(columnNameIfExists(COLUMNNAME_I_LineNo, poInfo)) .errorMsgMaxLength(poInfo.getFieldLength(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg)) // .build(); } private static void assertColumnNameExists(@NonNull final String columnName, @NonNull final POInfo poInfo) { if (!poInfo.hasColumnName(columnName)) { throw new AdempiereException("No " + poInfo.getTableName() + "." + columnName + " defined"); } } private static String columnNameIfExists(@NonNull final String columnName, @NonNull final POInfo poInfo) { return poInfo.hasColumnName(columnName) ? columnName : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImportTableDescriptorRepository.java
1
请完成以下Java代码
public String toString() { return "ACCEPT_ALL"; } @Override public Set<String> getParameters(@Nullable final String contextTableName) { return ImmutableSet.of(); } @Override public boolean accept(final IValidationContext evalCtx, final NamePair item) { return true; } }; public static Composer compose() { return new Composer(); } @EqualsAndHashCode private static final class ComposedNamePairPredicate implements INamePairPredicate { private final ImmutableSet<INamePairPredicate> predicates; private ComposedNamePairPredicate(final Set<INamePairPredicate> predicates) { // NOTE: we assume the predicates set is: not empty, has more than one element, does not contain nulls this.predicates = ImmutableSet.copyOf(predicates); } @Override public String toString() { return MoreObjects.toStringHelper("composite") .addValue(predicates) .toString(); } @Override public ImmutableSet<String> getParameters(@Nullable final String contextTableName) { return predicates.stream() .flatMap(predicate -> predicate.getParameters(contextTableName).stream()) .collect(ImmutableSet.toImmutableSet()); } @Override public boolean accept(final IValidationContext evalCtx, final NamePair item) { for (final INamePairPredicate predicate : predicates) { if (predicate.accept(evalCtx, item)) { return true; } } return false; } } public static class Composer { private Set<INamePairPredicate> collectedPredicates = null; private Composer() { super(); } public INamePairPredicate build() { if (collectedPredicates == null || collectedPredicates.isEmpty())
{ return ACCEPT_ALL; } else if (collectedPredicates.size() == 1) { return collectedPredicates.iterator().next(); } else { return new ComposedNamePairPredicate(collectedPredicates); } } public Composer add(@Nullable final INamePairPredicate predicate) { if (predicate == null || predicate == ACCEPT_ALL) { return this; } if (collectedPredicates == null) { collectedPredicates = new LinkedHashSet<>(); } if (collectedPredicates.contains(predicate)) { return this; } collectedPredicates.add(predicate); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\NamePairPredicates.java
1
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (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(); } @Override public org.compiere.model.I_C_DataImport getC_DataImport() { return get_ValueAsPO(COLUMNNAME_C_DataImport_ID, org.compiere.model.I_C_DataImport.class); } @Override public void setC_DataImport(org.compiere.model.I_C_DataImport C_DataImport) { set_ValueFromPO(COLUMNNAME_C_DataImport_ID, org.compiere.model.I_C_DataImport.class, C_DataImport); } /** Set Daten Import. @param C_DataImport_ID Daten Import */ @Override public void setC_DataImport_ID (int C_DataImport_ID) { if (C_DataImport_ID < 1) set_Value (COLUMNNAME_C_DataImport_ID, null); else set_Value (COLUMNNAME_C_DataImport_ID, Integer.valueOf(C_DataImport_ID)); } /** Get Daten Import. @return Daten Import */ @Override public int getC_DataImport_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Data Import Run. @param C_DataImport_Run_ID Data Import Run */ @Override public void setC_DataImport_Run_ID (int C_DataImport_Run_ID) { if (C_DataImport_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, null); else
set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, Integer.valueOf(C_DataImport_Run_ID)); } /** Get Data Import Run. @return Data Import Run */ @Override public int getC_DataImport_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beleg fertig stellen. @param IsDocComplete Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen. */ @Override public void setIsDocComplete (boolean IsDocComplete) { set_Value (COLUMNNAME_IsDocComplete, Boolean.valueOf(IsDocComplete)); } /** Get Beleg fertig stellen. @return Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen. */ @Override public boolean isDocComplete () { Object oo = get_Value(COLUMNNAME_IsDocComplete); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DataImport_Run.java
1
请完成以下Java代码
private boolean updateHeader() { String sql = "UPDATE C_Cash c" + " SET StatementDifference=" //replace null with 0 there is no difference with this + "(SELECT COALESCE(SUM(currencyConvert(cl.Amount, cl.C_Currency_ID, cb.C_Currency_ID, c.DateAcct, 0, c.AD_Client_ID, c.AD_Org_ID)),0) " + "FROM C_CashLine cl, C_CashBook cb " + "WHERE cb.C_CashBook_ID=c.C_CashBook_ID" + " AND cl.C_Cash_ID=c.C_Cash_ID" + " AND cl.IsActive='Y'" +") " + "WHERE C_Cash_ID=" + getC_Cash_ID(); int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); if (no != 1) { log.warn("Difference #" + no); } // Ending Balance sql = "UPDATE C_Cash" + " SET EndingBalance = BeginningBalance + StatementDifference " + "WHERE C_Cash_ID=" + getC_Cash_ID(); no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); if (no != 1) { log.warn("Balance #" + no); } return no == 1; } // updateHeader @Override public MCash getC_Cash() throws RuntimeException {
return getParent(); } public String getSummary() { // TODO: improve summary message StringBuffer sb = new StringBuffer(); MCash cash = getC_Cash(); if (cash != null && cash.getC_Cash_ID() > 0) { sb.append(cash.getSummary()); } if (sb.length() > 0) { sb.append(" - "); } sb.append(Msg.translate(getCtx(), COLUMNNAME_Amount)).append(": ").append(getAmount()); return sb.toString(); } } // MCashLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MCashLine.java
1
请在Spring Boot框架中完成以下Java代码
public String showTodos(ModelMap model) { // String name = getLoggedInUserName(model); model.put("todos", todoService.getTodosByUser(model)); // model.put("todos", service.retrieveTodos(name)); return "list-todos"; } @RequestMapping(value = "/add-todo", method = RequestMethod.GET) public String showAddTodoPage(ModelMap model) { model.addAttribute("todo", new Todo()); return "todo"; } @RequestMapping(value = "/delete-todo", method = RequestMethod.GET) public String deleteTodo(@RequestParam long id) { todoService.deleteTodo(id); // service.deleteTodo(id); return "redirect:/list-todos"; } @RequestMapping(value = "/update-todo", method = RequestMethod.GET) public String showUpdateTodoPage(@RequestParam long id, ModelMap model) { Todo todo = todoService.getTodoById(id).get(); model.put("todo", todo); return "todo"; } @RequestMapping(value = "/update-todo", method = RequestMethod.POST) public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } // todo.setUserName(getLoggedInUserName(model));
todoService.updateTodo(todo); return "redirect:/list-todos"; } @RequestMapping(value = "/add-todo", method = RequestMethod.POST) public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } // todo.setUserName(getLoggedInUserName(model)); todoService.saveTodo(todo); return "redirect:/list-todos"; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDBNoSec\src\main\java\spring\hibernate\controller\TodoController.java
2
请完成以下Java代码
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getPhoneNumber() {
return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public int hashCode() { return Objects.hash(city, email, firstName, id, lastName, phoneNumber, postalCode, state, street); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Customer)) { return false; } Customer other = (Customer) obj; return Objects.equals(city, other.city) && Objects.equals(email, other.email) && Objects.equals(firstName, other.firstName) && id == other.id && Objects.equals(lastName, other.lastName) && Objects.equals(phoneNumber, other.phoneNumber) && Objects.equals(postalCode, other.postalCode) && Objects.equals(state, other.state) && Objects.equals(street, other.street); } @Override public String toString() { return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", street=" + street + ", postalCode=" + postalCode + ", city=" + city + ", state=" + state + ", phoneNumber=" + phoneNumber + ", email=" + email + "]"; } public static Customer[] fromMockFile() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); InputStream jsonFile = new FileInputStream("src/test/resources/json_optimization_mock_data.json"); Customer[] feedback = objectMapper.readValue(jsonFile, Customer[].class); return feedback; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonoptimization\Customer.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentCandidatesRestController { private final ShipmentCandidateAPIService shipmentCandidateAPIService; public ShipmentCandidatesRestController(@NonNull final ShipmentCandidateAPIService shipmentCandidateAPIService) { this.shipmentCandidateAPIService = shipmentCandidateAPIService; } @GetMapping("shipmentCandidates") public ResponseEntity<JsonResponseShipmentCandidates> getShipmentCandidates( @ApiParam("Max number orders per request for which shipmentSchedules shall be returned.\n" + "ShipmentSchedules without an order count as one.") // @RequestParam(name = "limit", required = false, defaultValue = "10") // @Nullable final Integer limit) {
final QueryLimit limitEff = QueryLimit.ofNullableOrNoLimit(limit).ifNoLimitUse(10); final JsonResponseShipmentCandidates result = shipmentCandidateAPIService.exportShipmentCandidates(limitEff); return ResponseEntity.ok(result); } @PostMapping("shipmentCandidatesResult") public ResponseEntity<String> postShipmentCandidatesStatus(@RequestBody @NonNull final JsonRequestCandidateResults status) { try (final MDC.MDCCloseable ignore = MDC.putCloseable("TransactionIdAPI", status.getTransactionKey())) { shipmentCandidateAPIService.updateStatus(status); return ResponseEntity.accepted().body("Shipment candidates updated"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ShipmentCandidatesRestController.java
2
请完成以下Java代码
public class DefaultDeploymentCache<T> implements DeploymentCache<T> { private static final Logger logger = LoggerFactory.getLogger(DefaultDeploymentCache.class); protected Map<String, T> cache; /** Cache with no limit */ public DefaultDeploymentCache() { this.cache = synchronizedMap(new HashMap<String, T>()); } /** * Cache which has a hard limit: no more elements will be cached than the limit. */ public DefaultDeploymentCache(final int limit) { this.cache = synchronizedMap( new LinkedHashMap<String, T>(limit + 1, 0.75f, true) { // +1 is needed, because the entry is inserted first, before it is removed // 0.75 is the default (see javadocs) // true will keep the 'access-order', which is needed to have a real LRU cache private static final long serialVersionUID = 1L; protected boolean removeEldestEntry(Map.Entry<String, T> eldest) { boolean removeEldest = size() > limit; if (removeEldest && logger.isTraceEnabled()) { logger.trace("Cache limit {} is reached, {} will be evicted", limit, eldest.getKey()); } return removeEldest; } } ); } public T get(String id) { return cache.get(id); } public void add(String id, T obj) { cache.put(id, obj);
} public void remove(String id) { cache.remove(id); } @Override public boolean contains(String id) { return cache.containsKey(id); } public void clear() { cache.clear(); } // For testing purposes only public int size() { return cache.size(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\DefaultDeploymentCache.java
1
请在Spring Boot框架中完成以下Java代码
protected final ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment, Element... elements) { boolean deprecated = Arrays.stream(elements).anyMatch(environment::isDeprecated); return deprecated ? environment.resolveItemDeprecation(getGetter()) : null; } private String resolveType(MetadataGenerationEnvironment environment) { return environment.getTypeUtils().getType(getDeclaringElement(), getType()); } /** * Resolve the property description. * @param environment the metadata generation environment * @return the property description */ protected abstract String resolveDescription(MetadataGenerationEnvironment environment); /** * Resolve the default value for this property. * @param environment the metadata generation environment * @return the default value or {@code null} */ protected abstract Object resolveDefaultValue(MetadataGenerationEnvironment environment);
/** * Resolve the {@link ItemDeprecation} for this property. * @param environment the metadata generation environment * @return the deprecation or {@code null} */ protected abstract ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment); /** * Return true if this descriptor is for a property. * @param environment the metadata generation environment * @return if this is a property */ abstract boolean isProperty(MetadataGenerationEnvironment environment); }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\PropertyDescriptor.java
2
请完成以下Java代码
public class ThrottleGatewayFilter implements GatewayFilter { private static final Log log = LogFactory.getLog(ThrottleGatewayFilter.class); private volatile TokenBucket tokenBucket; int capacity; int refillTokens; int refillPeriod; TimeUnit refillUnit; private TokenBucket getTokenBucket() { if (tokenBucket != null) { return tokenBucket; } synchronized (this) { if (tokenBucket == null) { tokenBucket = TokenBuckets.builder() .withCapacity(capacity) .withFixedIntervalRefillStrategy(refillTokens, refillPeriod, refillUnit) .build(); } } return tokenBucket; } public int getCapacity() { return capacity; } public ThrottleGatewayFilter setCapacity(int capacity) { this.capacity = capacity; return this; } public int getRefillTokens() { return refillTokens; } public ThrottleGatewayFilter setRefillTokens(int refillTokens) { this.refillTokens = refillTokens; return this; } public int getRefillPeriod() {
return refillPeriod; } public ThrottleGatewayFilter setRefillPeriod(int refillPeriod) { this.refillPeriod = refillPeriod; return this; } public TimeUnit getRefillUnit() { return refillUnit; } public ThrottleGatewayFilter setRefillUnit(TimeUnit refillUnit) { this.refillUnit = refillUnit; return this; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { TokenBucket tokenBucket = getTokenBucket(); // TODO: get a token bucket for a key log.debug("TokenBucket capacity: " + tokenBucket.getCapacity()); boolean consumed = tokenBucket.tryConsume(); if (consumed) { return chain.filter(exchange); } exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); return exchange.getResponse().setComplete(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-sample\src\main\java\org\springframework\cloud\gateway\sample\ThrottleGatewayFilter.java
1
请完成以下Java代码
public class AddressDetails { private String address; private String zipcode; private List<ContactDetails> contactDetails; public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; }
public List<ContactDetails> getContactDetails() { return contactDetails; } public void setContactDetails(List<ContactDetails> contactDetails) { this.contactDetails = contactDetails; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\pojo\AddressDetails.java
1
请完成以下Java代码
protected BooleanStringExpression createGeneralExpression(final ExpressionContext context, final String expressionStr, final List<Object> expressionChunks) { return new GeneralExpression(context, this, expressionStr, expressionChunks); } }); } private static final class BooleanValueConverter implements ValueConverter<Boolean, BooleanStringExpression> { public static final transient BooleanStringExpressionSupport.BooleanValueConverter instance = new BooleanStringExpressionSupport.BooleanValueConverter(); private BooleanValueConverter() { super(); } @Override public Boolean convertFrom(final Object valueObj, final ExpressionContext options) { if (valueObj == null) { return null; } final Boolean defaultValue = null; return DisplayType.toBoolean(valueObj, defaultValue); } } private static final class NullExpression extends NullExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { public NullExpression(final Compiler<Boolean, BooleanStringExpression> compiler) { super(compiler); } } private static final class ConstantExpression extends ConstantExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { private ConstantExpression(final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final Boolean constantValue) { super(ExpressionContext.EMPTY, compiler, expressionStr, constantValue); } } private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression {
private SingleParameterExpression(final ExpressionContext context, final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final CtxName parameter) { super(context, compiler, expressionStr, parameter); } @Override protected Boolean extractParameterValue(Evaluatee ctx) { return parameter.getValueAsBoolean(ctx); } } private static final class GeneralExpression extends GeneralExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { private GeneralExpression(final ExpressionContext context, final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks) { super(context, compiler, expressionStr, expressionChunks); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\BooleanStringExpressionSupport.java
1
请完成以下Java代码
public void setIsPrinted (boolean IsPrinted) { set_Value (COLUMNNAME_IsPrinted, Boolean.valueOf(IsPrinted)); } /** Get Printed. @return Indicates if this document / line is printed */ public boolean isPrinted () { Object oo = get_Value(COLUMNNAME_IsPrinted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); }
/** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_PayrollConcept.java
1
请在Spring Boot框架中完成以下Java代码
public void copyPreliminaryValues(final I_C_InvoiceLine from, final I_C_InvoiceLine to) { // nothing right now } @Override public void copyValues(final I_C_InvoiceLine from, final I_C_InvoiceLine to) { // 08864 // Make sure the Attribute Set Instance is cloned form the initial invoice line to the credit memo one Services.get(IAttributeSetInstanceBL.class).cloneASI(to, from); // 08908 // Make IsManualPrice false, since the price it taken from the invoiceline to.setPriceActual(from.getPriceActual()); to.setPriceList(from.getPriceList()); to.setPriceLimit(from.getPriceLimit()); to.setPriceEntered(from.getPriceEntered()); final de.metas.adempiere.model.I_C_InvoiceLine invoiceLine = InterfaceWrapperHelper.create(to, de.metas.adempiere.model.I_C_InvoiceLine.class); // set this flag on true; meaning the pricing engine shall not be called in the future because the price was already set from the "parent" invoiceLine invoiceLine.setIsManualPrice(true);
} public static CreditMemoInvoiceLineCopyHandler getInstance() { return CreditMemoInvoiceLineCopyHandler.instance; } /** * */ @Override public Class<I_C_InvoiceLine> getSupportedItemsClass() { return I_C_InvoiceLine.class; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\CreditMemoInvoiceLineCopyHandler.java
2
请完成以下Java代码
public void clear() { headers.clear(); } @Override public Set<String> keySet() { return headers.keySet(); } @Override public Collection<List<String>> values() { return headers.values(); } @Override public Set<Entry<String, List<String>>> entrySet() { return headers.entrySet(); } public void add(String headerName, String headerValue) { headers.computeIfAbsent(headerName, key -> new ArrayList<>()).add(headerValue); } public String formatAsString() { return formatAsString(false); } public String formatAsString(boolean maskValues) { if (rawStringHeaders != null && !maskValues) { return rawStringHeaders; } StringBuilder sb = new StringBuilder(); for (Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); for (String headerValue : entry.getValue()) { sb.append(headerName); if (headerValue != null) { sb.append(": ").append(maskValues ? HEADER_VALUE_MASK : headerValue); } else { sb.append(":"); } sb.append('\n'); } } if (sb.length() > 0) { // Delete the last new line (\n) sb.deleteCharAt(sb.length() - 1);
} return sb.toString(); } public static HttpHeaders parseFromString(String headersString) { HttpHeaders headers = new HttpHeaders(headersString); if (StringUtils.isNotEmpty(headersString)) { try (BufferedReader reader = new BufferedReader(new StringReader(headersString))) { String line = reader.readLine(); while (line != null) { int colonIndex = line.indexOf(':'); if (colonIndex > 0) { String headerName = line.substring(0, colonIndex); if (line.length() > colonIndex + 2) { headers.add(headerName, StringUtils.strip(line.substring(colonIndex + 1))); } else { headers.add(headerName, ""); } line = reader.readLine(); } else { throw new FlowableIllegalArgumentException("Header line '" + line + "' is invalid"); } } } catch (IOException ex) { throw new FlowableException("IO exception occurred", ex); } } return headers; } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpHeaders.java
1
请完成以下Java代码
public class ActiveObjectCounter<T> { private final ConcurrentMap<T, CountDownLatch> locks = new ConcurrentHashMap<>(); private volatile boolean active = true; public void add(T object) { CountDownLatch lock = new CountDownLatch(1); this.locks.putIfAbsent(object, lock); } public void release(T object) { CountDownLatch remove = this.locks.remove(object); if (remove != null) { remove.countDown(); } } public boolean await(long timeout, TimeUnit timeUnit) throws InterruptedException { long t0 = System.currentTimeMillis(); long t1 = t0 + TimeUnit.MILLISECONDS.convert(timeout, timeUnit); while (System.currentTimeMillis() <= t1) { if (this.locks.isEmpty()) { return true; } Collection<T> objects = new HashSet<>(this.locks.keySet()); for (T object : objects) { CountDownLatch lock = this.locks.get(object); if (lock == null) { continue; } t0 = System.currentTimeMillis(); if (lock.await(t1 - t0, TimeUnit.MILLISECONDS)) { this.locks.remove(object); } } } return false; }
public int getCount() { return this.locks.size(); } public void reset() { this.locks.clear(); this.active = true; } public void deactivate() { this.active = false; } public boolean isActive() { return this.active; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\ActiveObjectCounter.java
1
请完成以下Java代码
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdatedTime() { return lastUpdatedTime; } public void setLastUpdatedTime(Date lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public Date getTime() { return getCreateTime();
} public ByteArrayRef getByteArrayRef() { return byteArrayRef; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricVariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", revision=").append(revision); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java
1
请完成以下Java代码
private final IHUProductStorage createProductStorage(final I_M_HU_Storage storage) { final ProductId productId = ProductId.ofRepoId(storage.getM_Product_ID()); final I_C_UOM uom = IHUStorageBL.extractUOM(storage); final HUProductStorage productStorage = new HUProductStorage(this, productId, uom); return productStorage; } @Override public boolean isVirtual() { return virtualHU; } @Override public I_M_HU getM_HU() { return hu; } @Override public String toString() { return "HUStorage [hu=" + hu + ", virtualHU=" + virtualHU + "]"; } @Override public I_C_UOM getC_UOMOrNull() { return dao.getC_UOMOrNull(hu); } @Override public boolean isSingleProductWithQtyEqualsTo(@NonNull final ProductId productId, @NonNull final Quantity qty) { final List<IHUProductStorage> productStorages = getProductStorages(); return productStorages.size() == 1
&& ProductId.equals(productStorages.get(0).getProductId(), productId) && productStorages.get(0).getQty(qty.getUOM()).compareTo(qty) == 0; } @Override public boolean isSingleProductStorageMatching(@NonNull final ProductId productId) { final List<IHUProductStorage> productStorages = getProductStorages(); return isSingleProductStorageMatching(productStorages, productId); } private static boolean isSingleProductStorageMatching(@NonNull final List<IHUProductStorage> productStorages, @NotNull final ProductId productId) { return productStorages.size() == 1 && ProductId.equals(productStorages.get(0).getProductId(), productId); } @Override public boolean isEmptyOrSingleProductStorageMatching(@NonNull final ProductId productId) { final List<IHUProductStorage> productStorages = getProductStorages(); return productStorages.isEmpty() || isSingleProductStorageMatching(productStorages, productId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUStorage.java
1
请完成以下Java代码
public List<ConnectorDefinition> get() throws IOException { List<ConnectorDefinition> connectorDefinitions = new ArrayList<>(); Optional<Resource[]> resourcesOptional = retrieveResources(); if (resourcesOptional.isPresent()) { for (Resource resource : resourcesOptional.get()) { connectorDefinitions.add(read(resource.getInputStream())); } validate(connectorDefinitions); } return connectorDefinitions; } protected void validate(List<ConnectorDefinition> connectorDefinitions) { if (!connectorDefinitions.isEmpty()) { Set<String> processedNames = new HashSet<>(); for (ConnectorDefinition connectorDefinition : connectorDefinitions) { String name = connectorDefinition.getName();
if (name == null || name.isEmpty()) { throw new IllegalStateException("connectorDefinition name cannot be null or empty"); } if (name.contains(".")) { throw new IllegalStateException("connectorDefinition name cannot have '.' character"); } if (!processedNames.add(name)) { throw new IllegalStateException( "More than one connectorDefinition with name '" + name + "' was found. Names must be unique." ); } } } } }
repos\Activiti-develop\activiti-core-common\activiti-spring-connector\src\main\java\org\activiti\core\common\spring\connector\ConnectorDefinitionService.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; } @Override public boolean equals(Object obj) { if (this == obj) {
return true; } if(obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } IdManBook other = (IdManBook) obj; return Objects.equals(id, other.getId()); } @Override public int hashCode() { return Objects.hash(id); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootLombokEqualsAndHashCode\src\main\java\com\app\IdManBook.java
1
请完成以下Java代码
public void release() { this.parent = null; this.id = null; } @Override public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } @Override protected ServletRequest getRequest() { return this.pageContext.getRequest(); } @Override protected ServletResponse getResponse() { return this.pageContext.getResponse(); } @Override protected ServletContext getServletContext() { return this.pageContext.getServletContext(); } private final class PageContextVariableLookupEvaluationContext implements EvaluationContext { private EvaluationContext delegate; private PageContextVariableLookupEvaluationContext(EvaluationContext delegate) { this.delegate = delegate; } @Override public TypedValue getRootObject() { return this.delegate.getRootObject(); } @Override public List<ConstructorResolver> getConstructorResolvers() { return this.delegate.getConstructorResolvers(); } @Override public List<MethodResolver> getMethodResolvers() { return this.delegate.getMethodResolvers(); } @Override public List<PropertyAccessor> getPropertyAccessors() { return this.delegate.getPropertyAccessors(); } @Override public TypeLocator getTypeLocator() { return this.delegate.getTypeLocator(); }
@Override public TypeConverter getTypeConverter() { return this.delegate.getTypeConverter(); } @Override public TypeComparator getTypeComparator() { return this.delegate.getTypeComparator(); } @Override public OperatorOverloader getOperatorOverloader() { return this.delegate.getOperatorOverloader(); } @Override public @Nullable BeanResolver getBeanResolver() { return this.delegate.getBeanResolver(); } @Override public void setVariable(String name, @Nullable Object value) { this.delegate.setVariable(name, value); } @Override public Object lookupVariable(String name) { Object result = this.delegate.lookupVariable(name); if (result == null) { result = JspAuthorizeTag.this.pageContext.findAttribute(name); } return result; } } }
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\JspAuthorizeTag.java
1
请完成以下Java代码
public Object around(ProceedingJoinPoint point) throws Throwable { // 获取类名 String className = point.getTarget().getClass().getName(); // 获取方法 String methodName = point.getSignature().getName(); // 记录开始时间 long beginTime = System.currentTimeMillis(); // 记录返回结果 Object result = null; Exception ex = null; try { // 执行方法 result = point.proceed(); return result; } catch (Exception e) { ex = e;
throw e; } finally { // 计算消耗时间 long costTime = System.currentTimeMillis() - beginTime; // 发生异常,则打印 ERROR 日志 if (ex != null) { logger.error("[className: {}][methodName: {}][cost: {} ms][args: {}][发生异常]", className, methodName, point.getArgs(), ex); // 正常执行,则打印 INFO 日志 } else { logger.info("[className: {}][methodName: {}][cost: {} ms][args: {}][return: {}]", className, methodName, costTime, point.getArgs(), result); } } } }
repos\SpringBoot-Labs-master\lab-37\lab-37-logging-aop\src\main\java\cn\iocoder\springboot\lab37\loggingdemo\aspect\HttpAccessAspect.java
1