instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void setDayOfDelivery (final @Nullable BigDecimal DayOfDelivery)
{
set_Value (COLUMNNAME_DayOfDelivery, DayOfDelivery);
}
@Override
public BigDecimal getDayOfDelivery()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DayOfDelivery);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDeliveryInfo (final @Nullable String DeliveryInfo)
{
set_Value (COLUMNNAME_DeliveryInfo, DeliveryInfo);
}
@Override
public String getDeliveryInfo()
{
return get_ValueAsString(COLUMNNAME_DeliveryInfo);
}
@Override
public void setDeliveryNote (final @Nullable String DeliveryNote)
{
set_Value (COLUMNNAME_DeliveryNote, DeliveryNote);
}
@Override
public String getDeliveryNote()
{
return get_ValueAsString(COLUMNNAME_DeliveryNote);
}
@Override
public void setEndDate (final @Nullable java.sql.Timestamp EndDate)
{
set_Value (COLUMNNAME_EndDate, EndDate);
}
@Override
public java.sql.Timestamp getEndDate()
{
return get_ValueAsTimestamp(COLUMNNAME_EndDate);
}
@Override
public void setExternalId (final String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setExternallyUpdatedAt (final @Nullable java.sql.Timestamp ExternallyUpdatedAt)
{
set_Value (COLUMNNAME_ExternallyUpdatedAt, ExternallyUpdatedAt);
}
@Override
public java.sql.Timestamp getExternallyUpdatedAt()
{
return get_ValueAsTimestamp(COLUMNNAME_ExternallyUpdatedAt);
}
@Override
public void setIsArchived (final boolean IsArchived)
{
set_Value (COLUMNNAME_IsArchived, IsArchived);
}
@Override
public boolean isArchived()
{
return get_ValueAsBoolean(COLUMNNAME_IsArchived);
|
}
@Override
public void setIsInitialCare (final boolean IsInitialCare)
{
set_Value (COLUMNNAME_IsInitialCare, IsInitialCare);
}
@Override
public boolean isInitialCare()
{
return get_ValueAsBoolean(COLUMNNAME_IsInitialCare);
}
@Override
public void setIsSeriesOrder (final boolean IsSeriesOrder)
{
set_Value (COLUMNNAME_IsSeriesOrder, IsSeriesOrder);
}
@Override
public boolean isSeriesOrder()
{
return get_ValueAsBoolean(COLUMNNAME_IsSeriesOrder);
}
@Override
public void setNextDelivery (final @Nullable java.sql.Timestamp NextDelivery)
{
set_Value (COLUMNNAME_NextDelivery, NextDelivery);
}
@Override
public java.sql.Timestamp getNextDelivery()
{
return get_ValueAsTimestamp(COLUMNNAME_NextDelivery);
}
@Override
public void setRootId (final @Nullable String RootId)
{
set_Value (COLUMNNAME_RootId, RootId);
}
@Override
public String getRootId()
{
return get_ValueAsString(COLUMNNAME_RootId);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_Order.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
SecurityFilterChain httpSecurity(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(authorize -> authorize.anyRequest()
.authenticated())
.csrf(Customizer.withDefaults())
.build();
}
@Bean
UserDetailsService userDetailsService() {
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
UserDetails user = User.builder()
.username("john")
|
.password("password")
.passwordEncoder(passwordEncoder::encode)
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password("password")
.passwordEncoder(passwordEncoder::encode)
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-authorization\spring-security-annotation-template-parameter\src\main\java\com\baeldung\security\SecurityConfiguration.java
| 2
|
请完成以下Java代码
|
public static String stream(String url) throws Exception {
try (InputStream input = new URI(url).toURL().openStream()) {
InputStreamReader isr = new InputStreamReader(input, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(isr);
StringBuilder json = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
json.append((char) c);
}
return json.toString();
}
}
public static JsonNode get(String url) throws StreamReadException, DatabindException, MalformedURLException, Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(new URI(url).toURL());
return json;
}
public static <T> T get(String url, Class<T> type) throws StreamReadException, DatabindException, MalformedURLException, Exception {
|
ObjectMapper mapper = new ObjectMapper();
T entity = mapper.readValue(new URI(url).toURL(), type);
return entity;
}
public static String getString(String url) throws Exception {
return get(url).toPrettyString();
}
public static JSONObject getJson(String url) throws Exception {
String json = IOUtils.toString(new URI(url).toURL(), Charset.forName("UTF-8"));
JSONObject object = new JSONObject(json);
return object;
}
}
|
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\jsonurlreader\JsonUrlReader.java
| 1
|
请完成以下Java代码
|
private void createQuarantineHUsByLotNoQuarantineId(final int lotNoQuarantineId)
{
final LotNumberQuarantine lotNoQuarantine = lotNoQuarantineRepo.getById(lotNoQuarantineId);
final I_M_Attribute lotNoAttribute = lotNumberDateAttributeDAO.getLotNumberAttribute();
if (lotNoAttribute == null)
{
throw new AdempiereException("Not lotNo attribute found.");
}
final List<I_M_HU> husForAttributeStringValue = retrieveHUsForAttributeStringValue(
lotNoQuarantine.getProductId(),
lotNoAttribute,
lotNoQuarantine.getLotNo());
for (final I_M_HU hu : husForAttributeStringValue)
{
final HuId huId = HuId.ofRepoId(hu.getM_HU_ID());
if (ddOrderMoveScheduleService.isScheduledToMove(huId))
{
// the HU is already quarantined
continue;
}
final List<de.metas.handlingunits.model.I_M_InOutLine> inOutLinesForHU = huInOutDAO.retrieveInOutLinesForHU(hu);
if (Check.isEmpty(inOutLinesForHU))
{
continue;
}
huLotNoQuarantineService.markHUAsQuarantine(hu);
final I_M_InOut firstReceipt = inOutLinesForHU.get(0).getM_InOut();
final BPartnerLocationId bpLocationId = BPartnerLocationId.ofRepoId(firstReceipt.getC_BPartner_ID(), firstReceipt.getC_BPartner_Location_ID());
husToQuarantine.add(HUToDistribute.builder()
.hu(hu)
.quarantineLotNo(lotNoQuarantine)
.bpartnerLocationId(bpLocationId)
.build());
}
}
|
private List<I_M_HU> retrieveHUsForAttributeStringValue(
final int productId,
final I_M_Attribute attribute,
final String value)
{
final IHUQueryBuilder huQueryBuilder = Services.get(IHandlingUnitsDAO.class)
.createHUQueryBuilder()
.addOnlyWithAttribute(attribute, value)
.addHUStatusesToInclude(ImmutableList.of(X_M_HU.HUSTATUS_Picked, X_M_HU.HUSTATUS_Active));
if (productId > 0)
{
huQueryBuilder.addOnlyWithProductId(ProductId.ofRepoId(productId));
}
return huQueryBuilder.list();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\product\process\WEBUI_M_Product_LotNumber_Quarantine.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractSettings implements Serializable {
@Serial
private static final long serialVersionUID = 7434920549178503670L;
private final Map<String, Object> settings;
protected AbstractSettings(Map<String, Object> settings) {
Assert.notEmpty(settings, "settings cannot be empty");
this.settings = Collections.unmodifiableMap(new HashMap<>(settings));
}
/**
* Returns a configuration setting.
* @param name the name of the setting
* @param <T> the type of the setting
* @return the value of the setting, or {@code null} if not available
*/
@SuppressWarnings("unchecked")
public <T> T getSetting(String name) {
Assert.hasText(name, "name cannot be empty");
return (T) getSettings().get(name);
}
/**
* Returns a {@code Map} of the configuration settings.
* @return a {@code Map} of the configuration settings
*/
public Map<String, Object> getSettings() {
return this.settings;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AbstractSettings that = (AbstractSettings) obj;
return this.settings.equals(that.settings);
}
@Override
public int hashCode() {
return Objects.hash(this.settings);
}
@Override
public String toString() {
return "AbstractSettings {" + "settings=" + this.settings + '}';
}
/**
* A builder for subclasses of {@link AbstractSettings}.
*
* @param <T> the type of object
* @param <B> the type of the builder
*/
protected abstract static class AbstractBuilder<T extends AbstractSettings, B extends AbstractBuilder<T, B>> {
private final Map<String, Object> settings = new HashMap<>();
protected AbstractBuilder() {
}
/**
* Sets a configuration setting.
* @param name the name of the setting
|
* @param value the value of the setting
* @return the {@link AbstractBuilder} for further configuration
*/
public B setting(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
getSettings().put(name, value);
return getThis();
}
/**
* A {@code Consumer} of the configuration settings {@code Map} allowing the
* ability to add, replace, or remove.
* @param settingsConsumer a {@link Consumer} of the configuration settings
* {@code Map}
* @return the {@link AbstractBuilder} for further configuration
*/
public B settings(Consumer<Map<String, Object>> settingsConsumer) {
settingsConsumer.accept(getSettings());
return getThis();
}
public abstract T build();
protected final Map<String, Object> getSettings() {
return this.settings;
}
@SuppressWarnings("unchecked")
protected final B getThis() {
return (B) this;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\AbstractSettings.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JSONDocumentFilter
{
public static DocumentFilterList unwrapList(final List<JSONDocumentFilter> jsonFilters, final DocumentFilterDescriptorsProvider filterDescriptorProvider)
{
if (jsonFilters == null || jsonFilters.isEmpty())
{
return DocumentFilterList.EMPTY;
}
return jsonFilters
.stream()
.map(filterDescriptorProvider::unwrap)
.filter(Objects::nonNull)
.collect(DocumentFilterList.toDocumentFilterList());
}
public static DocumentFilter unwrapAsGenericFilter(final JSONDocumentFilter jsonFilter)
{
return DocumentFilter.builder()
.filterId(jsonFilter.getFilterId())
.parameters(jsonFilter.getParameters()
.stream()
.map(jsonParam -> DocumentFilterParam.builder()
.setFieldName(jsonParam.getParameterName())
.setValue(jsonParam.getValue())
.setValueTo(jsonParam.getValueTo())
.setOperator()
.build())
.collect(GuavaCollectors.toImmutableList()))
.build();
}
public static List<JSONDocumentFilter> ofList(final DocumentFilterList filters, final JSONOptions jsonOpts)
{
if (filters == null || filters.isEmpty())
{
return ImmutableList.of();
}
return filters.stream()
.map(filter -> of(filter, jsonOpts))
.collect(GuavaCollectors.toImmutableList());
}
public static JSONDocumentFilter of(final DocumentFilter filter, final JSONOptions jsonOpts)
{
final String filterId = filter.getFilterId();
final List<JSONDocumentFilterParam> jsonParameters = filter.getParameters()
.stream()
.filter(filterParam -> !filter.isInternalParameter(filterParam.getFieldName()))
.map(filterParam -> JSONDocumentFilterParam.of(filterParam, jsonOpts))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(GuavaCollectors.toImmutableList());
|
return new JSONDocumentFilter(filterId, filter.getCaption(jsonOpts.getAdLanguage()), jsonParameters);
}
@JsonProperty("filterId")
String filterId;
@JsonProperty("caption")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
String caption;
@JsonProperty("parameters")
List<JSONDocumentFilterParam> parameters;
@JsonCreator
@Builder
private JSONDocumentFilter(
@JsonProperty("filterId") @NonNull final String filterId,
@JsonProperty("caption") @Nullable final String caption,
@JsonProperty("parameters") @Nullable @Singular final List<JSONDocumentFilterParam> parameters)
{
Check.assumeNotEmpty(filterId, "filterId is not empty");
this.filterId = filterId;
this.caption = caption;
this.parameters = parameters == null ? ImmutableList.of() : ImmutableList.copyOf(parameters);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\json\JSONDocumentFilter.java
| 2
|
请完成以下Java代码
|
public void save(DataOutputStream out) throws Exception
{
out.writeInt(o.length);
for (char c : o)
{
out.writeChar(c);
}
out.writeInt(w.length);
for (double v : w)
{
out.writeDouble(v);
}
}
@Override
public boolean load(ByteArray byteArray)
{
|
int size = byteArray.nextInt();
o = new char[size];
for (int i = 0; i < size; ++i)
{
o[i] = byteArray.nextChar();
}
size = byteArray.nextInt();
w = new double[size];
for (int i = 0; i < size; ++i)
{
w[i] = byteArray.nextDouble();
}
return true;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\FeatureFunction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AuditLogsCleanUpService extends AbstractCleanUpService {
private final AuditLogDao auditLogDao;
private final SqlPartitioningRepository partitioningRepository;
@Value("${sql.ttl.audit_logs.ttl:0}")
private long ttlInSec;
@Value("${sql.audit_logs.partition_size:168}")
private int partitionSizeInHours;
public AuditLogsCleanUpService(PartitionService partitionService, AuditLogDao auditLogDao, SqlPartitioningRepository partitioningRepository) {
super(partitionService);
this.auditLogDao = auditLogDao;
this.partitioningRepository = partitioningRepository;
}
@Scheduled(initialDelayString = "#{T(org.apache.commons.lang3.RandomUtils).nextLong(0, ${sql.ttl.audit_logs.checking_interval_ms})}",
fixedDelayString = "${sql.ttl.audit_logs.checking_interval_ms}")
|
public void cleanUp() {
long auditLogsExpTime = getCurrentTimeMillis() - TimeUnit.SECONDS.toMillis(ttlInSec);
log.debug("cleanup {}", auditLogsExpTime);
if (isSystemTenantPartitionMine()) {
auditLogDao.cleanUpAuditLogs(auditLogsExpTime);
} else {
partitioningRepository.cleanupPartitionsCache(AUDIT_LOG_TABLE_NAME, auditLogsExpTime, TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
}
public long getCurrentTimeMillis() {
return System.currentTimeMillis();
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ttl\AuditLogsCleanUpService.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Department getDepartment() {
|
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\joins\model\Employee.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public AuthenticationSuccessHandler loginSuccessHandler() {
return new CustomLoginSuccessHandler();
}
/**
* Authentication beans
*/
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider bean = new CustomDaoAuthenticationProvider();
bean.setUserDetailsService(customUserDetailsService);
bean.setPasswordEncoder(encoder());
return bean;
}
/**
* Order of precedence is very important.
* <p>
* Matching occurs from top to bottom - so, the topmost match succeeds first.
*/
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/", "/index", "/authenticate")
.permitAll()
.requestMatchers("/secured/**/**", "/secured/**/**/**", "/secured/socket", "/secured/success")
.authenticated()
.anyRequest()
.authenticated())
.formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login")
.permitAll()
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/authenticate")
.successHandler(loginSuccessHandler())
.failureUrl("/denied")
.permitAll())
.logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutSuccessHandler(logoutSuccessHandler()))
/**
* Applies to User Roles - not to login failures or unauthenticated access attempts.
*/
|
.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.accessDeniedHandler(accessDeniedHandler()))
.authenticationProvider(authenticationProvider());
/** Disabled for local testing */
http.csrf(AbstractHttpConfigurer::disable);
/** This is solely required to support H2 console viewing in Spring MVC with Spring Security */
http.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin()))
.authorizeHttpRequests(Customizer.withDefaults());
return http.build();
}
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.authenticationProvider(authenticationProvider())
.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("/resources/**");
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsecuredsockets\config\SecurityConfig.java
| 2
|
请完成以下Java代码
|
private PackToInfo extractPackToInfo(
@NonNull final PickingCandidate pickingCandidate,
@NonNull final ShipmentSchedulesCache shipmentSchedulesCache)
{
final PackToSpec packToSpec = pickingCandidate.getPackToSpec();
if (packToSpec == null)
{
throw new AdempiereException("Pack To Instructions shall be specified for " + pickingCandidate);
}
final ShipmentScheduleId shipmentScheduleId = pickingCandidate.getShipmentScheduleId();
final ProductId productId = ProductId.ofRepoId(shipmentSchedulesCache.getById(shipmentScheduleId).getM_Product_ID());
return packToHUsProducer.extractPackToInfo(
productId,
packToSpec,
null,
null,
shipmentSchedulesCache.getShipToBPLocationId(shipmentScheduleId),
shipmentSchedulesCache.getShipFromLocatorId(shipmentScheduleId));
}
public I_M_HU packToSingleHU(
@NonNull final IHUContext huContext,
@NonNull final HuId pickFromHUId,
@NonNull final ProductId productId,
@NonNull final Quantity qtyPicked,
@NonNull final PickingCandidateId pickingCandidateId)
{
final PackToInfo packToInfo = getPackToInfo(pickingCandidateId);
final boolean checkIfAlreadyPacked = isOnlyOnePickingCandidatePackedTo(packToInfo);
final List<I_M_HU> packedToHUs = packToHUsProducer.packToHU(
PackToHUsProducer.PackToHURequest.builder()
.huContext(huContext)
.pickFromHUId(pickFromHUId)
.packToInfo(packToInfo)
.productId(productId)
.qtyPicked(qtyPicked)
.catchWeight(null)
.documentRef(pickingCandidateId.toTableRecordReference())
.checkIfAlreadyPacked(checkIfAlreadyPacked)
.createInventoryForMissingQty(false)
.build()
)
.getAllTURecords();
if (packedToHUs.isEmpty())
{
throw new AdempiereException("Nothing was packed from " + pickFromHUId);
|
}
else if (packedToHUs.size() != 1)
{
final String packedHUsDisplayStr = packedToHUs.stream().map(hu -> String.valueOf(hu.getM_HU_ID())).collect(Collectors.joining(", "));
throw new AdempiereException("More than one HU was packed from " + pickFromHUId + ": " + packedHUsDisplayStr)
.appendParametersToMessage()
.setParameter("qtyPicked", qtyPicked);
}
else
{
return CollectionUtils.singleElement(packedToHUs);
}
}
private PackToInfo getPackToInfo(final PickingCandidateId pickingCandidateId)
{
final PackToInfo packToInfo = packToInfos.get(pickingCandidateId);
if (packToInfo == null)
{
throw new AdempiereException("No Pack To Infos computed for " + pickingCandidateId);
}
return packToInfo;
}
private boolean isOnlyOnePickingCandidatePackedTo(final PackToInfo packToInfo)
{
return pickingCandidateIdsByPackToInfo.get(packToInfo).size() == 1;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\ProcessPickingCandidatesCommand.java
| 1
|
请完成以下Java代码
|
private void updateRecord(final I_UI_Trace record, final UITraceEventCreateRequest from)
{
record.setExternalId(from.getId().getAsString());
record.setEventName(from.getEventName());
record.setTimestamp(Timestamp.from(from.getTimestamp()));
record.setURL(from.getUrl());
record.setUserName(from.getUsername());
record.setCaption(from.getCaption());
record.setUI_ApplicationId(from.getApplicationId() != null ? from.getApplicationId().getAsString() : null);
record.setUI_DeviceId(from.getDeviceId());
record.setUI_TabId(from.getTabId());
record.setUserAgent(from.getUserAgent());
record.setEventData(extractPropertiesAsJsonString(from));
}
private String extractPropertiesAsJsonString(final UITraceEventCreateRequest request)
{
final Map<String, Object> properties = request.getProperties();
|
if (properties == null)
{
return "";
}
try
{
return jsonObjectMapper.writeValueAsString(properties);
}
catch (JsonProcessingException e)
{
logger.warn("Failed converting request's properties to string: {}", request, e);
return properties.toString();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ui_trace\UITraceRepository.java
| 1
|
请完成以下Java代码
|
public int indexOf(Object o) {
return ruleResults.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return ruleResults.lastIndexOf(o);
}
@Override
public ListIterator<DmnDecisionResultEntries> listIterator() {
return asUnmodifiableList().listIterator();
}
@Override
public ListIterator<DmnDecisionResultEntries> listIterator(int index) {
return asUnmodifiableList().listIterator(index);
}
|
@Override
public List<DmnDecisionResultEntries> subList(int fromIndex, int toIndex) {
return asUnmodifiableList().subList(fromIndex, toIndex);
}
@Override
public String toString() {
return ruleResults.toString();
}
protected List<DmnDecisionResultEntries> asUnmodifiableList() {
return Collections.unmodifiableList(ruleResults);
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultImpl.java
| 1
|
请完成以下Java代码
|
public String outputFile(TableInfo tableInfo) {
// custom file name
return projectDir + "/src/main/resources/mybatis/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
// =================== strategy setting ==================
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel) // table name: underline_to_camel
.setColumnNaming(NamingStrategy.underline_to_camel) // file name: underline_to_camel
.setInclude(tableNames) // tableNames
.setCapitalMode(true) // enable CapitalMod(ORACLE )
.setTablePrefix(prefixTable) // remove table prefix
// .setFieldPrefix(pc.getModuleName() + "_") // remove fields prefix
// .setSuperEntityClass("com.maoxs.pojo") // Entity implement
// .setSuperControllerClass("com.maoxs.controller") // Controller implement
// .setSuperEntityColumns("id") // Super Columns
// .setEntityLombokModel(true) // enable lombok
.setControllerMappingHyphenStyle(true); // controller MappingHyphenStyle
// ================== custome template setting:default mybatis-plus/src/main/resources/templates ======================
//default: src/main/resources/templates directory
TemplateConfig tc = new TemplateConfig();
tc.setXml(null) // xml template
.setEntity("/templates/entity.java") // entity template
|
.setMapper("/templates/mapper.java") // mapper template
.setController("/templates/controller.java") // service template
.setService("/templates/service.java") // serviceImpl template
.setServiceImpl("/templates/serviceImpl.java"); // controller template
// ==================== gen setting ===================
AutoGenerator mpg = new AutoGenerator();
mpg.setCfg(cfg)
.setTemplate(tc)
.setGlobalConfig(gc)
.setDataSource(dsc)
.setPackageInfo(pc)
.setStrategy(strategy)
.setTemplateEngine(new FreemarkerTemplateEngine()); // choose freemarker engine,pay attention to pom dependency!
mpg.execute();
}
}
|
repos\springboot-demo-master\generator\src\main\java\com\et\generator\Generator.java
| 1
|
请完成以下Java代码
|
public static <T, R> Collector<T, ?, R> collectUsingListAccumulator(@NonNull final Function<List<T>, R> finisher)
{
final Supplier<List<T>> supplier = ArrayList::new;
final BiConsumer<List<T>, T> accumulator = List::add;
final BinaryOperator<List<T>> combiner = (acc1, acc2) -> {
acc1.addAll(acc2);
return acc1;
};
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T, R> Collector<T, ?, R> collectUsingHashSetAccumulator(@NonNull final Function<HashSet<T>, R> finisher)
{
final Supplier<HashSet<T>> supplier = HashSet::new;
final BiConsumer<HashSet<T>, T> accumulator = HashSet::add;
final BinaryOperator<HashSet<T>> combiner = (acc1, acc2) -> {
acc1.addAll(acc2);
return acc1;
};
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T, R, K> Collector<T, ?, R> collectUsingMapAccumulator(@NonNull final Function<T, K> keyMapper, @NonNull final Function<Map<K, T>, R> finisher)
{
final Supplier<Map<K, T>> supplier = LinkedHashMap::new;
final BiConsumer<Map<K, T>, T> accumulator = (map, item) -> map.put(keyMapper.apply(item), item);
final BinaryOperator<Map<K, T>> combiner = (acc1, acc2) -> {
acc1.putAll(acc2);
return acc1;
};
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T, R, K, V> Collector<T, ?, R> collectUsingMapAccumulator(
@NonNull final Function<T, K> keyMapper,
|
@NonNull final Function<T, V> valueMapper,
@NonNull final Function<Map<K, V>, R> finisher)
{
final Supplier<Map<K, V>> supplier = LinkedHashMap::new;
final BiConsumer<Map<K, V>, T> accumulator = (map, item) -> map.put(keyMapper.apply(item), valueMapper.apply(item));
final BinaryOperator<Map<K, V>> combiner = (acc1, acc2) -> {
acc1.putAll(acc2);
return acc1;
};
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <R, K, V> Collector<Map.Entry<K, V>, ?, R> collectUsingMapAccumulator(@NonNull final Function<Map<K, V>, R> finisher)
{
return collectUsingMapAccumulator(Map.Entry::getKey, Map.Entry::getValue, finisher);
}
public static <T> Collector<T, ?, Optional<ImmutableSet<T>>> toOptionalImmutableSet()
{
return Collectors.collectingAndThen(
ImmutableSet.toImmutableSet(),
set -> !set.isEmpty() ? Optional.of(set) : Optional.empty());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\GuavaCollectors.java
| 1
|
请完成以下Java代码
|
public final boolean isDebugTrxCloseStacktrace()
{
return debugTrxCloseStacktrace;
}
@Override
public final void setDebugTrxCloseStacktrace(final boolean debugTrxCloseStacktrace)
{
this.debugTrxCloseStacktrace = debugTrxCloseStacktrace;
}
@Override
public final void setDebugClosedTransactions(final boolean enabled)
{
trxName2trxLock.lock();
try
{
if (enabled)
{
if (debugClosedTransactionsList == null)
{
debugClosedTransactionsList = new ArrayList<>();
}
}
else
{
debugClosedTransactionsList = null;
}
}
finally
{
trxName2trxLock.unlock();
}
}
@Override
public final boolean isDebugClosedTransactions()
{
return debugClosedTransactionsList != null;
}
@Override
public final List<ITrx> getDebugClosedTransactions()
{
trxName2trxLock.lock();
try
{
if (debugClosedTransactionsList == null)
|
{
return Collections.emptyList();
}
return new ArrayList<>(debugClosedTransactionsList);
}
finally
{
trxName2trxLock.unlock();
}
}
@Override
public void setDebugConnectionBackendId(boolean debugConnectionBackendId)
{
this.debugConnectionBackendId = debugConnectionBackendId;
}
@Override
public boolean isDebugConnectionBackendId()
{
return debugConnectionBackendId;
}
@Override
public String toString()
{
return "AbstractTrxManager [trxName2trx=" + trxName2trx + ", trxName2trxLock=" + trxName2trxLock + ", trxNameGenerator=" + trxNameGenerator + ", threadLocalTrx=" + threadLocalTrx + ", threadLocalOnRunnableFail=" + threadLocalOnRunnableFail + ", debugTrxCreateStacktrace=" + debugTrxCreateStacktrace + ", debugTrxCloseStacktrace=" + debugTrxCloseStacktrace + ", debugClosedTransactionsList="
+ debugClosedTransactionsList + ", debugConnectionBackendId=" + debugConnectionBackendId + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrxManager.java
| 1
|
请完成以下Java代码
|
public String amounts(final ICalloutField calloutField)
{
if (isCalloutActive()) // assuming it is resetting value
{
return NO_ERROR;
}
final I_C_PaymentAllocate paymentAlloc = calloutField.getModel(I_C_PaymentAllocate.class);
// No Invoice
final int C_Invoice_ID = paymentAlloc.getC_Invoice_ID();
if (C_Invoice_ID <= 0)
{
return NO_ERROR;
}
// Get Info from Tab
BigDecimal Amount = paymentAlloc.getAmount();
final BigDecimal DiscountAmt = paymentAlloc.getDiscountAmt();
BigDecimal WriteOffAmt = paymentAlloc.getWriteOffAmt();
|
final BigDecimal OverUnderAmt = paymentAlloc.getOverUnderAmt();
final BigDecimal InvoiceAmt = paymentAlloc.getInvoiceAmt();
// Changed Column
final String colName = calloutField.getColumnName();
// PayAmt - calculate write off
if (I_C_PaymentAllocate.COLUMNNAME_Amount.equals(colName))
{
WriteOffAmt = InvoiceAmt.subtract(Amount).subtract(DiscountAmt).subtract(OverUnderAmt);
paymentAlloc.setWriteOffAmt(WriteOffAmt);
}
else // calculate Amount
{
Amount = InvoiceAmt.subtract(DiscountAmt).subtract(WriteOffAmt).subtract(OverUnderAmt);
paymentAlloc.setAmount(Amount);
}
return NO_ERROR;
} // amounts
} // CalloutPaymentAllocate
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\CalloutPaymentAllocate.java
| 1
|
请完成以下Java代码
|
public class CharPrimitiveLookup extends Lookup {
private char[] elements;
private final char pivot = 'b';
@Setup
@Override
public void prepare() {
char common = 'a';
elements = new char[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
|
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return CharPrimitiveLookup.class.getSimpleName();
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\CharPrimitiveLookup.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MultipartProperties {
/**
* Whether to enable support of multipart uploads.
*/
private boolean enabled = true;
/**
* Intermediate location of uploaded files.
*/
private @Nullable String location;
/**
* Max file size.
*/
private DataSize maxFileSize = DataSize.ofMegabytes(1);
/**
* Max request size.
*/
private DataSize maxRequestSize = DataSize.ofMegabytes(10);
/**
* Threshold after which files are written to disk.
*/
private DataSize fileSizeThreshold = DataSize.ofBytes(0);
/**
* Whether to resolve the multipart request lazily at the time of file or parameter
* access.
*/
private boolean resolveLazily;
/**
* Whether to resolve the multipart request strictly complying with the Servlet
* specification, only to be used for "multipart/form-data" requests.
*/
private boolean strictServletCompliance;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable String getLocation() {
return this.location;
}
public void setLocation(@Nullable String location) {
this.location = location;
}
public DataSize getMaxFileSize() {
return this.maxFileSize;
}
public void setMaxFileSize(DataSize maxFileSize) {
this.maxFileSize = maxFileSize;
}
public DataSize getMaxRequestSize() {
return this.maxRequestSize;
}
public void setMaxRequestSize(DataSize maxRequestSize) {
this.maxRequestSize = maxRequestSize;
|
}
public DataSize getFileSizeThreshold() {
return this.fileSizeThreshold;
}
public void setFileSizeThreshold(DataSize fileSizeThreshold) {
this.fileSizeThreshold = fileSizeThreshold;
}
public boolean isResolveLazily() {
return this.resolveLazily;
}
public void setResolveLazily(boolean resolveLazily) {
this.resolveLazily = resolveLazily;
}
public boolean isStrictServletCompliance() {
return this.strictServletCompliance;
}
public void setStrictServletCompliance(boolean strictServletCompliance) {
this.strictServletCompliance = strictServletCompliance;
}
/**
* Create a new {@link MultipartConfigElement} using the properties.
* @return a new {@link MultipartConfigElement} configured using there properties
*/
public MultipartConfigElement createMultipartConfig() {
MultipartConfigFactory factory = new MultipartConfigFactory();
PropertyMapper map = PropertyMapper.get();
map.from(this.fileSizeThreshold).to(factory::setFileSizeThreshold);
map.from(this.location).whenHasText().to(factory::setLocation);
map.from(this.maxRequestSize).to(factory::setMaxRequestSize);
map.from(this.maxFileSize).to(factory::setMaxFileSize);
return factory.createMultipartConfig();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\MultipartProperties.java
| 2
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected void prepare()
{
final IQueryFilter<I_C_Invoice> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
return;
}
final int selectionCount = queryBL
.createQueryBuilder(I_C_Invoice.class)
.filter(userSelectionFilter)
.addEqualsFilter(I_C_Invoice.COLUMNNAME_DocStatus, X_C_Invoice.DOCSTATUS_Completed)
.addOnlyActiveRecordsFilter()
.create()
.createSelection(getPinstanceId());
|
if (selectionCount <= 0)
{
throw new AdempiereException("@NoSelection@");
}
}
@Override
protected String doIt() throws Exception
{
enqueuer.enqueueSelection(getProcessInfo().getPinstanceId());
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_CancelAndRecreate.java
| 1
|
请完成以下Java代码
|
public List<I_AD_Printer_Tray> retrieveTrays(final LogicalPrinterId printerId)
{
return queryBL.createQueryBuilder(I_AD_Printer_Tray.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_Printer_Tray.COLUMNNAME_AD_Printer_ID, printerId)
.create()
.list();
}
@Override
public Stream<I_AD_PrinterHW> streamActiveHardwarePrinters()
{
return queryBL.createQueryBuilder(I_AD_PrinterHW.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_PrinterHW.COLUMNNAME_AD_PrinterHW_ID)
.create()
.stream();
}
@Override
public List<I_AD_PrinterHW_MediaTray> retrieveMediaTrays(@NonNull final HardwarePrinterId hardwarePrinterId)
{
|
return queryBL.createQueryBuilder(I_AD_PrinterHW_MediaTray.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_PrinterHW_MediaTray.COLUMNNAME_AD_PrinterHW_ID, hardwarePrinterId)
.create()
.list();
}
@Override
public Stream<I_AD_PrinterHW_MediaTray> streamActiveMediaTrays()
{
return queryBL.createQueryBuilder(I_AD_PrinterHW_MediaTray.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_PrinterHW_MediaTray.COLUMNNAME_AD_PrinterHW_ID)
.orderBy(I_AD_PrinterHW_MediaTray.COLUMNNAME_AD_PrinterHW_MediaTray_ID)
.create()
.stream();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\AbstractPrintingDAO.java
| 1
|
请完成以下Java代码
|
public static ShipmentScheduleAndJobSchedulesCollection ofList(final List<ShipmentScheduleAndJobSchedules> list)
{
return list.isEmpty() ? EMPTY : new ShipmentScheduleAndJobSchedulesCollection(list);
}
public static ShipmentScheduleAndJobSchedulesCollection ofShipmentSchedules(final Collection<? extends de.metas.inoutcandidate.model.I_M_ShipmentSchedule> shipmentSchedules)
{
if (shipmentSchedules.isEmpty()) {return EMPTY;}
return shipmentSchedules.stream()
.map(ShipmentScheduleAndJobSchedules::ofShipmentSchedule)
.collect(collect());
}
public static Collector<ShipmentScheduleAndJobSchedules, ?, ShipmentScheduleAndJobSchedulesCollection> collect()
{
return GuavaCollectors.collectUsingListAccumulator(ShipmentScheduleAndJobSchedulesCollection::ofList);
}
public boolean isEmpty() {return list.isEmpty();}
@Override
public @NotNull Iterator<ShipmentScheduleAndJobSchedules> iterator() {return list.iterator();}
public ImmutableSet<PickingJobScheduleId> getJobScheduleIds()
{
return list.stream()
.flatMap(schedule -> schedule.getJobScheduleIds().stream())
.collect(ImmutableSet.toImmutableSet());
}
|
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIdsWithoutJobSchedules()
{
return getShipmentScheduleIds(schedule -> !schedule.hasJobSchedules());
}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIdsWithJobSchedules()
{
return getShipmentScheduleIds(ShipmentScheduleAndJobSchedules::hasJobSchedules);
}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds(@NonNull final Predicate<ShipmentScheduleAndJobSchedules> filter)
{
return list.stream()
.filter(filter)
.map(ShipmentScheduleAndJobSchedules::getShipmentScheduleId)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleAndJobSchedulesCollection.java
| 1
|
请完成以下Java代码
|
private static class AttributeAggregator
{
private final AttributeCode attributeCode;
private final AttributeValueType attributeValueType;
private final HashSet<Object> values = new HashSet<>();
void collect(@NonNull final IAttributeSet from)
{
final Object value = attributeValueType.map(new AttributeValueType.CaseMapper<Object>()
{
@Nullable
@Override
public Object string()
{
return from.getValueAsString(attributeCode);
}
@Override
public Object number()
{
return from.getValueAsBigDecimal(attributeCode);
}
@Nullable
@Override
public Object date()
{
|
return from.getValueAsDate(attributeCode);
}
@Nullable
@Override
public Object list()
{
return from.getValueAsString(attributeCode);
}
});
values.add(value);
}
void updateAggregatedValueTo(@NonNull final IAttributeSet to)
{
if (values.size() == 1 && to.hasAttribute(attributeCode))
{
to.setValue(attributeCode, values.iterator().next());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AttributeSetAggregator.java
| 1
|
请完成以下Java代码
|
private @Nullable String extractMatchAllRemainingPathSegmentsVariable(String path) {
Matcher matcher = ALL_REMAINING_PATH_SEGMENTS_VAR_PATTERN.matcher(path);
return matcher.matches() ? matcher.group(1) : null;
}
/**
* Returns the path for the operation.
* @return the path
*/
public String getPath() {
return this.path;
}
/**
* Returns the name of the variable used to catch all remaining path segments or
* {@code null}.
* @return the variable name
* @since 2.2.0
*/
public @Nullable String getMatchAllRemainingPathSegmentsVariable() {
return this.matchAllRemainingPathSegmentsVariable;
}
/**
* Returns the HTTP method for the operation.
* @return the HTTP method
*/
public WebEndpointHttpMethod getHttpMethod() {
return this.httpMethod;
}
/**
* Returns the media types that the operation consumes.
* @return the consumed media types
*/
public Collection<String> getConsumes() {
return Collections.unmodifiableCollection(this.consumes);
}
/**
* Returns the media types that the operation produces.
* @return the produced media types
*/
public Collection<String> getProduces() {
return Collections.unmodifiableCollection(this.produces);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
WebOperationRequestPredicate other = (WebOperationRequestPredicate) obj;
boolean result = true;
result = result && this.consumes.equals(other.consumes);
|
result = result && this.httpMethod == other.httpMethod;
result = result && this.canonicalPath.equals(other.canonicalPath);
result = result && this.produces.equals(other.produces);
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.consumes.hashCode();
result = prime * result + this.httpMethod.hashCode();
result = prime * result + this.canonicalPath.hashCode();
result = prime * result + this.produces.hashCode();
return result;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(this.httpMethod + " to path '" + this.path + "'");
if (!CollectionUtils.isEmpty(this.consumes)) {
result.append(" consumes: ").append(StringUtils.collectionToCommaDelimitedString(this.consumes));
}
if (!CollectionUtils.isEmpty(this.produces)) {
result.append(" produces: ").append(StringUtils.collectionToCommaDelimitedString(this.produces));
}
return result.toString();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebOperationRequestPredicate.java
| 1
|
请完成以下Java代码
|
public class Md4PasswordEncoder extends AbstractValidatingPasswordEncoder {
private static final String PREFIX = "{";
private static final String SUFFIX = "}";
private StringKeyGenerator saltGenerator = new Base64StringKeyGenerator();
private boolean encodeHashAsBase64;
public void setEncodeHashAsBase64(boolean encodeHashAsBase64) {
this.encodeHashAsBase64 = encodeHashAsBase64;
}
/**
* Encodes the rawPass using a MessageDigest. If a salt is specified it will be merged
* with the password before encoding.
* @param rawPassword The plain text password
* @return Hex string of password digest (or base64 encoded string if
* encodeHashAsBase64 is enabled.
*/
@Override
public String encodeNonNullPassword(String rawPassword) {
String salt = PREFIX + this.saltGenerator.generateKey() + SUFFIX;
return digest(salt, rawPassword);
}
private String digest(String salt, CharSequence rawPassword) {
if (rawPassword == null) {
rawPassword = "";
}
String saltedPassword = rawPassword + salt;
byte[] saltedPasswordBytes = Utf8.encode(saltedPassword);
Md4 md4 = new Md4();
md4.update(saltedPasswordBytes, 0, saltedPasswordBytes.length);
byte[] digest = md4.digest();
String encoded = encodedNonNullPassword(digest);
return salt + encoded;
}
private String encodedNonNullPassword(byte[] digest) {
if (this.encodeHashAsBase64) {
return Utf8.decode(Base64.getEncoder().encode(digest));
}
return new String(Hex.encode(digest));
}
/**
* Takes a previously encoded password and compares it with a rawpassword after mixing
|
* in the salt and encoding that value
* @param rawPassword plain text password
* @param encodedPassword previously encoded password
* @return true or false
*/
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
String salt = extractSalt(encodedPassword);
String rawPasswordEncoded = digest(salt, rawPassword);
return PasswordEncoderUtils.equals(encodedPassword.toString(), rawPasswordEncoded);
}
private String extractSalt(String prefixEncodedPassword) {
int start = prefixEncodedPassword.indexOf(PREFIX);
if (start != 0) {
return "";
}
int end = prefixEncodedPassword.indexOf(SUFFIX, start);
if (end < 0) {
return "";
}
return prefixEncodedPassword.substring(start, end + 1);
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\Md4PasswordEncoder.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
return;
}
@Override
protected String doIt() throws Exception
{
final IADValidatorRegistryBL validatorRegistry = Services.get(IADValidatorRegistryBL.class);
final List<Class<?>> registeredClasses = validatorRegistry.getRegisteredClasses();
for (final Class<?> registeredClass : registeredClasses)
{
final IADValidatorResult errorLog = validatorRegistry.validate(getCtx(), registeredClass);
|
logAllExceptions(errorLog, validatorRegistry.getValidator(registeredClass));
}
return "OK";
}
private void logAllExceptions(final IADValidatorResult errorLog, final IADValidator<?> validator)
{
for (final IADValidatorViolation violation : errorLog.getViolations())
{
addLog(validator.getLogMessage(violation));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\process\AppDictValidator.java
| 1
|
请完成以下Java代码
|
private Runtime.Version getVersion(URL url) {
// The standard JDK handler uses #runtime to indicate that the runtime version
// should be used. This unfortunately doesn't work for us as
// jdk.internal.loader.URLClassPath only adds the runtime fragment when the URL
// is using the internal JDK handler. We need to flip the default to use
// the runtime version. See gh-38050
return "base".equals(url.getRef()) ? JarFile.baseVersion() : JarFile.runtimeVersion();
}
private boolean isLocalFileUrl(URL url) {
return url.getProtocol().equalsIgnoreCase("file") && isLocal(url.getHost());
}
private boolean isLocal(String host) {
return host == null || host.isEmpty() || host.equals("~") || host.equalsIgnoreCase("localhost");
}
private JarFile createJarFileForLocalFile(URL url, Runtime.Version version, Consumer<JarFile> closeAction)
throws IOException {
String path = UrlDecoder.decode(url.getPath());
return new UrlJarFile(new File(path), version, closeAction);
}
private JarFile createJarFileForNested(URL url, Runtime.Version version, Consumer<JarFile> closeAction)
throws IOException {
NestedLocation location = NestedLocation.fromUrl(url);
return new UrlNestedJarFile(location.path().toFile(), location.nestedEntryName(), version, closeAction);
}
private JarFile createJarFileForStream(URL url, Version version, Consumer<JarFile> closeAction) throws IOException {
try (InputStream in = url.openStream()) {
return createJarFileForStream(in, version, closeAction);
}
}
private JarFile createJarFileForStream(InputStream in, Version version, Consumer<JarFile> closeAction)
throws IOException {
Path local = Files.createTempFile("jar_cache", null);
try {
|
Files.copy(in, local, StandardCopyOption.REPLACE_EXISTING);
JarFile jarFile = new UrlJarFile(local.toFile(), version, closeAction);
local.toFile().deleteOnExit();
return jarFile;
}
catch (Throwable ex) {
deleteIfPossible(local, ex);
throw ex;
}
}
private void deleteIfPossible(Path local, Throwable cause) {
try {
Files.delete(local);
}
catch (IOException ex) {
cause.addSuppressed(ex);
}
}
static boolean isNestedUrl(URL url) {
return url.getProtocol().equalsIgnoreCase("nested");
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\UrlJarFileFactory.java
| 1
|
请完成以下Java代码
|
public void setLastEnqueued (final @Nullable java.sql.Timestamp LastEnqueued)
{
set_Value (COLUMNNAME_LastEnqueued, LastEnqueued);
}
@Override
public java.sql.Timestamp getLastEnqueued()
{
return get_ValueAsTimestamp(COLUMNNAME_LastEnqueued);
}
@Override
public void setLastProcessed (final @Nullable java.sql.Timestamp LastProcessed)
{
set_Value (COLUMNNAME_LastProcessed, LastProcessed);
}
@Override
public java.sql.Timestamp getLastProcessed()
{
return get_ValueAsTimestamp(COLUMNNAME_LastProcessed);
}
@Override
public de.metas.async.model.I_C_Queue_WorkPackage getLastProcessed_WorkPackage()
{
return get_ValueAsPO(COLUMNNAME_LastProcessed_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class);
}
@Override
public void setLastProcessed_WorkPackage(final de.metas.async.model.I_C_Queue_WorkPackage LastProcessed_WorkPackage)
{
set_ValueFromPO(COLUMNNAME_LastProcessed_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, LastProcessed_WorkPackage);
}
@Override
public void setLastProcessed_WorkPackage_ID (final int LastProcessed_WorkPackage_ID)
{
if (LastProcessed_WorkPackage_ID < 1)
set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, null);
else
set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, LastProcessed_WorkPackage_ID);
}
@Override
public int getLastProcessed_WorkPackage_ID()
{
return get_ValueAsInt(COLUMNNAME_LastProcessed_WorkPackage_ID);
}
@Override
public void setName (final java.lang.String Name)
{
|
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public de.metas.async.model.I_C_Async_Batch getParent_Async_Batch()
{
return get_ValueAsPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class);
}
@Override
public void setParent_Async_Batch(final de.metas.async.model.I_C_Async_Batch Parent_Async_Batch)
{
set_ValueFromPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, Parent_Async_Batch);
}
@Override
public void setParent_Async_Batch_ID (final int Parent_Async_Batch_ID)
{
if (Parent_Async_Batch_ID < 1)
set_Value (COLUMNNAME_Parent_Async_Batch_ID, null);
else
set_Value (COLUMNNAME_Parent_Async_Batch_ID, Parent_Async_Batch_ID);
}
@Override
public int getParent_Async_Batch_ID()
{
return get_ValueAsInt(COLUMNNAME_Parent_Async_Batch_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
/**
* The {@link User.getId() userId} of the person responsible for this task.
*/
public String getOwner() {
return owner;
}
/**
* indication of how important/urgent this task is with a number between 0 and
* 100 where higher values mean a higher priority and lower values mean lower
* priority: [0..19] lowest, [20..39] low, [40..59] normal, [60..79] high
* [80..100] highest
*/
public int getPriority() {
return priority;
}
/**
* Reference to the process definition or null if it is not related to a
* process.
*/
public String getProcessDefinitionId() {
return processDefinitionId;
}
/**
* Reference to the process instance or null if it is not related to a process
* instance.
*/
public String getProcessInstanceId() {
return processInstanceId;
}
/**
* The id of the activity in the process defining this task or null if this is
* not related to a process
*/
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
/**
* Return the id of the tenant this task belongs to. Can be <code>null</code>
* if the task belongs to no single tenant.
*/
public String getTenantId() {
return tenantId;
}
|
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventName=" + eventName
+ ", name=" + name
+ ", createTime=" + createTime
+ ", lastUpdated=" + lastUpdated
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", taskDefinitionKey=" + taskDefinitionKey
+ ", assignee=" + assignee
+ ", owner=" + owner
+ ", description=" + description
+ ", dueDate=" + dueDate
+ ", followUpDate=" + followUpDate
+ ", priority=" + priority
+ ", deleteReason=" + deleteReason
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseExecutionId=" + caseExecutionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\TaskEvent.java
| 1
|
请完成以下Java代码
|
public static EmbeddedDatabaseConnection get(@Nullable ClassLoader classLoader) {
for (EmbeddedDatabaseConnection candidate : EmbeddedDatabaseConnection.values()) {
String driverClassName = candidate.getDriverClassName();
if (candidate != NONE && driverClassName != null && ClassUtils.isPresent(driverClassName, classLoader)) {
return candidate;
}
}
return NONE;
}
/**
* Convenience method to determine if a given connection factory represents an
* embedded database type.
* @param connectionFactory the connection factory to interrogate
* @return true if the connection factory represents an embedded database
* @since 2.5.1
*/
public static boolean isEmbedded(ConnectionFactory connectionFactory) {
|
OptionsCapableConnectionFactory optionsCapable = OptionsCapableConnectionFactory.unwrapFrom(connectionFactory);
Assert.state(optionsCapable != null,
() -> "Cannot determine database's type as ConnectionFactory is not options-capable. To be "
+ "options-capable, a ConnectionFactory should be created with "
+ ConnectionFactoryBuilder.class.getName());
ConnectionFactoryOptions options = optionsCapable.getOptions();
for (EmbeddedDatabaseConnection candidate : values()) {
if (candidate.embedded.test(options)) {
return true;
}
}
return false;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\EmbeddedDatabaseConnection.java
| 1
|
请完成以下Java代码
|
public class ExceptionMappingAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private final Map<String, String> failureUrlMap = new HashMap<>();
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
String url = this.failureUrlMap.get(exception.getClass().getName());
if (url != null) {
getRedirectStrategy().sendRedirect(request, response, url);
}
else {
super.onAuthenticationFailure(request, response, exception);
}
}
/**
* Sets the map of exception types (by name) to URLs.
* @param failureUrlMap the map keyed by the fully-qualified name of the exception
* class, with the corresponding failure URL as the value.
* @throws IllegalArgumentException if the entries are not Strings or the URL is not
|
* valid.
*/
public void setExceptionMappings(Map<?, ?> failureUrlMap) {
this.failureUrlMap.clear();
for (Map.Entry<?, ?> entry : failureUrlMap.entrySet()) {
Object exception = entry.getKey();
Object url = entry.getValue();
Assert.isInstanceOf(String.class, exception, "Exception key must be a String (the exception classname).");
Assert.isInstanceOf(String.class, url, "URL must be a String");
Assert.isTrue(UrlUtils.isValidRedirectUrl((String) url), () -> "Not a valid redirect URL: " + url);
this.failureUrlMap.put((String) exception, (String) url);
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\ExceptionMappingAuthenticationFailureHandler.java
| 1
|
请完成以下Java代码
|
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setPP_Maturing_Candidates_v_ID (final int PP_Maturing_Candidates_v_ID)
{
if (PP_Maturing_Candidates_v_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Maturing_Candidates_v_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Maturing_Candidates_v_ID, PP_Maturing_Candidates_v_ID);
}
@Override
public int getPP_Maturing_Candidates_v_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Maturing_Candidates_v_ID);
}
@Override
public org.eevolution.model.I_PP_Order_Candidate getPP_Order_Candidate()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Candidate_ID, org.eevolution.model.I_PP_Order_Candidate.class);
}
@Override
public void setPP_Order_Candidate(final org.eevolution.model.I_PP_Order_Candidate PP_Order_Candidate)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Candidate_ID, org.eevolution.model.I_PP_Order_Candidate.class, PP_Order_Candidate);
}
@Override
public void setPP_Order_Candidate_ID (final int PP_Order_Candidate_ID)
{
if (PP_Order_Candidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, PP_Order_Candidate_ID);
}
@Override
public int getPP_Order_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Candidate_ID);
}
@Override
public org.eevolution.model.I_PP_Product_BOMVersions getPP_Product_BOMVersions()
{
return get_ValueAsPO(COLUMNNAME_PP_Product_BOMVersions_ID, org.eevolution.model.I_PP_Product_BOMVersions.class);
}
|
@Override
public void setPP_Product_BOMVersions(final org.eevolution.model.I_PP_Product_BOMVersions PP_Product_BOMVersions)
{
set_ValueFromPO(COLUMNNAME_PP_Product_BOMVersions_ID, org.eevolution.model.I_PP_Product_BOMVersions.class, PP_Product_BOMVersions);
}
@Override
public void setPP_Product_BOMVersions_ID (final int PP_Product_BOMVersions_ID)
{
if (PP_Product_BOMVersions_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, PP_Product_BOMVersions_ID);
}
@Override
public int getPP_Product_BOMVersions_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID);
}
@Override
public void setPP_Product_Planning_ID (final int PP_Product_Planning_ID)
{
if (PP_Product_Planning_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, PP_Product_Planning_ID);
}
@Override
public int getPP_Product_Planning_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_Maturing_Candidates_v.java
| 1
|
请完成以下Java代码
|
public static boolean contains0x00(final String s) {
return s != null && s.contains("\u0000");
}
public static String randomNumeric(int length) {
return RandomStringUtils.secure().nextNumeric(length);
}
public static String random(int length) {
return RandomStringUtils.secure().next(length);
}
public static String random(int length, String chars) {
return RandomStringUtils.secure().next(length, chars);
}
public static String randomAlphanumeric(int count) {
return RandomStringUtils.secure().nextAlphanumeric(count);
}
public static String randomAlphabetic(int count) {
return RandomStringUtils.secure().nextAlphabetic(count);
}
public static String generateSafeToken(int length) {
byte[] bytes = new byte[length];
RANDOM.nextBytes(bytes);
Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
return encoder.encodeToString(bytes);
}
public static String generateSafeToken() {
return generateSafeToken(DEFAULT_TOKEN_LENGTH);
}
public static String truncate(String string, int maxLength) {
return truncate(string, maxLength, n -> "...[truncated " + n + " symbols]");
}
public static String truncate(String string, int maxLength, Function<Integer, String> truncationMarkerFunc) {
if (string == null || maxLength <= 0 || string.length() <= maxLength) {
return string;
}
|
int truncatedSymbols = string.length() - maxLength;
return string.substring(0, maxLength) + truncationMarkerFunc.apply(truncatedSymbols);
}
public static List<String> splitByCommaWithoutQuotes(String value) {
List<String> splitValues = List.of(value.trim().split("\\s*,\\s*"));
List<String> result = new ArrayList<>();
char lastWayInputValue = '#';
for (String str : splitValues) {
char startWith = str.charAt(0);
char endWith = str.charAt(str.length() - 1);
// if first value is not quote, so we return values after split
if (startWith != '\'' && startWith != '"') return splitValues;
// if value is not in quote, so we return values after split
if (startWith != endWith) return splitValues;
// if different way values, so don't replace quote and return values after split
if (lastWayInputValue != '#' && startWith != lastWayInputValue) return splitValues;
result.add(str.substring(1, str.length() - 1));
lastWayInputValue = startWith;
}
return result;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\StringUtils.java
| 1
|
请完成以下Java代码
|
public boolean cancel(boolean mayInterruptIfRunning)
{
// already completed, always return false
return false;
}
@Override
public boolean isCancelled()
{
return false;
}
@Override
public boolean isDone()
{
|
return true;
}
@Override
public T get()
{
return value;
}
@Override
public T get(long timeout, TimeUnit unit)
{
return value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\InstantFuture.java
| 1
|
请完成以下Java代码
|
public void configure(Map<String, ?> configs, boolean isKey) {
if (NO_PARSER.equals(this.parser)) {
String parserMethod = (String) configs.get(isKey ? KEY_PARSER : VALUE_PARSER);
Assert.state(parserMethod != null,
"A parser must be provided either via a constructor or consumer properties");
this.parser = SerializationUtils.propertyToMethodInvokingFunction(parserMethod, String.class,
getClass().getClassLoader());
}
}
@Override
public T deserialize(String topic, byte[] data) {
return deserialize(topic, null, data);
}
@Override
public T deserialize(String topic, @Nullable Headers headers, byte[] data) {
return this.parser.apply(data == null ? null : new String(data, this.charset), headers);
}
@Override
public T deserialize(String topic, Headers headers, ByteBuffer data) {
String value = deserialize(data);
return this.parser.apply(value, headers);
}
private @Nullable String deserialize(@Nullable ByteBuffer data) {
if (data == null) {
return null;
}
if (data.hasArray()) {
return new String(data.array(), data.position() + data.arrayOffset(), data.remaining(), this.charset);
}
return new String(Utils.toArray(data), this.charset);
}
|
/**
* Set a charset to use when converting byte[] to {@link String}. Default UTF-8.
* @param charset the charset.
*/
public void setCharset(Charset charset) {
Assert.notNull(charset, "'charset' cannot be null");
this.charset = charset;
}
/**
* Get the configured charset.
* @return the charset.
*/
public Charset getCharset() {
return this.charset;
}
/**
* Get the configured parser function.
* @return the function.
*/
public BiFunction<String, Headers, T> getParser() {
return this.parser;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\ParseStringDeserializer.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public de.metas.shipper.gateway.go.model.I_GO_DeliveryOrder getGO_DeliveryOrder() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_GO_DeliveryOrder_ID, de.metas.shipper.gateway.go.model.I_GO_DeliveryOrder.class);
}
@Override
public void setGO_DeliveryOrder(de.metas.shipper.gateway.go.model.I_GO_DeliveryOrder GO_DeliveryOrder)
{
set_ValueFromPO(COLUMNNAME_GO_DeliveryOrder_ID, de.metas.shipper.gateway.go.model.I_GO_DeliveryOrder.class, GO_DeliveryOrder);
}
/** Set GO Delivery Order.
@param GO_DeliveryOrder_ID GO Delivery Order */
@Override
public void setGO_DeliveryOrder_ID (int GO_DeliveryOrder_ID)
{
if (GO_DeliveryOrder_ID < 1)
set_ValueNoCheck (COLUMNNAME_GO_DeliveryOrder_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GO_DeliveryOrder_ID, Integer.valueOf(GO_DeliveryOrder_ID));
}
/** Get GO Delivery Order.
@return GO Delivery Order */
@Override
public int getGO_DeliveryOrder_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GO_DeliveryOrder_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set GO Delivery Order Package.
@param GO_DeliveryOrder_Package_ID GO Delivery Order Package */
@Override
public void setGO_DeliveryOrder_Package_ID (int GO_DeliveryOrder_Package_ID)
{
if (GO_DeliveryOrder_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_GO_DeliveryOrder_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GO_DeliveryOrder_Package_ID, Integer.valueOf(GO_DeliveryOrder_Package_ID));
}
/** Get GO Delivery Order Package.
@return GO Delivery Order Package */
@Override
public int getGO_DeliveryOrder_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GO_DeliveryOrder_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
@Override
public org.compiere.model.I_M_Package getM_Package() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
}
@Override
public void setM_Package(org.compiere.model.I_M_Package M_Package)
{
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
}
/** Set Packstück.
@param M_Package_ID
Shipment Package
*/
@Override
public void setM_Package_ID (int M_Package_ID)
{
if (M_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID));
}
/** Get Packstück.
@return Shipment Package
*/
@Override
public int getM_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_DeliveryOrder_Package.java
| 1
|
请完成以下Java代码
|
public class XMLHandlerFactory implements IXMLHandlerFactory
{
/**
* Map: Bean Class -> Converter Class
*
* e.g. I_AD_Migration -> MigrationHandler
*/
private final Map<Class<?>, Class<?>> handlerByBeanClass = new HashMap<Class<?>, Class<?>>();
/**
* Map: NodeName -> Bean Class
*
* e.g. "Migration" -> I_AD_Migration
*/
private final Map<String, Class<?>> beanClassesByNodeName = new HashMap<String, Class<?>>();
public XMLHandlerFactory()
{
// Register defaults
registerHandler(MigrationHandler.NODENAME, I_AD_Migration.class, MigrationHandler.class);
registerHandler(MigrationStepHandler.NODENAME, I_AD_MigrationStep.class, MigrationStepHandler.class);
registerHandler(MigrationDataHandler.NODENAME, I_AD_MigrationData.class, MigrationDataHandler.class);
}
@Override
public <T> void registerHandler(String nodeName, Class<T> beanClass, Class<? extends IXMLHandler<T>> converterClass)
{
beanClassesByNodeName.put(nodeName, beanClass);
handlerByBeanClass.put(beanClass, converterClass);
}
@Override
public <T> Class<T> getBeanClassByNodeName(String nodeName)
{
@SuppressWarnings("unchecked")
final Class<T> beanClass = (Class<T>)beanClassesByNodeName.get(nodeName);
return beanClass;
}
@Override
public <T> IXMLHandler<T> getHandlerByNodeName(String nodeName)
{
final Class<T> beanClass = getBeanClassByNodeName(nodeName);
|
return getHandler(beanClass);
}
@Override
public <T> IXMLHandler<T> getHandler(Class<T> clazz)
{
final Class<?> converterClass = handlerByBeanClass.get(clazz);
try
{
@SuppressWarnings("unchecked")
IXMLHandler<T> converter = (IXMLHandler<T>)converterClass.newInstance();
return converter;
}
catch (Exception e)
{
throw new AdempiereException(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\impl\XMLHandlerFactory.java
| 1
|
请完成以下Java代码
|
public int addArchivePartToPDF(@NonNull final PrintingData data, @NonNull final PrintingSegment segment)
{
try
{
return addArchivePartToPDF0(data, segment);
}
catch (final Exception e)
{
throw new PrintingQueueAggregationException(data.getPrintingQueueItemId().getRepoId(), e);
}
}
private int addArchivePartToPDF0(@NonNull final PrintingData data, @NonNull final PrintingSegment segment) throws IOException
{
if (!data.hasData())
{
logger.info("PrintingData {} does not contain any data; -> returning", data);
return 0;
}
logger.debug("Adding data={}; segment={}", data, segment);
int pagesAdded = 0;
for (int i = 0; i < segment.getCopies(); i++)
{
final PdfReader reader = new PdfReader(data.getData());
final int archivePageNums = reader.getNumberOfPages();
int pageFrom = segment.getPageFrom();
if (pageFrom <= 0)
{
// First page is 1 - See com.lowagie.text.pdf.PdfWriter.getImportedPage
pageFrom = 1;
}
int pageTo = segment.getPageTo();
if (pageTo > archivePageNums)
{
// shall not happen at this point
logger.debug("Page to ({}) is greater then number of pages. Considering number of pages: {}", new Object[] { pageTo, archivePageNums });
pageTo = archivePageNums;
}
if (pageFrom > pageTo)
{
// shall not happen at this point
logger.warn("Page from ({}) is greater then Page to ({}). Skipping: {}", pageFrom, pageTo, segment);
return 0;
}
|
logger.debug("PageFrom={}, PageTo={}, NumberOfPages={}", pageFrom, pageTo, archivePageNums);
for (int page = pageFrom; page <= pageTo; page++)
{
try
{
pdfCopy.addPage(pdfCopy.getImportedPage(reader, page));
}
catch (final BadPdfFormatException e)
{
throw new AdempiereException("@Invalid@ " + segment + " (Page: " + page + ")", e);
}
pagesAdded++;
}
pdfCopy.freeReader(reader);
reader.close();
}
logger.debug("Added {} pages", pagesAdded);
return pagesAdded;
}
@Override
public void close()
{
document.close();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataToPDFWriter.java
| 1
|
请完成以下Java代码
|
public void setLeichMehl_PluFile_Config_ID (final int LeichMehl_PluFile_Config_ID)
{
if (LeichMehl_PluFile_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_Config_ID, LeichMehl_PluFile_Config_ID);
}
@Override
public int getLeichMehl_PluFile_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_Config_ID);
}
@Override
public void setReplacement (final java.lang.String Replacement)
{
set_Value (COLUMNNAME_Replacement, Replacement);
}
@Override
public java.lang.String getReplacement()
{
return get_ValueAsString(COLUMNNAME_Replacement);
}
/**
* ReplacementSource AD_Reference_ID=541598
* Reference name: ReplacementSourceList
*/
public static final int REPLACEMENTSOURCE_AD_Reference_ID=541598;
/** Product = P */
public static final String REPLACEMENTSOURCE_Product = "P";
/** PPOrder = PP */
public static final String REPLACEMENTSOURCE_PPOrder = "PP";
/** CustomProcessResult = CP */
public static final String REPLACEMENTSOURCE_CustomProcessResult = "CP";
@Override
public void setReplacementSource (final java.lang.String ReplacementSource)
{
set_Value (COLUMNNAME_ReplacementSource, ReplacementSource);
}
@Override
public java.lang.String getReplacementSource()
{
return get_ValueAsString(COLUMNNAME_ReplacementSource);
}
@Override
public void setReplaceRegExp (final @Nullable java.lang.String ReplaceRegExp)
{
set_Value (COLUMNNAME_ReplaceRegExp, ReplaceRegExp);
}
@Override
public java.lang.String getReplaceRegExp()
{
return get_ValueAsString(COLUMNNAME_ReplaceRegExp);
}
@Override
public void setTargetFieldName (final java.lang.String TargetFieldName)
{
set_Value (COLUMNNAME_TargetFieldName, TargetFieldName);
}
@Override
public java.lang.String getTargetFieldName()
|
{
return get_ValueAsString(COLUMNNAME_TargetFieldName);
}
/**
* TargetFieldType AD_Reference_ID=541611
* Reference name: AttributeTypeList
*/
public static final int TARGETFIELDTYPE_AD_Reference_ID=541611;
/** textArea = textArea */
public static final String TARGETFIELDTYPE_TextArea = "textArea";
/** EAN13 = EAN13 */
public static final String TARGETFIELDTYPE_EAN13 = "EAN13";
/** EAN128 = EAN128 */
public static final String TARGETFIELDTYPE_EAN128 = "EAN128";
/** numberField = numberField */
public static final String TARGETFIELDTYPE_NumberField = "numberField";
/** date = date */
public static final String TARGETFIELDTYPE_Date = "date";
/** unitChar = unitChar */
public static final String TARGETFIELDTYPE_UnitChar = "unitChar";
/** graphic = graphic */
public static final String TARGETFIELDTYPE_Graphic = "graphic";
@Override
public void setTargetFieldType (final java.lang.String TargetFieldType)
{
set_Value (COLUMNNAME_TargetFieldType, TargetFieldType);
}
@Override
public java.lang.String getTargetFieldType()
{
return get_ValueAsString(COLUMNNAME_TargetFieldType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_Config.java
| 1
|
请完成以下Java代码
|
public class SponsorNoObject
{
private String sponsorNo;
private String name;
private int sponsorID;
//
private String stringRepresentation = null;
public SponsorNoObject(int sponsorID, String sponsorNo, String name)
{
super();
this.sponsorID = sponsorID;
this.sponsorNo = sponsorNo;
this.name = name;
}
public int getSponsorID()
{
return sponsorID;
}
public void setSponsorID(int sponsorID)
{
this.sponsorID = sponsorID;
}
public String getSponsorNo()
{
return sponsorNo;
}
public void setSponsorNo(String sponsorNo)
{
this.sponsorNo = sponsorNo;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getStringRepresentation()
{
return stringRepresentation;
}
public void setStringRepresentation(String stringRepresentation)
|
{
this.stringRepresentation = stringRepresentation;
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof SponsorNoObject))
return false;
if (this == obj)
return true;
//
SponsorNoObject sno = (SponsorNoObject)obj;
return this.sponsorNo == sno.sponsorNo;
}
@Override
public String toString()
{
String str = getStringRepresentation();
if (str != null)
return str;
return sponsorNo + ", " + name;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\SponsorNoObject.java
| 1
|
请完成以下Java代码
|
public class GetExecutionVariablesCmd implements Command<VariableMap>, Serializable {
private static final long serialVersionUID = 1L;
protected String executionId;
protected Collection<String> variableNames;
protected boolean isLocal;
protected boolean deserializeValues;
public GetExecutionVariablesCmd(String executionId, Collection<String> variableNames, boolean isLocal, boolean deserializeValues) {
this.executionId = executionId;
this.variableNames = variableNames;
this.isLocal = isLocal;
this.deserializeValues = deserializeValues;
}
public VariableMap execute(CommandContext commandContext) {
ensureNotNull("executionId", executionId);
ExecutionEntity execution = commandContext
.getExecutionManager()
|
.findExecutionById(executionId);
ensureNotNull("execution " + executionId + " doesn't exist", "execution", execution);
checkGetExecutionVariables(execution, commandContext);
VariableMapImpl executionVariables = new VariableMapImpl();
// collect variables from execution
execution.collectVariables(executionVariables, variableNames, isLocal, deserializeValues);
return executionVariables;
}
protected void checkGetExecutionVariables(ExecutionEntity execution, CommandContext commandContext) {
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkReadProcessInstanceVariable(execution);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetExecutionVariablesCmd.java
| 1
|
请完成以下Java代码
|
private static Font getCellStyle(Cell cell) throws DocumentException, IOException {
Font font = new Font();
CellStyle cellStyle = cell.getCellStyle();
org.apache.poi.ss.usermodel.Font cellFont = cell.getSheet()
.getWorkbook()
.getFontAt(cellStyle.getFontIndexAsInt());
short fontColorIndex = cellFont.getColor();
if (fontColorIndex != IndexedColors.AUTOMATIC.getIndex() && cellFont instanceof XSSFFont) {
XSSFColor fontColor = ((XSSFFont) cellFont).getXSSFColor();
if (fontColor != null) {
byte[] rgb = fontColor.getRGB();
if (rgb != null && rgb.length == 3) {
font.setColor(new BaseColor(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
}
}
}
if (cellFont.getItalic()) {
font.setStyle(Font.ITALIC);
}
if (cellFont.getStrikeout()) {
font.setStyle(Font.STRIKETHRU);
}
if (cellFont.getUnderline() == 1) {
font.setStyle(Font.UNDERLINE);
}
short fontSize = cellFont.getFontHeightInPoints();
font.setSize(fontSize);
if (cellFont.getBold()) {
font.setStyle(Font.BOLD);
|
}
String fontName = cellFont.getFontName();
if (FontFactory.isRegistered(fontName)) {
font.setFamily(fontName); // Use extracted font family if supported by iText
} else {
logger.warn("Unsupported font type: {}", fontName);
// - Use a fallback font (e.g., Helvetica)
font.setFamily("Helvetica");
}
return font;
}
public static void main(String[] args) throws DocumentException, IOException {
String excelFilePath = "src/main/resources/excelsample.xlsx";
String pdfFilePath = "src/main/resources/pdfsample.pdf";
convertExcelToPDF(excelFilePath, pdfFilePath);
}
}
|
repos\tutorials-master\text-processing-libraries-modules\pdf-2\src\main\java\com\baeldung\exceltopdf\ExcelToPDFConverter.java
| 1
|
请完成以下Java代码
|
public class SerializableDataFormat implements DataFormat {
private static final SerializableLogger LOG = ExternalTaskClientLogger.SERIALIZABLE_FORMAT_LOGGER;
protected String name;
public SerializableDataFormat(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean canMap(Object value) {
return value instanceof Serializable;
}
public String writeValue(Object value) {
ByteArrayOutputStream baos = null;
ObjectOutputStream ois = null;
try {
baos = new ByteArrayOutputStream();
ois = new ObjectOutputStream(baos);
ois.writeObject(value);
byte[] deserializedObjectByteArray = baos.toByteArray();
Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(deserializedObjectByteArray);
}
catch (IOException e) {
throw LOG.unableToWriteValue(value, e);
}
finally {
IoUtil.closeSilently(ois);
IoUtil.closeSilently(baos);
}
}
|
public <T> T readValue(String value, String typeIdentifier) {
return readValue(value);
}
public <T> T readValue(String value, Class<T> cls) {
return readValue(value);
}
@SuppressWarnings("unchecked")
protected <T> T readValue(String value) {
Decoder decoder = Base64.getDecoder();
byte[] base64DecodedSerializedValue = decoder.decode(value);
InputStream is = null;
ObjectInputStream ois = null;
try {
is = new ByteArrayInputStream(base64DecodedSerializedValue);
ois = new ObjectInputStream(is);
return (T) ois.readObject();
}
catch (ClassNotFoundException e) {
throw LOG.classNotFound(e);
}
catch (IOException e) {
throw LOG.unableToReadValue(value, e);
}
finally {
IoUtil.closeSilently(ois);
IoUtil.closeSilently(is);
}
}
public String getCanonicalTypeName(Object value) {
return value.getClass().getName();
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\serializable\SerializableDataFormat.java
| 1
|
请完成以下Java代码
|
public void setMTree(MTree tree)
{
m_MTree = tree;
}
@Override
public MTreeNode getRoot()
{
return (MTreeNode)super.getRoot();
}
public boolean saveChildren(MTreeNode parent)
{
return saveChildren(parent, parent.getChildrenList());
}
public boolean saveChildren(MTreeNode parent, List<MTreeNode> children)
{
try
{
m_MTree.updateNodeChildren(parent, children);
}
catch (Exception e)
{
ADialog.error(0, null, "Error", e.getLocalizedMessage());
|
log.error(e.getLocalizedMessage(), e);
return false;
}
return true;
}
// metas: begin
public void filterIds(final List<Integer> ids)
{
Check.assumeNotNull(ids, "Param 'ids' is not null");
Services.get(IADTreeBL.class).filterIds(getRoot(), ids);
reload();
}
// metas: end
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\AdempiereTreeModel.java
| 1
|
请完成以下Java代码
|
private PerformanceMonitoringService performanceMonitoringService()
{
PerformanceMonitoringService performanceMonitoringService = _performanceMonitoringService;
if (performanceMonitoringService == null || performanceMonitoringService instanceof NoopPerformanceMonitoringService)
{
performanceMonitoringService = _performanceMonitoringService = SpringContextHolder.instance.getBeanOr(
PerformanceMonitoringService.class,
NoopPerformanceMonitoringService.INSTANCE);
}
return performanceMonitoringService;
}
//
//
//
public boolean isDeveloperMode()
{
return developerModeBL().isEnabled();
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue, final int ad_client_id, final int ad_org_id)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue, ad_client_id, ad_org_id);
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue);
}
public boolean isChangeLogEnabled()
|
{
return sessionBL().isChangeLogEnabled();
}
public String getInsertChangeLogType(final int adClientId)
{
return sysConfigBL().getValue("SYSTEM_INSERT_CHANGELOG", "N", adClientId);
}
public void saveChangeLogs(final List<ChangeLogRecord> changeLogRecords)
{
sessionDAO().saveChangeLogs(changeLogRecords);
}
public void logMigration(final MFSession session, final PO po, final POInfo poInfo, final String actionType)
{
migrationLogger().logMigration(session, po, poInfo, actionType);
}
public void fireDocumentNoChange(final PO po, final String value)
{
documentNoBL().fireDocumentNoChange(po, value); // task 09776
}
public ADRefList getRefListById(@NonNull final ReferenceId referenceId)
{
return adReferenceService().getRefListById(referenceId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POServicesFacade.java
| 1
|
请完成以下Java代码
|
public class Artist implements Serializable {
private String name;
private String country;
private String genre;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
|
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((genre == null) ? 0 : genre.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Artist other = (Artist) obj;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (genre == null) {
if (other.genre != null)
return false;
} else if (!genre.equals(other.genre))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-libraries\src\main\java\com\baeldung\hibernate\types\Artist.java
| 1
|
请完成以下Java代码
|
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.passwordEncoder = () -> passwordEncoder;
this.userNotFoundEncodedPassword = null;
}
protected PasswordEncoder getPasswordEncoder() {
return this.passwordEncoder.get();
}
protected UserDetailsService getUserDetailsService() {
return this.userDetailsService;
}
public void setUserDetailsPasswordService(UserDetailsPasswordService userDetailsPasswordService) {
|
Assert.notNull(userDetailsPasswordService, "userDetailsPasswordService cannot be null");
this.userDetailsPasswordService = userDetailsPasswordService;
}
/**
* Sets the {@link CompromisedPasswordChecker} to be used before creating a successful
* authentication. Defaults to {@code null}.
* @param compromisedPasswordChecker the {@link CompromisedPasswordChecker} to use
* @since 6.3
*/
public void setCompromisedPasswordChecker(CompromisedPasswordChecker compromisedPasswordChecker) {
Assert.notNull(compromisedPasswordChecker, "compromisedPasswordChecker cannot be null");
this.compromisedPasswordChecker = compromisedPasswordChecker;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\dao\DaoAuthenticationProvider.java
| 1
|
请完成以下Java代码
|
public class RabbitChannelMessageListenerAdapter implements MessageListener {
protected EventRegistry eventRegistry;
protected InboundChannelModel inboundChannelModel;
public RabbitChannelMessageListenerAdapter(EventRegistry eventRegistry, InboundChannelModel inboundChannelModel) {
this.eventRegistry = eventRegistry;
this.inboundChannelModel = inboundChannelModel;
}
@Override
public void onMessage(Message message) {
eventRegistry.eventReceived(inboundChannelModel, new RabbitInboundEvent(message));
}
public EventRegistry getEventRegistry() {
|
return eventRegistry;
}
public void setEventRegistry(EventRegistry eventRegistry) {
this.eventRegistry = eventRegistry;
}
public InboundChannelModel getInboundChannelModel() {
return inboundChannelModel;
}
public void setInboundChannelModel(InboundChannelModel inboundChannelModel) {
this.inboundChannelModel = inboundChannelModel;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\rabbit\RabbitChannelMessageListenerAdapter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public GetArticlesResult findByFilters(String tag,
String author,
String favorited,
Integer limit,
Integer offset) {
return bus.executeQuery(GetArticles.builder()
.tag(tag)
.author(author)
.favorited(favorited)
.limit(limit)
.offset(offset)
.build());
}
@Override
public CreateArticleResult create(@Valid CreateArticle command) {
return bus.executeCommand(command);
}
@Override
public GetFeedResult feed(Integer limit, Integer offset) {
return bus.executeQuery(new GetFeed(limit, offset));
}
@Override
public GetArticleResult findBySlug(String slug) {
return bus.executeQuery(new GetArticle(slug));
}
@Override
public UpdateArticleResult updateBySlug(String slug, @Valid UpdateArticle command) {
return bus.executeCommand(command.withSlug(slug));
}
@Override
public void deleteBySlug(String slug) {
bus.executeCommand(new DeleteArticle(slug));
|
}
@Override
public FavoriteArticleResult favorite(String slug) {
return bus.executeCommand(new FavoriteArticle(slug));
}
@Override
public UnfavoriteArticleResult unfavorite(String slug) {
return bus.executeCommand(new UnfavoriteArticle(slug));
}
@Override
public GetCommentsResult findAllComments(String slug) {
return bus.executeQuery(new GetComments(slug));
}
@Override
public AddCommentResult addComment(String slug, @Valid AddComment command) {
return bus.executeCommand(command.withSlug(slug));
}
@Override
public void deleteComment(String slug, Long id) {
bus.executeCommand(new DeleteComment(slug, id));
}
}
|
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\web\ArticleController.java
| 2
|
请完成以下Java代码
|
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
|
+ ", revision=" + revision
+ ", name=" + name
+ ", description=" + description
+ ", type=" + type
+ ", taskId=" + taskId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ ", url=" + url
+ ", contentId=" + contentId
+ ", content=" + content
+ ", tenantId=" + tenantId
+ ", createTime=" + createTime
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AttachmentEntity.java
| 1
|
请完成以下Java代码
|
public void setModels(List<CarModel> models) {
this.models = models;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((models == null) ? 0 : models.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
|
return false;
CarMaker other = (CarMaker) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (models == null) {
if (other.models != null)
return false;
} else if (!models.equals(other.models))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarMaker.java
| 1
|
请完成以下Java代码
|
public class Main {
static String filePath = Objects.requireNonNull(Main.class.getClassLoader().getResource("myFile.gz")).getFile();
public static void main(String[] args) throws IOException {
// Test readGZipFile method
List<String> fileContents = readGZipFile(filePath);
System.out.println("Contents of GZIP file:");
fileContents.forEach(System.out::println);
// Test findInZipFile method
String searchTerm = "Line 1 content";
List<String> foundLines = findInZipFile(filePath, searchTerm);
System.out.println("Lines containing '" + searchTerm + "' in GZIP file:");
foundLines.forEach(System.out::println);
// Test useContentsOfZipFile method
System.out.println("Using contents of GZIP file with consumer:");
useContentsOfZipFile(filePath, linesStream -> {
linesStream.filter(line -> line.length() > 10).forEach(System.out::println);
});
}
public static List<String> readGZipFile(String filePath) throws IOException {
List<String> lines = new ArrayList<>();
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
}
|
return lines;
}
public static List<String> findInZipFile(String filePath, String toFind) throws IOException {
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
return bufferedReader.lines().filter(line -> line.contains(toFind)).collect(toList());
}
}
public static void useContentsOfZipFile(String filePath, Consumer<Stream<String>> consumer) throws IOException {
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
consumer.accept(bufferedReader.lines());
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\usinggzipInputstream\Main.java
| 1
|
请完成以下Java代码
|
public @Nullable String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) {
String actualToken = super.resolveCsrfTokenValue(request, csrfToken);
if (actualToken == null) {
return null;
}
return getTokenValue(actualToken, csrfToken.getToken());
}
private static @Nullable String getTokenValue(String actualToken, String token) {
byte[] actualBytes;
try {
actualBytes = Base64.getUrlDecoder().decode(actualToken);
}
catch (Exception ex) {
logger.trace(LogMessage.format("Not returning the CSRF token since it's not Base64-encoded"), ex);
return null;
}
byte[] tokenBytes = Utf8.encode(token);
int tokenSize = tokenBytes.length;
if (actualBytes.length != tokenSize * 2) {
logger.trace(LogMessage.format(
"Not returning the CSRF token since its Base64-decoded length (%d) is not equal to (%d)",
actualBytes.length, tokenSize * 2));
return null;
}
// extract token and random bytes
byte[] xoredCsrf = new byte[tokenSize];
byte[] randomBytes = new byte[tokenSize];
System.arraycopy(actualBytes, 0, randomBytes, 0, tokenSize);
System.arraycopy(actualBytes, tokenSize, xoredCsrf, 0, tokenSize);
byte[] csrfBytes = xorCsrf(randomBytes, xoredCsrf);
return Utf8.decode(csrfBytes);
}
private static String createXoredCsrfToken(SecureRandom secureRandom, String token) {
byte[] tokenBytes = Utf8.encode(token);
byte[] randomBytes = new byte[tokenBytes.length];
secureRandom.nextBytes(randomBytes);
byte[] xoredBytes = xorCsrf(randomBytes, tokenBytes);
byte[] combinedBytes = new byte[tokenBytes.length + randomBytes.length];
System.arraycopy(randomBytes, 0, combinedBytes, 0, randomBytes.length);
System.arraycopy(xoredBytes, 0, combinedBytes, randomBytes.length, xoredBytes.length);
return Base64.getUrlEncoder().encodeToString(combinedBytes);
}
private static byte[] xorCsrf(byte[] randomBytes, byte[] csrfBytes) {
Assert.isTrue(randomBytes.length == csrfBytes.length, "arrays must be equal length");
int len = csrfBytes.length;
byte[] xoredCsrf = new byte[len];
System.arraycopy(csrfBytes, 0, xoredCsrf, 0, len);
for (int i = 0; i < len; i++) {
xoredCsrf[i] ^= randomBytes[i];
|
}
return xoredCsrf;
}
private static final class CachedCsrfTokenSupplier implements Supplier<CsrfToken> {
private final Supplier<CsrfToken> delegate;
private @Nullable CsrfToken csrfToken;
private CachedCsrfTokenSupplier(Supplier<CsrfToken> delegate) {
this.delegate = delegate;
}
@Override
public CsrfToken get() {
if (this.csrfToken == null) {
this.csrfToken = this.delegate.get();
}
return this.csrfToken;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\XorCsrfTokenRequestAttributeHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ConnectionInfo parseXForwardedInfo(ConnectionInfo connectionInfo, HttpRequest request) {
String ipHeader = request.headers().get(X_FORWARDED_IP_HEADER);
if (ipHeader != null) {
connectionInfo = connectionInfo.withRemoteAddress(
AddressUtils.parseAddress(ipHeader.split(",", 2)[0], connectionInfo.getRemoteAddress().getPort()));
}
String protoHeader = request.headers().get(X_FORWARDED_PROTO_HEADER);
if (protoHeader != null) {
connectionInfo = connectionInfo.withScheme(protoHeader.split(",", 2)[0].trim());
}
String hostHeader = request.headers().get(X_FORWARDED_HOST_HEADER);
if (hostHeader != null) {
connectionInfo = connectionInfo
.withHostAddress(AddressUtils.parseAddress(hostHeader.split(",", 2)[0].trim(),
getDefaultHostPort(connectionInfo.getScheme()), DEFAULT_FORWARDED_HEADER_VALIDATION));
}
String portHeader = request.headers().get(X_FORWARDED_PORT_HEADER);
|
if (portHeader != null && !portHeader.isEmpty()) {
String portStr = portHeader.split(",", 2)[0].trim();
if (portStr.chars().allMatch(Character::isDigit)) {
int port = Integer.parseInt(portStr);
connectionInfo = connectionInfo.withHostAddress(
AddressUtils.createUnresolved(connectionInfo.getHostAddress().getHostString(), port),
connectionInfo.getHostName(), port);
}
else if (DEFAULT_FORWARDED_HEADER_VALIDATION) {
throw new IllegalArgumentException("Failed to parse a port from " + portHeader);
}
}
return connectionInfo;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\DefaultNettyHttpForwardedHeaderHandler.java
| 2
|
请完成以下Spring Boot application配置
|
spring.ai.vectorstore.redis.uri=redis://127.0.0.1:6379
spring.ai.vectorstore.redis.index=default-index
spring.ai.vectorstore.redis.prefix=default
# API key if needed, e.g. OpenAI
spri
|
ng.ai.openai.api.key=<api-key>
spring.main.allow-bean-definition-overriding=true
|
repos\springboot-demo-master\RedisVectorStore\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final PMMBalanceSegment other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(C_BPartner_ID, other.C_BPartner_ID)
.append(M_Product_ID, other.M_Product_ID)
.append(M_AttributeSetInstance_ID, other.M_AttributeSetInstance_ID)
// .append(M_HU_PI_Item_Product_ID, other.M_HU_PI_Item_Product_ID)
.append(C_Flatrate_DataEntry_ID, other.C_Flatrate_DataEntry_ID)
.isEqual();
}
@Override
public int hashCode()
{
if (_hashCode == null)
{
_hashCode = new HashcodeBuilder()
.append(C_BPartner_ID)
.append(M_Product_ID)
.append(M_AttributeSetInstance_ID)
// .append(M_HU_PI_Item_Product_ID)
.append(C_Flatrate_DataEntry_ID)
.toHashcode();
}
return _hashCode;
}
public int getC_BPartner_ID()
{
return C_BPartner_ID;
}
public int getM_Product_ID()
{
return M_Product_ID;
}
public int getM_AttributeSetInstance_ID()
{
return M_AttributeSetInstance_ID;
}
// public int getM_HU_PI_Item_Product_ID()
// {
// return M_HU_PI_Item_Product_ID;
// }
public int getC_Flatrate_DataEntry_ID()
{
return C_Flatrate_DataEntry_ID;
}
public static final class Builder
{
private Integer C_BPartner_ID;
private Integer M_Product_ID;
private int M_AttributeSetInstance_ID = 0;
// private Integer M_HU_PI_Item_Product_ID;
private int C_Flatrate_DataEntry_ID = -1;
|
private Builder()
{
super();
}
public PMMBalanceSegment build()
{
return new PMMBalanceSegment(this);
}
public Builder setC_BPartner_ID(final int C_BPartner_ID)
{
this.C_BPartner_ID = C_BPartner_ID;
return this;
}
public Builder setM_Product_ID(final int M_Product_ID)
{
this.M_Product_ID = M_Product_ID;
return this;
}
public Builder setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
this.M_AttributeSetInstance_ID = M_AttributeSetInstance_ID;
return this;
}
// public Builder setM_HU_PI_Item_Product_ID(final int M_HU_PI_Item_Product_ID)
// {
// this.M_HU_PI_Item_Product_ID = M_HU_PI_Item_Product_ID;
// return this;
// }
public Builder setC_Flatrate_DataEntry_ID(final int C_Flatrate_DataEntry_ID)
{
this.C_Flatrate_DataEntry_ID = C_Flatrate_DataEntry_ID;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\balance\PMMBalanceSegment.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult create(@RequestBody SmsHomeAdvertise advertise) {
int count = advertiseService.create(advertise);
if (count > 0)
return CommonResult.success(count);
return CommonResult.failed();
}
@ApiOperation("删除广告")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@RequestParam("ids") List<Long> ids) {
int count = advertiseService.delete(ids);
if (count > 0)
return CommonResult.success(count);
return CommonResult.failed();
}
@ApiOperation("修改上下线状态")
@RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateStatus(@PathVariable Long id, Integer status) {
int count = advertiseService.updateStatus(id, status);
if (count > 0)
return CommonResult.success(count);
return CommonResult.failed();
}
@ApiOperation("获取广告详情")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<SmsHomeAdvertise> getItem(@PathVariable Long id) {
SmsHomeAdvertise advertise = advertiseService.getItem(id);
return CommonResult.success(advertise);
}
@ApiOperation("修改广告")
|
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody SmsHomeAdvertise advertise) {
int count = advertiseService.update(id, advertise);
if (count > 0)
return CommonResult.success(count);
return CommonResult.failed();
}
@ApiOperation("分页查询广告")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<SmsHomeAdvertise>> list(@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "type", required = false) Integer type,
@RequestParam(value = "endTime", required = false) String endTime,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<SmsHomeAdvertise> advertiseList = advertiseService.list(name, type, endTime, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(advertiseList));
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsHomeAdvertiseController.java
| 2
|
请完成以下Java代码
|
public RuleChain findDefaultEntityByTenantId(UUID tenantId) {
return findRootRuleChainByTenantIdAndType(tenantId, RuleChainType.CORE);
}
@Override
public PageData<RuleChain> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findRuleChainsByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) {
return ruleChainRepository.findRuleChainsByTenantIdAndResource(tenantId.getId(), reference, PageRequest.of(0, limit));
}
@Override
|
public List<EntityInfo> findByResource(String reference, int limit) {
return ruleChainRepository.findRuleChainsByResource(reference, PageRequest.of(0, limit));
}
@Override
public List<RuleChainFields> findNextBatch(UUID id, int batchSize) {
return ruleChainRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.RULE_CHAIN;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\rule\JpaRuleChainDao.java
| 1
|
请完成以下Java代码
|
public class SameBehaviorInstructionValidator implements MigrationInstructionValidator {
public static final List<Set<Class<?>>> EQUIVALENT_BEHAVIORS =
new ArrayList<Set<Class<?>>>();
static {
EQUIVALENT_BEHAVIORS.add(CollectionUtil.<Class<?>>asHashSet(
CallActivityBehavior.class, CaseCallActivityBehavior.class
));
EQUIVALENT_BEHAVIORS.add(CollectionUtil.<Class<?>>asHashSet(
SubProcessActivityBehavior.class, EventSubProcessActivityBehavior.class
));
}
protected Map<Class<?>, Set<Class<?>>> equivalentBehaviors = new HashMap<Class<?>, Set<Class<?>>>();
public SameBehaviorInstructionValidator() {
this(EQUIVALENT_BEHAVIORS);
}
public SameBehaviorInstructionValidator(List<Set<Class<?>>> equivalentBehaviors) {
for (Set<Class<?>> equivalenceClass : equivalentBehaviors) {
for (Class<?> clazz : equivalenceClass) {
this.equivalentBehaviors.put(clazz, equivalenceClass);
}
}
}
public void validate(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) {
|
ActivityImpl sourceActivity = instruction.getSourceActivity();
ActivityImpl targetActivity = instruction.getTargetActivity();
Class<?> sourceBehaviorClass = sourceActivity.getActivityBehavior().getClass();
Class<?> targetBehaviorClass = targetActivity.getActivityBehavior().getClass();
if (!sameBehavior(sourceBehaviorClass, targetBehaviorClass)) {
report.addFailure("Activities have incompatible types "
+ "(" + sourceBehaviorClass.getSimpleName() + " is not compatible with " + targetBehaviorClass.getSimpleName() + ")");
}
}
protected boolean sameBehavior(Class<?> sourceBehavior, Class<?> targetBehavior) {
if (sourceBehavior == targetBehavior) {
return true;
}
else {
Set<Class<?>> equivalentBehaviors = this.equivalentBehaviors.get(sourceBehavior);
if (equivalentBehaviors != null) {
return equivalentBehaviors.contains(targetBehavior);
}
else {
return false;
}
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\SameBehaviorInstructionValidator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private boolean isEdqsType(TenantId tenantId, ObjectType objectType) {
if (objectType == null) {
return false;
}
if (!tenantId.isSysTenantId()) {
return ObjectType.edqsTypes.contains(objectType);
} else {
return ObjectType.edqsSystemTypes.contains(objectType);
}
}
private void broadcast(ToCoreEdqsMsg msg) {
clusterService.broadcastToCore(ToCoreNotificationMsg.newBuilder()
.setToEdqsCoreServiceMsg(ToEdqsCoreServiceMsg.newBuilder()
.setValue(ByteString.copyFrom(JacksonUtil.writeValueAsBytes(msg))))
.build());
}
@SneakyThrows
private EdqsSyncState getSyncState() {
EdqsSyncState state = attributesService.find(TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID, AttributeScope.SERVER_SCOPE, "edqsSyncState").get(30, TimeUnit.SECONDS)
.flatMap(KvEntry::getJsonValue)
.map(value -> JacksonUtil.fromString(value, EdqsSyncState.class))
.orElse(null);
log.info("EDQS sync state: {}", state);
return state;
}
|
@SneakyThrows
private void saveSyncState(EdqsSyncStatus status) {
saveSyncState(status, null);
}
@SneakyThrows
private void saveSyncState(EdqsSyncStatus status, Set<ObjectType> objectTypes) {
EdqsSyncState state = new EdqsSyncState(status, objectTypes);
log.info("New EDQS sync state: {}", state);
attributesService.save(TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID, AttributeScope.SERVER_SCOPE, new BaseAttributeKvEntry(
new JsonDataEntry("edqsSyncState", JacksonUtil.toString(state)),
System.currentTimeMillis())).get(30, TimeUnit.SECONDS);
}
@PreDestroy
private void stop() {
executor.shutdown();
scheduler.shutdownNow();
eventsProducer.stop();
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edqs\DefaultEdqsService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
|
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java
| 2
|
请完成以下Java代码
|
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
|
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public File getMainDirectory() {
return mainDirectory;
}
public void setMainDirectory(File mainDirectory) {
this.mainDirectory = mainDirectory;
}
}
|
repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\bval\model\User.java
| 1
|
请完成以下Java代码
|
public static <T> List<List<T>> partition(Collection<T> values, int partitionSize) {
if (values == null) {
return null;
} else if (values.isEmpty()) {
return Collections.emptyList();
}
List<T> valuesList;
if (values instanceof List) {
valuesList = (List<T>) values;
} else {
valuesList = new ArrayList<>(values);
}
int valuesSize = values.size();
if (valuesSize <= partitionSize) {
return Collections.singletonList(valuesList);
}
List<List<T>> safeValuesList = new ArrayList<>();
consumePartitions(values, partitionSize, safeValuesList::add);
return safeValuesList;
}
public static <T> void consumePartitions(Collection<T> values, int partitionSize, Consumer<List<T>> partitionConsumer) {
int valuesSize = values.size();
List<T> valuesList;
if (values instanceof List) {
valuesList = (List<T>) values;
} else {
valuesList = new ArrayList<>(values);
}
if (valuesSize <= partitionSize) {
partitionConsumer.accept(valuesList);
|
} else {
for (int startIndex = 0; startIndex < valuesSize; startIndex += partitionSize) {
int endIndex = startIndex + partitionSize;
if (endIndex > valuesSize) {
endIndex = valuesSize; // endIndex in #subList is exclusive
}
List<T> subList = valuesList.subList(startIndex, endIndex);
partitionConsumer.accept(subList);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\util\CollectionUtil.java
| 1
|
请完成以下Java代码
|
public CommentEntity findCommentByProcessInstanceIdAndCommentId(String processInstanceId, String commentId) {
checkHistoryEnabled();
Map<String, String> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("id", commentId);
return (CommentEntity) getDbEntityManager().selectOne("selectCommentByProcessInstanceIdAndCommentId", parameters);
}
public DbOperation addRemovalTimeToCommentsByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("rootProcessInstanceId", rootProcessInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
return getDbEntityManager()
.updatePreserveOrder(CommentEntity.class, "updateCommentsByRootProcessInstanceId", parameters);
}
public DbOperation addRemovalTimeToCommentsByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
|
return getDbEntityManager()
.updatePreserveOrder(CommentEntity.class, "updateCommentsByProcessInstanceId", parameters);
}
public DbOperation deleteCommentsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(CommentEntity.class, "deleteCommentsByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentManager.java
| 1
|
请完成以下Java代码
|
public class X_C_BPartner_DocType extends org.compiere.model.PO implements I_C_BPartner_DocType, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 835197703L;
/** Standard Constructor */
public X_C_BPartner_DocType (final Properties ctx, final int C_BPartner_DocType_ID, @Nullable final String trxName)
{
super (ctx, C_BPartner_DocType_ID, trxName);
}
/** Load Constructor */
public X_C_BPartner_DocType (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BPartner_DocType_ID (final int C_BPartner_DocType_ID)
{
if (C_BPartner_DocType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_DocType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_DocType_ID, C_BPartner_DocType_ID);
}
@Override
public int getC_BPartner_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_DocType_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public I_C_BPartner_Report_Text getC_BPartner_Report_Text()
{
|
return get_ValueAsPO(COLUMNNAME_C_BPartner_Report_Text_ID, I_C_BPartner_Report_Text.class);
}
@Override
public void setC_BPartner_Report_Text(final I_C_BPartner_Report_Text C_BPartner_Report_Text)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_Report_Text_ID, I_C_BPartner_Report_Text.class, C_BPartner_Report_Text);
}
@Override
public void setC_BPartner_Report_Text_ID (final int C_BPartner_Report_Text_ID)
{
if (C_BPartner_Report_Text_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Report_Text_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Report_Text_ID, C_BPartner_Report_Text_ID);
}
@Override
public int getC_BPartner_Report_Text_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Report_Text_ID);
}
@Override
public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\partnerreporttext\model\X_C_BPartner_DocType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class QueryHelper
{
@NonNull
@VisibleForTesting
public static JsonQuery buildEqualsJsonQuery(@NonNull final String key, @NonNull final String value)
{
return JsonQuery.builder()
.field(key)
.queryType(QueryType.EQUALS)
.value(value)
.build();
}
@NonNull
public static MultiQueryRequest buildUpdatedAfterFilterQueryRequest(@NonNull final String updatedAfter)
{
return MultiQueryRequest.builder()
.filter(buildUpdatedAfterJsonQueries(updatedAfter))
.build();
}
@NonNull
public static MultiQueryRequest buildShopware6GetCustomersQueryRequest(@NonNull final String updatedAfter, final PageAndLimit pageAndLimitValues)
{
return MultiQueryRequest.builder()
.filter(buildUpdatedAfterJsonQueries(updatedAfter))
.page(pageAndLimitValues.getPageIndex())
.limit(pageAndLimitValues.getLimit())
.build();
}
@NonNull
public static MultiQueryRequest buildQueryParentProductRequest(@NonNull final String parentId)
{
return MultiQueryRequest.builder()
.filter(JsonQuery.builder()
.field(FIELD_PRODUCT_ID)
.queryType(QueryType.EQUALS)
.value(parentId)
|
.build())
.build();
}
@NonNull
@VisibleForTesting
public static JsonQuery buildUpdatedAfterJsonQueries(@NonNull final String updatedAfter)
{
final HashMap<String, String> parameters = new HashMap<>();
parameters.put(PARAMETERS_GTE, updatedAfter);
return JsonQuery.builder()
.queryType(QueryType.MULTI)
.operatorType(OperatorType.OR)
.jsonQuery(JsonQuery.builder()
.field(FIELD_UPDATED_AT)
.queryType(QueryType.RANGE)
.parameters(parameters)
.build())
.jsonQuery(JsonQuery.builder()
.field(FIELD_CREATED_AT)
.queryType(QueryType.RANGE)
.parameters(parameters)
.build())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\model\QueryHelper.java
| 2
|
请完成以下Java代码
|
public void setKeepResponseBodyDays (final int KeepResponseBodyDays)
{
set_Value (COLUMNNAME_KeepResponseBodyDays, KeepResponseBodyDays);
}
@Override
public int getKeepResponseBodyDays()
{
return get_ValueAsInt(COLUMNNAME_KeepResponseBodyDays);
}
@Override
public void setKeepResponseDays (final int KeepResponseDays)
{
set_Value (COLUMNNAME_KeepResponseDays, KeepResponseDays);
}
@Override
public int getKeepResponseDays()
{
return get_ValueAsInt(COLUMNNAME_KeepResponseDays);
}
/**
* Method AD_Reference_ID=541306
* Reference name: Http_Method
*/
public static final int METHOD_AD_Reference_ID=541306;
/** GET = GET */
public static final String METHOD_GET = "GET";
/** POST = POST */
public static final String METHOD_POST = "POST";
/** PUT = PUT */
public static final String METHOD_PUT = "PUT";
/** DELETE = DELETE */
public static final String METHOD_DELETE = "DELETE";
/** OPTIONS = OPTIONS */
public static final String METHOD_OPTIONS = "OPTIONS";
/** PATCH = PATCH */
public static final String METHOD_PATCH = "PATCH";
/** HEAD = HEAD */
public static final String METHOD_HEAD = "HEAD";
/** TRACE = TRACE */
public static final String METHOD_TRACE = "TRACE";
/** CONNECT = CONNECT */
public static final String METHOD_CONNECT = "CONNECT";
@Override
public void setMethod (final @Nullable java.lang.String Method)
{
set_Value (COLUMNNAME_Method, Method);
}
@Override
public java.lang.String getMethod()
{
return get_ValueAsString(COLUMNNAME_Method);
}
/**
* NotifyUserInCharge AD_Reference_ID=541315
* Reference name: NotifyItems
*/
public static final int NOTIFYUSERINCHARGE_AD_Reference_ID=541315;
/** Niemals = NEVER */
public static final String NOTIFYUSERINCHARGE_Niemals = "NEVER ";
/** Aufrufen mit Fehler = ONLY_ON_ERROR */
public static final String NOTIFYUSERINCHARGE_AufrufenMitFehler = "ONLY_ON_ERROR ";
/** Allen Aufrufen = ALWAYS */
|
public static final String NOTIFYUSERINCHARGE_AllenAufrufen = "ALWAYS ";
@Override
public void setNotifyUserInCharge (final @Nullable java.lang.String NotifyUserInCharge)
{
set_Value (COLUMNNAME_NotifyUserInCharge, NotifyUserInCharge);
}
@Override
public java.lang.String getNotifyUserInCharge()
{
return get_ValueAsString(COLUMNNAME_NotifyUserInCharge);
}
@Override
public void setPathPrefix (final @Nullable java.lang.String PathPrefix)
{
set_Value (COLUMNNAME_PathPrefix, PathPrefix);
}
@Override
public java.lang.String getPathPrefix()
{
return get_ValueAsString(COLUMNNAME_PathPrefix);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Audit_Config.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserGroupId implements RepoIdAware
{
@JsonCreator
public static UserGroupId ofRepoId(final int repoId)
{
return new UserGroupId(repoId);
}
public static UserGroupId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new UserGroupId(repoId) : null;
}
public static int toRepoId(final UserGroupId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(final UserGroupId id1, final UserGroupId id2)
{
return Objects.equals(id1, id2);
|
}
private final int repoId;
private UserGroupId(final int repoId)
{
this.repoId = Check.assumeGreaterOrEqualToZero(repoId, "AD_UserGroup_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserGroupId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DefaultDependencyMetadataProvider implements DependencyMetadataProvider {
@Override
@Cacheable(cacheNames = "initializr.dependency-metadata", key = "#p1")
public DependencyMetadata get(InitializrMetadata metadata, Version bootVersion) {
Map<String, Dependency> dependencies = new LinkedHashMap<>();
for (Dependency dependency : metadata.getDependencies().getAll()) {
if (dependency.match(bootVersion)) {
dependencies.put(dependency.getId(), dependency.resolve(bootVersion));
}
}
Map<String, Repository> repositories = new LinkedHashMap<>();
for (Dependency dependency : dependencies.values()) {
if (dependency.getRepository() != null) {
repositories.put(dependency.getRepository(),
metadata.getConfiguration().getEnv().getRepositories().get(dependency.getRepository()));
}
}
|
Map<String, BillOfMaterials> boms = new LinkedHashMap<>();
for (Dependency dependency : dependencies.values()) {
if (dependency.getBom() != null) {
boms.put(dependency.getBom(),
metadata.getConfiguration().getEnv().getBoms().get(dependency.getBom()).resolve(bootVersion));
}
}
// Each resolved bom may require additional repositories
for (BillOfMaterials bom : boms.values()) {
for (String id : bom.getRepositories()) {
repositories.put(id, metadata.getConfiguration().getEnv().getRepositories().get(id));
}
}
return new DependencyMetadata(bootVersion, dependencies, repositories, boms);
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\DefaultDependencyMetadataProvider.java
| 2
|
请完成以下Java代码
|
private static String clean(String s){
if(s==null) return null;
// 去除结尾控制符/空白(不影响中间合法空格)
return s.replaceAll("[\\p{Cntrl}]+","").trim();
}
/* -------- 若仍需要旧接口,可保留 (不建议再用于新前端) -------- */
@Deprecated
public static String desEncrypt(String data) throws Exception {
return decryptLegacyNoPadding(data);
}
/* 加密(若前端不再使用,可忽略;保留旧实现避免影响历史) */
@Deprecated
public static String encrypt(String data) throws Exception {
try{
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
int plaintextLength = dataBytes.length;
|
if (plaintextLength % blockSize != 0) {
plaintextLength += (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return Base64.encodeToString(encrypted);
}catch(Exception e){
throw new IllegalStateException("legacy encrypt error", e);
}
}
// public static void main(String[] args) throws Exception {
// // 前端 CBC/Pkcs7 密文测试
// String frontCipher = encrypt("sa"); // 仅验证管道是否可用(旧方式)
// System.out.println(resolvePassword(frontCipher));
// }
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\encryption\AesEncryptUtil.java
| 1
|
请完成以下Java代码
|
public String encrypt(String text) {
return new String(Base64.getEncoder().encode(encrypt(text.getBytes(this.charset))), this.defaultCharset);
}
@Override
public String decrypt(String encryptedText) {
if (this.privateKey == null) {
throw new IllegalStateException("Private key must be provided for decryption");
}
return new String(decrypt(Base64.getDecoder().decode(encryptedText.getBytes(this.defaultCharset))),
this.charset);
}
@Override
public byte[] encrypt(byte[] byteArray) {
return encrypt(byteArray, this.publicKey, this.algorithm);
}
@Override
public byte[] decrypt(byte[] encryptedByteArray) {
return decrypt(encryptedByteArray, this.privateKey, this.algorithm);
}
private static byte[] encrypt(byte[] text, PublicKey key, RsaAlgorithm alg) {
ByteArrayOutputStream output = new ByteArrayOutputStream(text.length);
try {
final Cipher cipher = Cipher.getInstance(alg.getJceName());
int limit = Math.min(text.length, alg.getMaxLength());
int pos = 0;
while (pos < text.length) {
cipher.init(Cipher.ENCRYPT_MODE, key);
cipher.update(text, pos, limit);
pos += limit;
limit = Math.min(text.length - pos, alg.getMaxLength());
byte[] buffer = cipher.doFinal();
output.write(buffer, 0, buffer.length);
}
return output.toByteArray();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
|
throw new IllegalStateException("Cannot encrypt", ex);
}
}
private static byte[] decrypt(byte[] text, @Nullable RSAPrivateKey key, RsaAlgorithm alg) {
ByteArrayOutputStream output = new ByteArrayOutputStream(text.length);
try {
final Cipher cipher = Cipher.getInstance(alg.getJceName());
int maxLength = getByteLength(key);
int pos = 0;
while (pos < text.length) {
int limit = Math.min(text.length - pos, maxLength);
cipher.init(Cipher.DECRYPT_MODE, key);
cipher.update(text, pos, limit);
pos += limit;
byte[] buffer = cipher.doFinal();
output.write(buffer, 0, buffer.length);
}
return output.toByteArray();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Cannot decrypt", ex);
}
}
// copied from sun.security.rsa.RSACore.getByteLength(java.math.BigInteger)
public static int getByteLength(@Nullable RSAKey key) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
int n = key.getModulus().bitLength();
return (n + 7) >> 3;
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\RsaRawEncryptor.java
| 1
|
请完成以下Java代码
|
public void setBackground (boolean error)
{
if (error)
setBackground(AdempierePLAF.getFieldBackground_Error());
else if (!isReadWrite())
setBackground(AdempierePLAF.getFieldBackground_Inactive());
else if (m_mandatory)
setBackground(AdempierePLAF.getFieldBackground_Mandatory());
else
setBackground(AdempierePLAF.getFieldBackground_Normal());
} // setBackground
/**
* Set Background
* @param bg
*/
@Override
public void setBackground (Color bg)
{
if (bg.equals(getBackground()))
return;
super.setBackground(bg);
} // setBackground
/**
* Set Editor to value
* @param value value of the editor
*/
@Override
public void setValue (Object value)
{
if (value == null)
setText("");
else
setText(value.toString());
} // setValue
/**
|
* Return Editor value
* @return current value
*/
@Override
public Object getValue()
{
return new String(super.getPassword());
} // getValue
/**
* Return Display Value
* @return displayed String value
*/
@Override
public String getDisplay()
{
return new String(super.getPassword());
} // getDisplay
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CPassword.java
| 1
|
请完成以下Java代码
|
public void setBankName (String BankName)
{
set_Value (COLUMNNAME_BankName, BankName);
}
/** Get Bank Name.
@return Bank Name */
public String getBankName ()
{
return (String)get_Value(COLUMNNAME_BankName);
}
/** Set Cheque No.
@param ChequeNo Cheque No */
public void setChequeNo (String ChequeNo)
{
set_Value (COLUMNNAME_ChequeNo, ChequeNo);
}
/** Get Cheque No.
@return Cheque No */
public String getChequeNo ()
{
return (String)get_Value(COLUMNNAME_ChequeNo);
}
/** Set Black List Cheque.
@param U_BlackListCheque_ID Black List Cheque */
|
public void setU_BlackListCheque_ID (int U_BlackListCheque_ID)
{
if (U_BlackListCheque_ID < 1)
set_ValueNoCheck (COLUMNNAME_U_BlackListCheque_ID, null);
else
set_ValueNoCheck (COLUMNNAME_U_BlackListCheque_ID, Integer.valueOf(U_BlackListCheque_ID));
}
/** Get Black List Cheque.
@return Black List Cheque */
public int getU_BlackListCheque_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_BlackListCheque_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_U_BlackListCheque.java
| 1
|
请完成以下Java代码
|
private void writeStackTrace(PrintWriter writer, ThreadInfo info, MonitorInfo[] lockedMonitors) {
int depth = 0;
for (StackTraceElement element : info.getStackTrace()) {
writeStackTraceElement(writer, element, info, lockedMonitorsForDepth(lockedMonitors, depth), depth == 0);
depth++;
}
}
private List<MonitorInfo> lockedMonitorsForDepth(MonitorInfo[] lockedMonitors, int depth) {
return Stream.of(lockedMonitors).filter((candidate) -> candidate.getLockedStackDepth() == depth).toList();
}
private void writeStackTraceElement(PrintWriter writer, StackTraceElement element, ThreadInfo info,
List<MonitorInfo> lockedMonitors, boolean firstElement) {
writer.printf("\tat %s%n", element.toString());
LockInfo lockInfo = info.getLockInfo();
if (firstElement && lockInfo != null) {
if (element.getClassName().equals(Object.class.getName()) && element.getMethodName().equals("wait")) {
writer.printf("\t- waiting on %s%n", format(lockInfo));
}
else {
String lockOwner = info.getLockOwnerName();
if (lockOwner != null) {
writer.printf("\t- waiting to lock %s owned by \"%s\" t@%d%n", format(lockInfo), lockOwner,
info.getLockOwnerId());
}
else {
writer.printf("\t- parking to wait for %s%n", format(lockInfo));
}
}
}
writeMonitors(writer, lockedMonitors);
}
private String format(LockInfo lockInfo) {
|
return String.format("<%x> (a %s)", lockInfo.getIdentityHashCode(), lockInfo.getClassName());
}
private void writeMonitors(PrintWriter writer, List<MonitorInfo> lockedMonitorsAtCurrentDepth) {
for (MonitorInfo lockedMonitor : lockedMonitorsAtCurrentDepth) {
writer.printf("\t- locked %s%n", format(lockedMonitor));
}
}
private void writeLockedOwnableSynchronizers(PrintWriter writer, ThreadInfo info) {
writer.println(" Locked ownable synchronizers:");
LockInfo[] lockedSynchronizers = info.getLockedSynchronizers();
if (lockedSynchronizers == null || lockedSynchronizers.length == 0) {
writer.println("\t- None");
}
else {
for (LockInfo lockedSynchronizer : lockedSynchronizers) {
writer.printf("\t- Locked %s%n", format(lockedSynchronizer));
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\PlainTextThreadDumpFormatter.java
| 1
|
请完成以下Java代码
|
public DataEntryRecord getById(@NonNull final DataEntryRecordId dataEntryRecordId)
{
final I_DataEntry_Record record = getRecordById(dataEntryRecordId);
return toDataEntryRecord(record);
}
private I_DataEntry_Record getRecordById(final DataEntryRecordId dataEntryRecordId)
{
return load(dataEntryRecordId, I_DataEntry_Record.class);
}
private DataEntryRecord toDataEntryRecord(@NonNull final I_DataEntry_Record record)
{
final String jsonString = record.getDataEntry_RecordData();
final List<DataEntryRecordField<?>> fields = jsonDataEntryRecordMapper.deserialize(jsonString);
return DataEntryRecord.builder()
.id(DataEntryRecordId.ofRepoId(record.getDataEntry_Record_ID()))
.dataEntrySubTabId(DataEntrySubTabId.ofRepoId(record.getDataEntry_SubTab_ID()))
.mainRecord(TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID()))
.fields(fields)
.build();
}
public DataEntryRecordId save(@NonNull final DataEntryRecord dataEntryRecord)
{
final I_DataEntry_Record dataRecord;
final DataEntryRecordId existingId = dataEntryRecord.getId().orElse(null);
if (existingId == null)
{
dataRecord = newInstance(I_DataEntry_Record.class);
}
else
{
dataRecord = getRecordById(existingId);
}
dataRecord.setAD_Table_ID(dataEntryRecord.getMainRecord().getAD_Table_ID());
dataRecord.setRecord_ID(dataEntryRecord.getMainRecord().getRecord_ID());
dataRecord.setDataEntry_SubTab_ID(dataEntryRecord.getDataEntrySubTabId().getRepoId());
dataRecord.setIsActive(true);
final String jsonString = jsonDataEntryRecordMapper.serialize(dataEntryRecord.getFields());
dataRecord.setDataEntry_RecordData(jsonString);
saveRecord(dataRecord);
|
final DataEntryRecordId dataEntryRecordId = DataEntryRecordId.ofRepoId(dataRecord.getDataEntry_Record_ID());
dataEntryRecord.setId(dataEntryRecordId);
return dataEntryRecordId;
}
public void deleteBy(@NonNull final DataEntryRecordQuery query)
{
query(query).delete();
}
private IQuery<I_DataEntry_Record> query(@NonNull final DataEntryRecordQuery query)
{
final ImmutableSet<DataEntrySubTabId> dataEntrySubTabIds = query.getDataEntrySubTabIds();
final int recordId = query.getRecordId();
return Services.get(IQueryBL.class)
.createQueryBuilder(I_DataEntry_Record.class)
.addOnlyActiveRecordsFilter() // we have a UC on those columns
.addInArrayFilter(I_DataEntry_Record.COLUMN_DataEntry_SubTab_ID, dataEntrySubTabIds)
.addEqualsFilter(I_DataEntry_Record.COLUMN_Record_ID, recordId)
.orderBy(I_DataEntry_Record.COLUMNNAME_DataEntry_SubTab_ID)
.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecordRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public R<Tenant> detail(Tenant tenant) {
Tenant detail = tenantService.getOne(Condition.getQueryWrapper(tenant));
return R.data(detail);
}
/**
* 分页
*/
@GetMapping("/list")
@Parameters({
@Parameter(name = "tenantId", description = "参数名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "tenantName", description = "角色别名", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "contactNumber", description = "联系电话", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
})
@Operation(summary = "分页", description = "传入tenant")
public R<IPage<Tenant>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> tenant, Query query, BladeUser bladeUser) {
QueryWrapper<Tenant> queryWrapper = Condition.getQueryWrapper(tenant, Tenant.class);
IPage<Tenant> pages = tenantService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Tenant::getTenantId, bladeUser.getTenantId()) : queryWrapper);
return R.data(pages);
}
/**
* 下拉数据源
*/
@GetMapping("/select")
@Operation(summary = "下拉数据源", description = "传入tenant")
public R<List<Tenant>> select(Tenant tenant, BladeUser bladeUser) {
QueryWrapper<Tenant> queryWrapper = Condition.getQueryWrapper(tenant);
List<Tenant> list = tenantService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Tenant::getTenantId, bladeUser.getTenantId()) : queryWrapper);
return R.data(list);
}
/**
* 自定义分页
*/
@GetMapping("/page")
@Operation(summary = "分页", description = "传入tenant")
public R<IPage<Tenant>> page(Tenant tenant, Query query) {
IPage<Tenant> pages = tenantService.selectTenantPage(Condition.getPage(query), tenant);
return R.data(pages);
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@Operation(summary = "新增或修改", description = "传入tenant")
|
public R submit(@Valid @RequestBody Tenant tenant) {
return R.status(tenantService.saveTenant(tenant));
}
/**
* 删除
*/
@PostMapping("/remove")
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(tenantService.deleteLogic(Func.toLongList(ids)));
}
/**
* 根据域名查询信息
*
* @param domain 域名
*/
@GetMapping("/info")
@Operation(summary = "配置信息", description = "传入domain")
public R<Kv> info(String domain) {
Tenant tenant = tenantService.getOne(Wrappers.<Tenant>query().lambda().eq(Tenant::getDomain, domain));
Kv kv = Kv.init();
if (tenant != null) {
kv.set("tenantId", tenant.getTenantId()).set("domain", tenant.getDomain());
}
return R.data(kv);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\TenantController.java
| 2
|
请完成以下Java代码
|
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
attachTo(targetTransitionInstance.resolveRepresentativeExecution());
for (MigratingInstance dependentInstance : migratingDependentInstances) {
dependentInstance.attachState(targetTransitionInstance);
}
}
protected void attachTo(ExecutionEntity execution) {
jobEntity.setExecution(execution);
}
public void migrateState() {
// update activity reference
String activityId = targetScope.getId();
jobEntity.setActivityId(activityId);
migrateJobHandlerConfiguration();
if (targetJobDefinitionEntity != null) {
jobEntity.setJobDefinition(targetJobDefinitionEntity);
}
// update process definition reference
ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) targetScope.getProcessDefinition();
jobEntity.setProcessDefinitionId(processDefinition.getId());
jobEntity.setProcessDefinitionKey(processDefinition.getKey());
// update deployment reference
|
jobEntity.setDeploymentId(processDefinition.getDeploymentId());
}
public void migrateDependentEntities() {
for (MigratingInstance migratingDependentInstance : migratingDependentInstances) {
migratingDependentInstance.migrateState();
}
}
public void remove() {
jobEntity.delete();
}
public boolean migrates() {
return targetScope != null;
}
public ScopeImpl getTargetScope() {
return targetScope;
}
public JobDefinitionEntity getTargetJobDefinitionEntity() {
return targetJobDefinitionEntity;
}
protected abstract void migrateJobHandlerConfiguration();
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingJobInstance.java
| 1
|
请完成以下Java代码
|
private Map<InvoicePaySelectionLinesAggregationKey, AggregatedInvoicePaySelectionLines> getInvoiceKeyToGroupedPaySelectionLines(@NonNull final List<I_C_PaySelectionLine> paySelectionLines)
{
return paySelectionLines.stream()
// No Bank account. Nothing to do.
.filter(this::hasBusinessPartnerBankAccount)
.filter(this::isInvoicePaySelectionLine)
.collect(Collectors.groupingBy(this::extractPaySelectionLinesKey, LinkedHashMap::new, AggregatedInvoicePaySelectionLines.collect()));
}
private boolean hasBusinessPartnerBankAccount(@NonNull final I_C_PaySelectionLine line)
{
return BankAccountId.ofRepoIdOrNull(line.getC_BP_BankAccount_ID()) != null;
}
private boolean isOrderPaySelectionLine(@NonNull final I_C_PaySelectionLine line)
{
return paySelectionBL.extractType(line) == PaySelectionLineType.Order;
}
private boolean isInvoicePaySelectionLine(@NonNull final I_C_PaySelectionLine line)
{
return paySelectionBL.extractType(line) == PaySelectionLineType.Invoice;
}
private static @Nullable String toNullOrRemoveSpaces(@Nullable final String from)
{
final String fromNorm = StringUtils.trimBlankToNull(from);
return fromNorm != null ? fromNorm.replace(" ", "") : null;
}
@NonNull
private static String extractIBAN(@NonNull final BankAccount bpBankAccount)
{
final String iban = coalesceSuppliers(
() -> toNullOrRemoveSpaces(bpBankAccount.getIBAN()),
() -> toNullOrRemoveSpaces(bpBankAccount.getQR_IBAN())
);
if (Check.isBlank(iban))
{
throw new AdempiereException(ERR_C_BP_BankAccount_IBANNotSet, bpBankAccount);
}
return iban;
}
|
@NonNull
private CreateSEPAExportFromPaySelectionCommand.InvoicePaySelectionLinesAggregationKey extractPaySelectionLinesKey(@NonNull final I_C_PaySelectionLine paySelectionLine)
{
final BankAccountId bankAccountId = BankAccountId.ofRepoId(paySelectionLine.getC_BP_BankAccount_ID());
final BankAccount bpBankAccount = bankAccountDAO.getById(bankAccountId);
return InvoicePaySelectionLinesAggregationKey.builder()
.orgId(OrgId.ofRepoId(paySelectionLine.getAD_Org_ID()))
.partnerId(BPartnerId.ofRepoId(paySelectionLine.getC_BPartner_ID()))
.bankAccountId(bankAccountId)
.currencyId(bpBankAccount.getCurrencyId())
.iban(extractIBAN(bpBankAccount))
.swiftCode(extractSwiftCode(bpBankAccount))
.build();
}
private @Nullable String extractSwiftCode(@NonNull final BankAccount bpBankAccount)
{
return Optional.ofNullable(bpBankAccount.getBankId())
.map(bankRepo::getById)
.map(bank -> toNullOrRemoveSpaces(bank.getSwiftCode()))
.orElse(null);
}
@Value
@Builder
private static class InvoicePaySelectionLinesAggregationKey
{
@NonNull OrgId orgId;
@NonNull BPartnerId partnerId;
@NonNull BankAccountId bankAccountId;
@NonNull CurrencyId currencyId;
@NonNull String iban;
@Nullable String swiftCode;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\CreateSEPAExportFromPaySelectionCommand.java
| 1
|
请完成以下Java代码
|
public void setCalendarDay (final @Nullable java.lang.String CalendarDay)
{
set_Value (COLUMNNAME_CalendarDay, CalendarDay);
}
@Override
public java.lang.String getCalendarDay()
{
return get_ValueAsString(COLUMNNAME_CalendarDay);
}
@Override
public void setCalendarMonth (final @Nullable java.lang.String CalendarMonth)
{
set_Value (COLUMNNAME_CalendarMonth, CalendarMonth);
}
@Override
public java.lang.String getCalendarMonth()
{
return get_ValueAsString(COLUMNNAME_CalendarMonth);
}
@Override
public void setCalendarYear (final java.lang.String CalendarYear)
{
set_ValueNoCheck (COLUMNNAME_CalendarYear, CalendarYear);
}
@Override
public java.lang.String getCalendarYear()
{
|
return get_ValueAsString(COLUMNNAME_CalendarYear);
}
@Override
public void setCurrentNext (final int CurrentNext)
{
set_Value (COLUMNNAME_CurrentNext, CurrentNext);
}
@Override
public int getCurrentNext()
{
return get_ValueAsInt(COLUMNNAME_CurrentNext);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_No.java
| 1
|
请完成以下Java代码
|
public Config setInClass(ParameterizedTypeReference inTypeReference) {
this.inClass = inTypeReference;
return this;
}
public @Nullable ParameterizedTypeReference getOutClass() {
return outClass;
}
public Config setOutClass(Class outClass) {
return setOutClass(ParameterizedTypeReference.forType(outClass));
}
public Config setOutClass(ParameterizedTypeReference outClass) {
this.outClass = outClass;
return this;
}
public @Nullable RewriteFunction getRewriteFunction() {
return rewriteFunction;
}
public Config setRewriteFunction(RewriteFunction rewriteFunction) {
this.rewriteFunction = rewriteFunction;
return this;
}
public <T, R> Config setRewriteFunction(Class<T> inClass, Class<R> outClass,
|
RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
public <T, R> Config setRewriteFunction(ParameterizedTypeReference<T> inClass,
ParameterizedTypeReference<R> outClass, RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
public @Nullable String getContentType() {
return contentType;
}
public Config setContentType(@Nullable String contentType) {
this.contentType = contentType;
return this;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\ModifyRequestBodyGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public boolean canHandle(Object object) {
return object instanceof List;
}
public String detectType(Object object) {
return constructType(object).toCanonical();
}
protected JavaType constructType(Object object) {
TypeFactory typeFactory = TypeFactory.defaultInstance();
if (object instanceof List && !((List<?>) object).isEmpty()) {
List<?> list = (List<?>) object;
Object firstElement = list.get(0);
if (bindingsArePresent(list.getClass())) {
final JavaType elementType = constructType(firstElement);
return typeFactory.constructCollectionType(list.getClass(), elementType);
|
}
}
return typeFactory.constructType(object.getClass());
}
private boolean bindingsArePresent(Class<?> erasedType) {
TypeVariable<?>[] vars = erasedType.getTypeParameters();
int varLen = (vars == null) ? 0 : vars.length;
if (varLen == 0) {
return false;
}
if (varLen != 1) {
throw new IllegalArgumentException("Cannot create TypeBindings for class " + erasedType.getName() + " with 1 type parameter: class expects " + varLen);
}
return true;
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\json\ListJacksonJsonTypeDetector.java
| 1
|
请完成以下Java代码
|
public boolean isSuspended() {
return suspended;
}
public String getTenantId() {
return tenantId;
}
public String getCreateUserId() {
return createUserId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(final Date startTime) {
this.startTime = startTime;
}
public Date getExecutionStartTime() {
return executionStartTime;
}
public void setExecutionStartTime(final Date executionStartTime) {
this.executionStartTime = executionStartTime;
|
}
public static BatchDto fromBatch(Batch batch) {
BatchDto dto = new BatchDto();
dto.id = batch.getId();
dto.type = batch.getType();
dto.totalJobs = batch.getTotalJobs();
dto.jobsCreated = batch.getJobsCreated();
dto.batchJobsPerSeed = batch.getBatchJobsPerSeed();
dto.invocationsPerBatchJob = batch.getInvocationsPerBatchJob();
dto.seedJobDefinitionId = batch.getSeedJobDefinitionId();
dto.monitorJobDefinitionId = batch.getMonitorJobDefinitionId();
dto.batchJobDefinitionId = batch.getBatchJobDefinitionId();
dto.suspended = batch.isSuspended();
dto.tenantId = batch.getTenantId();
dto.createUserId = batch.getCreateUserId();
dto.startTime = batch.getStartTime();
dto.executionStartTime = batch.getExecutionStartTime();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchDto.java
| 1
|
请完成以下Java代码
|
public String toString(int indentFactor) throws JSONException {
return toString(indentFactor, 0);
}
/**
* Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the signalData structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @return a printable, displayable, transmittable representation of the array.
* @throws JSONException
*/
String toString(int indentFactor, int indent) throws JSONException {
int len = length();
if (len == 0) {
return "[]";
}
int i;
StringBuilder sb = new StringBuilder("[");
if (len == 1) {
sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor, indent));
} else {
int newindent = indent + indentFactor;
sb.append('\n');
for (i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(",\n");
}
for (int j = 0; j < newindent; j += 1) {
sb.append(' ');
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor, newindent));
}
sb.append('\n');
for (i = 0; i < indent; i += 1) {
sb.append(' ');
}
}
|
sb.append(']');
return sb.toString();
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the signalData structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
try {
boolean b = false;
int len = length();
writer.write('[');
for (int i = 0; i < len; i += 1) {
if (b) {
writer.write(',');
}
Object v = this.myArrayList.get(i);
if (v instanceof JSONObject) {
((JSONObject) v).write(writer);
} else if (v instanceof JSONArray) {
((JSONArray) v).write(writer);
} else {
writer.write(JSONObject.valueToString(v));
}
b = true;
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\JSONArray.java
| 1
|
请完成以下Java代码
|
public final class HUListCursor
{
private final ArrayList<I_M_HU> list = new ArrayList<>();
private int currentIndex = -1;
private I_M_HU currentItem = null;
private boolean currentItemSet = false;
/**
* Append item at the end of the underlying list.
*/
public void append(final I_M_HU item)
{
list.add(item);
}
public I_M_HU current()
{
Check.assume(currentItemSet, "has current item");
return currentItem;
}
public void closeCurrent()
{
currentItemSet = false;
currentItem = null;
}
public boolean hasCurrent()
{
return currentItemSet;
}
public boolean hasNext()
{
final int size = list.size();
if (currentIndex < 0)
{
return size > 0;
}
else
{
|
return currentIndex + 1 < size;
}
}
public I_M_HU next()
{
// Calculate the next index
final int nextIndex;
if (currentIndex < 0)
{
nextIndex = 0;
}
else
{
nextIndex = currentIndex + 1;
}
// Make sure the new index is valid
final int size = list.size();
if (nextIndex >= size)
{
throw new NoSuchElementException("index=" + nextIndex + ", size=" + size);
}
// Update status
this.currentIndex = nextIndex;
this.currentItem = list.get(nextIndex);
this.currentItemSet = true;
return currentItem;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUListCursor.java
| 1
|
请完成以下Java代码
|
public DocTypeId getDocTypeId(
@NonNull final DocBaseType docBaseType,
@NonNull final OrgId orgId)
{
return getDocTypeId(docBaseType, DocSubType.NONE, orgId);
}
@NonNull
public DocTypeId getDocTypeId(
@NonNull final DocBaseType docBaseType,
@NonNull final DocSubType docSubType,
@NonNull final OrgId orgId)
{
final I_AD_Org orgRecord = orgsDAO.getById(orgId);
final DocTypeQuery query = DocTypeQuery
.builder()
.docBaseType(docBaseType)
.docSubType(docSubType)
.adClientId(orgRecord.getAD_Client_ID())
.adOrgId(orgRecord.getAD_Org_ID())
.build();
return docTypeDAO.getDocTypeId(query);
}
@Nullable
public DocTypeId getOrderDocTypeId(@Nullable final JsonOrderDocType orderDocType, final OrgId orgId)
{
if (orderDocType == null)
{
return null;
}
final DocBaseType docBaseType = DocBaseType.SalesOrder;
final DocSubType docSubType;
if (JsonOrderDocType.PrepayOrder.equals(orderDocType))
{
docSubType = DocSubType.PrepayOrder;
}
else
{
docSubType = DocSubType.StandardOrder;
}
final I_AD_Org orgRecord = orgsDAO.getById(orgId);
|
final DocTypeQuery query = DocTypeQuery
.builder()
.docBaseType(docBaseType)
.docSubType(docSubType)
.adClientId(orgRecord.getAD_Client_ID())
.adOrgId(orgRecord.getAD_Org_ID())
.build();
return docTypeDAO.getDocTypeId(query);
}
@NonNull
public Optional<JsonOrderDocType> getOrderDocType(@Nullable final DocTypeId docTypeId)
{
if (docTypeId == null)
{
return Optional.empty();
}
final I_C_DocType docType = docTypeDAO.getById(docTypeId);
final DocBaseType docBaseType = DocBaseType.ofCode(docType.getDocBaseType());
if (!docBaseType.isSalesOrder())
{
throw new AdempiereException("Invalid base doc type!");
}
return Optional.ofNullable(JsonOrderDocType.ofCodeOrNull(docType.getDocSubType()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\DocTypeService.java
| 1
|
请完成以下Java代码
|
public class CmmnExternalWorkerTransitionBuilderImpl implements CmmnExternalWorkerTransitionBuilder {
protected final CommandExecutor commandExecutor;
protected final String externalJobId;
protected final String workerId;
protected Map<String, Object> variables;
public CmmnExternalWorkerTransitionBuilderImpl(CommandExecutor commandExecutor, String externalJobId, String workerId) {
this.commandExecutor = commandExecutor;
this.externalJobId = externalJobId;
this.workerId = workerId;
}
@Override
public CmmnExternalWorkerTransitionBuilder variables(Map<String, Object> variables) {
if (this.variables == null) {
this.variables = new LinkedHashMap<>();
}
this.variables.putAll(variables);
return this;
}
|
@Override
public CmmnExternalWorkerTransitionBuilder variable(String name, Object value) {
if (this.variables == null) {
this.variables = new LinkedHashMap<>();
}
this.variables.put(name, value);
return this;
}
@Override
public void complete() {
commandExecutor.execute(new ExternalWorkerJobCompleteCmd(externalJobId, workerId, variables));
}
@Override
public void terminate() {
commandExecutor.execute(new ExternalWorkerJobTerminateCmd(externalJobId, workerId, variables));
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnExternalWorkerTransitionBuilderImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String toPage(){
return "/imgUpload";
}
@RequestMapping(value = "/transfer",method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<InputStreamResource> imt2txt(@RequestParam("file") MultipartFile file){
try {
String originalFilename = file.getOriginalFilename();
HttpHeaders headers = new HttpHeaders();
// 支持jpg、png
if(originalFilename.toLowerCase().endsWith("jpg")||originalFilename.toLowerCase().endsWith("png")){
File outFile = img2TxtService.save(file.getBytes(), originalFilename);
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", outFile.getName()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(outFile.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(new FileInputStream(outFile)));
}else{
|
File error = new File(img2TxtService.getErrorPath());
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", error.getName()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(error.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(new FileInputStream(error)));
}
} catch (IOException e) {
logger.error(e);
return new ResponseEntity("暂不支持的文件格式",HttpStatus.BAD_REQUEST);
}
// return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
|
repos\spring-boot-quick-master\quick-img2txt\src\main\java\com\quick\controller\Img2TxtController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public DataScopeModel getDataScopeByMapper(String mapperId, String roleId) {
List<Object> args = new ArrayList<>(Collections.singletonList(mapperId));
List<Long> roleIds = Func.toLongList(roleId);
args.addAll(roleIds);
// 增加searched字段防止未配置的参数重复读库导致缓存击穿
// 后续若有新增配置则会清空缓存重新加载
DataScopeModel dataScope;
List<DataScopeModel> list = jdbcTemplate.query(DataScopeConstant.dataByMapper(roleIds.size()), args.toArray(), new BeanPropertyRowMapper<>(DataScopeModel.class));
if (CollectionUtil.isNotEmpty(list)) {
dataScope = list.iterator().next();
dataScope.setSearched(Boolean.TRUE);
} else {
dataScope = SEARCHED_DATA_SCOPE_MODEL;
}
return dataScope;
}
/**
* 获取数据权限
*
* @param code 数据权限资源编号
* @return DataScopeModel
*/
@Override
@GetMapping(GET_DATA_SCOPE_BY_CODE)
public DataScopeModel getDataScopeByCode(String code) {
|
// 增加searched字段防止未配置的参数重复读库导致缓存击穿
// 后续若有新增配置则会清空缓存重新加载
DataScopeModel dataScope;
List<DataScopeModel> list = jdbcTemplate.query(DataScopeConstant.DATA_BY_CODE, new Object[]{code}, new BeanPropertyRowMapper<>(DataScopeModel.class));
if (CollectionUtil.isNotEmpty(list)) {
dataScope = list.iterator().next();
dataScope.setSearched(Boolean.TRUE);
} else {
dataScope = SEARCHED_DATA_SCOPE_MODEL;
}
return dataScope;
}
/**
* 获取部门子级
*
* @param deptId 部门id
* @return deptIds
*/
@Override
@GetMapping(GET_DEPT_ANCESTORS)
public List<Long> getDeptAncestors(Long deptId) {
return jdbcTemplate.queryForList(DataScopeConstant.DATA_BY_DEPT, new Object[]{deptId}, Long.class);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\feign\DataScopeClient.java
| 2
|
请完成以下Java代码
|
public FlowableScriptEvaluationRequest script(String script) {
if (StringUtils.isEmpty(script)) {
throw new FlowableIllegalArgumentException("script is empty");
}
this.script = script;
return this;
}
@Override
public FlowableScriptEvaluationRequest resolver(Resolver resolver) {
this.resolver = resolver;
return this;
}
@Override
public FlowableScriptEvaluationRequest scopeContainer(VariableContainer scopeContainer) {
this.scopeContainer = scopeContainer;
return this;
}
@Override
public FlowableScriptEvaluationRequest inputVariableContainer(VariableContainer inputVariableContainer) {
this.inputVariableContainer = inputVariableContainer;
return this;
}
@Override
public FlowableScriptEvaluationRequest storeScriptVariables() {
this.storeScriptVariables = true;
return this;
}
|
@Override
public ScriptEvaluation evaluate() throws FlowableScriptException {
if (StringUtils.isEmpty(language)) {
throw new FlowableIllegalArgumentException("language is required");
}
if (StringUtils.isEmpty(script)) {
throw new FlowableIllegalArgumentException("script is required");
}
ScriptEngine scriptEngine = getEngineByName(language);
Bindings bindings = createBindings();
try {
Object result = scriptEngine.eval(script, bindings);
return new ScriptEvaluationImpl(resolver, result);
} catch (ScriptException e) {
throw new FlowableScriptException(e.getMessage(), e);
}
}
protected Bindings createBindings() {
return new ScriptBindings(Collections.singletonList(resolver), scopeContainer, inputVariableContainer, storeScriptVariables);
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\JSR223FlowableScriptEngine.java
| 1
|
请完成以下Java代码
|
public PermissionCheckBuilder atomicCheckForResourceId(Resource resource, String resourceId, Permission permission) {
if (!isPermissionDisabled(permission)) {
PermissionCheck permCheck = new PermissionCheck();
permCheck.setResource(resource);
permCheck.setResourceId(resourceId);
permCheck.setPermission(permission);
this.atomicChecks.add(permCheck);
}
return this;
}
public PermissionCheckBuilder composite() {
return new PermissionCheckBuilder(this);
}
public PermissionCheckBuilder done() {
parent.compositeChecks.add(this.build());
return parent;
}
public CompositePermissionCheck build() {
validate();
CompositePermissionCheck permissionCheck = new CompositePermissionCheck(disjunctive);
|
permissionCheck.setAtomicChecks(atomicChecks);
permissionCheck.setCompositeChecks(compositeChecks);
return permissionCheck;
}
public List<PermissionCheck> getAtomicChecks() {
return atomicChecks;
}
protected void validate() {
if (!atomicChecks.isEmpty() && !compositeChecks.isEmpty()) {
throw new ProcessEngineException("Mixed authorization checks of atomic and composite permissions are not supported");
}
}
public boolean isPermissionDisabled(Permission permission) {
AuthorizationManager authorizationManager = Context.getCommandContext().getAuthorizationManager();
return authorizationManager.isPermissionDisabled(permission);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\PermissionCheckBuilder.java
| 1
|
请完成以下Java代码
|
public void dispose()
{
} // dispose
private String m_columnName;
private String m_oldText;
private String m_initialText;
private volatile boolean m_setting = false;
private GridField m_mField;
// /** Logger */
// private static Logger log = CLogMgt.getLogger(VTextLong.class);
/**
* Set Editor to value
* @param value value
*/
@Override
public void setValue(Object value)
{
if (value == null)
m_oldText = "";
else
m_oldText = MADBoilerPlate.getPlainText(value.toString());
if (m_setting)
return;
super.setValue(m_oldText);
m_initialText = m_oldText;
// Always position Top
setCaretPosition(0);
} // setValue
/**
* Property Change Listener
* @param evt event
*/
@Override
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
requestFocus();
// metas end
} // propertyChange
/**
* Action Listener Interface - NOP
* @param listener listener
*/
@Override
public void addActionListener(ActionListener listener)
{
} // addActionListener
|
/**************************************************************************
* Key Listener Interface
* @param e event
*/
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
/**
* Key Released
* if Escape restore old Text.
* @param e event
*/
@Override
public void keyReleased(KeyEvent e)
{
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
setText(m_initialText);
m_setting = true;
try
{
fireVetoableChange(m_columnName, m_oldText, getText());
}
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
/**
* Set Field/WindowNo for ValuePreference
* @param mField field model
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
} // VTextLong
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VTextLong.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ReactiveAccountDao {
private ConnectionFactory connectionFactory;
public ReactiveAccountDao(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public Mono<Account> findById(long id) {
return Mono.from(connectionFactory.create())
.flatMap(c -> Mono.from(c.createStatement("select id,iban,balance from Account where id = $1")
.bind("$1", id)
.execute())
.doFinally((st) -> close(c)))
.map(result -> result.map((row, meta) ->
new Account(row.get("id", Long.class),
row.get("iban", String.class),
row.get("balance", BigDecimal.class))))
.flatMap( p -> Mono.from(p));
}
public Flux<Account> findAll() {
return Mono.from(connectionFactory.create())
.flatMap((c) -> Mono.from(c.createStatement("select id,iban,balance from Account")
.execute())
.doFinally((st) -> close(c)))
.flatMapMany(result -> Flux.from(result.map((row, meta) -> {
Account acc = new Account();
acc.setId(row.get("id", Long.class));
acc.setIban(row.get("iban", String.class));
|
acc.setBalance(row.get("balance", BigDecimal.class));
return acc;
})));
}
public Mono<Account> createAccount(Account account) {
return Mono.from(connectionFactory.create())
.flatMap(c -> Mono.from(c.beginTransaction())
.then(Mono.from(c.createStatement("insert into Account(iban,balance) values($1,$2)")
.bind("$1", account.getIban())
.bind("$2", account.getBalance())
.returnGeneratedValues("id")
.execute()))
.map(result -> result.map((row, meta) ->
new Account(row.get("id", Long.class),
account.getIban(),
account.getBalance())))
.flatMap(pub -> Mono.from(pub))
.delayUntil(r -> c.commitTransaction())
.doFinally((st) -> c.close()));
}
private <T> Mono<T> close(Connection connection) {
return Mono.from(connection.close())
.then(Mono.empty());
}
}
|
repos\tutorials-master\persistence-modules\r2dbc\src\main\java\com\baeldung\examples\r2dbc\ReactiveAccountDao.java
| 2
|
请完成以下Java代码
|
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCalculated (final BigDecimal QtyCalculated)
{
set_Value (COLUMNNAME_QtyCalculated, QtyCalculated);
}
@Override
public BigDecimal getQtyCalculated()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCalculated);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSalesRep_ID (final int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID);
}
@Override
public int getSalesRep_ID()
{
return get_ValueAsInt(COLUMNNAME_SalesRep_ID);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
@Override
public void setUserElementString2 (final @Nullable java.lang.String UserElementString2)
{
set_Value (COLUMNNAME_UserElementString2, UserElementString2);
}
@Override
public java.lang.String getUserElementString2()
{
return get_ValueAsString(COLUMNNAME_UserElementString2);
}
@Override
public void setUserElementString3 (final @Nullable java.lang.String UserElementString3)
{
set_Value (COLUMNNAME_UserElementString3, UserElementString3);
}
@Override
public java.lang.String getUserElementString3()
{
return get_ValueAsString(COLUMNNAME_UserElementString3);
}
@Override
public void setUserElementString4 (final @Nullable java.lang.String UserElementString4)
{
set_Value (COLUMNNAME_UserElementString4, UserElementString4);
}
|
@Override
public java.lang.String getUserElementString4()
{
return get_ValueAsString(COLUMNNAME_UserElementString4);
}
@Override
public void setUserElementString5 (final @Nullable java.lang.String UserElementString5)
{
set_Value (COLUMNNAME_UserElementString5, UserElementString5);
}
@Override
public java.lang.String getUserElementString5()
{
return get_ValueAsString(COLUMNNAME_UserElementString5);
}
@Override
public void setUserElementString6 (final @Nullable java.lang.String UserElementString6)
{
set_Value (COLUMNNAME_UserElementString6, UserElementString6);
}
@Override
public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ForecastLine.java
| 1
|
请完成以下Java代码
|
public boolean hasNext()
{
return hasPeeked || iterator.hasNext();
}
@Override
public E next()
{
if (!hasPeeked)
{
final E result = iterator.next();
return result;
}
final E result = peekedElement;
hasPeeked = false;
peekedElement = null;
return result;
}
@Override
public void remove()
{
if (hasPeeked)
{
throw new IllegalStateException("Can't remove after you've peeked at next");
}
iterator.remove();
}
|
@Override
public E peek()
{
if (!hasPeeked)
{
peekedElement = iterator.next();
hasPeeked = true;
}
return peekedElement;
}
@Override
public Iterator<E> getParentIterator()
{
return iterator;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\PeekIteratorWrapper.java
| 1
|
请完成以下Java代码
|
public class Question {
private String id;
private String description;
private String correctAnswer;
private List<String> options;
// Needed by Caused by: com.fasterxml.jackson.databind.JsonMappingException:
// Can not construct instance of com.in28minutes.springboot.model.Question:
// no suitable constructor found, can not deserialize from Object value
// (missing default constructor or creator, or perhaps need to add/enable
// type information?)
public Question() {
}
public Question(String id, String description, String correctAnswer,
List<String> options) {
super();
this.id = id;
this.description = description;
this.correctAnswer = correctAnswer;
this.options = options;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public String getCorrectAnswer() {
return correctAnswer;
}
|
public List<String> getOptions() {
return options;
}
@Override
public String toString() {
return String
.format("Question [id=%s, description=%s, correctAnswer=%s, options=%s]",
id, description, correctAnswer, options);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Question other = (Question) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
repos\SpringBootForBeginners-master\05.Spring-Boot-Advanced\src\main\java\com\in28minutes\springboot\model\Question.java
| 1
|
请完成以下Java代码
|
private static MediaType getContentType(final @Nullable HttpHeaders httpHeaders)
{
return httpHeaders != null ? httpHeaders.getContentType() : null;
}
@NonNull
private static Charset getCharset(final @NonNull ContentCachingResponseWrapper responseWrapper)
{
final String charset = StringUtils.trimBlankToNull(responseWrapper.getCharacterEncoding());
return charset != null ? Charset.forName(charset) : StandardCharsets.UTF_8;
}
@Nullable
private Object getBody(@NonNull final ContentCachingResponseWrapper responseWrapper)
{
if (responseWrapper.getContentSize() <= 0)
{
return null;
}
final MediaType contentType = getContentType(responseWrapper);
if (contentType == null)
{
return null;
}
else if (contentType.includes(MediaType.TEXT_PLAIN))
{
return new String(responseWrapper.getContentAsByteArray());
}
else if (contentType.includes(MediaType.APPLICATION_JSON))
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(responseWrapper.getContentAsByteArray(), Object.class);
}
catch (final IOException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
else
{
return responseWrapper.getContentAsByteArray();
}
}
@Nullable
private Object getBody(@Nullable final HttpHeaders httpHeaders, @Nullable final String bodyCandidate)
{
|
if (bodyCandidate == null)
{
return null;
}
final MediaType contentType = getContentType(httpHeaders);
if (contentType == null)
{
return null;
}
else if (contentType.includes(MediaType.TEXT_PLAIN))
{
return bodyCandidate;
}
else if (contentType.includes(MediaType.APPLICATION_JSON))
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(bodyCandidate, Object.class);
}
catch (final IOException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
else
{
return bodyCandidate;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiResponseMapper.java
| 1
|
请完成以下Java代码
|
public @Nullable String getHostValue() {
return hostValue;
}
public RewriteLocationResponseHeaderConfig setHostValue(String hostValue) {
this.hostValue = hostValue;
return this;
}
public String getProtocolsRegex() {
return protocolsRegex;
}
public RewriteLocationResponseHeaderConfig setProtocolsRegex(String protocolsRegex) {
this.protocolsRegex = protocolsRegex;
this.hostPortPattern = compileHostPortPattern(protocolsRegex);
|
this.hostPortVersionPattern = compileHostPortVersionPattern(protocolsRegex);
return this;
}
public Pattern getHostPortPattern() {
return hostPortPattern;
}
public Pattern getHostPortVersionPattern() {
return hostPortVersionPattern;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RewriteLocationResponseHeaderFilterFunctions.java
| 1
|
请完成以下Java代码
|
public String name() {
return this.fileSystem.toString();
}
@Override
public String type() {
return "nestedfs";
}
@Override
public boolean isReadOnly() {
return this.fileSystem.isReadOnly();
}
@Override
public long getTotalSpace() throws IOException {
return 0;
}
@Override
public long getUsableSpace() throws IOException {
return 0;
}
@Override
public long getUnallocatedSpace() throws IOException {
return 0;
}
@Override
public boolean supportsFileAttributeView(Class<? extends FileAttributeView> type) {
return getJarPathFileStore().supportsFileAttributeView(type);
}
@Override
public boolean supportsFileAttributeView(String name) {
return getJarPathFileStore().supportsFileAttributeView(name);
}
@Override
public <V extends FileStoreAttributeView> V getFileStoreAttributeView(Class<V> type) {
return getJarPathFileStore().getFileStoreAttributeView(type);
}
|
@Override
public Object getAttribute(String attribute) throws IOException {
try {
return getJarPathFileStore().getAttribute(attribute);
}
catch (UncheckedIOException ex) {
throw ex.getCause();
}
}
protected FileStore getJarPathFileStore() {
try {
return Files.getFileStore(this.fileSystem.getJarPath());
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileStore.java
| 1
|
请完成以下Java代码
|
public UserRolePermissionsBuilder setMobileApplicationAccesses(final MobileApplicationPermissions mobileApplicationAccesses)
{
this.mobileApplicationAccesses = mobileApplicationAccesses;
return this;
}
UserRolePermissionsBuilder setMiscPermissions(final GenericPermissions permissions)
{
Check.assumeNull(miscPermissions, "permissions not already configured");
miscPermissions = permissions;
return this;
}
public GenericPermissions getMiscPermissions()
{
Check.assumeNotNull(miscPermissions, "permissions configured");
return miscPermissions;
}
UserRolePermissionsBuilder setConstraints(final Constraints constraints)
{
Check.assumeNull(this.constraints, "constraints not already configured");
this.constraints = constraints;
return this;
}
public Constraints getConstraints()
{
Check.assumeNotNull(constraints, "constraints configured");
return constraints;
}
@SuppressWarnings("UnusedReturnValue")
public UserRolePermissionsBuilder includeUserRolePermissions(final UserRolePermissions userRolePermissions, final int seqNo)
{
userRolePermissionsToInclude.add(UserRolePermissionsInclude.of(userRolePermissions, seqNo));
return this;
}
UserRolePermissionsBuilder setAlreadyIncludedRolePermissions(final UserRolePermissionsIncludesList userRolePermissionsAlreadyIncluded)
{
Check.assumeNotNull(userRolePermissionsAlreadyIncluded, "included not null");
Check.assumeNull(this.userRolePermissionsAlreadyIncluded, "already included permissions were not configured before");
this.userRolePermissionsAlreadyIncluded = userRolePermissionsAlreadyIncluded;
return this;
}
UserRolePermissionsIncludesList getUserRolePermissionsIncluded()
{
|
Check.assumeNotNull(userRolePermissionsIncluded, "userRolePermissionsIncluded not null");
return userRolePermissionsIncluded;
}
public UserRolePermissionsBuilder setMenuInfo(final UserMenuInfo menuInfo)
{
this._menuInfo = menuInfo;
return this;
}
public UserMenuInfo getMenuInfo()
{
if (_menuInfo == null)
{
_menuInfo = findMenuInfo();
}
return _menuInfo;
}
private UserMenuInfo findMenuInfo()
{
final Role adRole = getRole();
final AdTreeId roleMenuTreeId = adRole.getMenuTreeId();
if (roleMenuTreeId != null)
{
return UserMenuInfo.of(roleMenuTreeId, adRole.getRootMenuId());
}
final I_AD_ClientInfo adClientInfo = getAD_ClientInfo();
final AdTreeId adClientMenuTreeId = AdTreeId.ofRepoIdOrNull(adClientInfo.getAD_Tree_Menu_ID());
if (adClientMenuTreeId != null)
{
return UserMenuInfo.of(adClientMenuTreeId, adRole.getRootMenuId());
}
// Fallback: when role has NO menu and there is no menu defined on AD_ClientInfo level - shall not happen
return UserMenuInfo.DEFAULT_MENU;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsBuilder.java
| 1
|
请完成以下Java代码
|
/*package */final class GridTabCalloutStateChangeListener implements StateChangeListener
{
public static final void bind(final GridTab gridTab, final ITabCallout callouts)
{
if(callouts == null || callouts == ITabCallout.NULL)
{
return; // nothing to bind
}
final GridTabCalloutStateChangeListener listener = new GridTabCalloutStateChangeListener(callouts);
gridTab.addStateChangeListener(listener);
}
private final ITabCallout callouts;
private GridTabCalloutStateChangeListener(final ITabCallout callouts)
{
Check.assumeNotNull(callouts, "callouts not null");
this.callouts = callouts;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(callouts)
.toString();
}
@Override
public void stateChange(final StateChangeEvent event)
{
final GridTab gridTab = event.getSource();
final StateChangeEventType eventType = event.getEventType();
switch (eventType)
{
case DATA_REFRESH_ALL:
callouts.onRefreshAll(gridTab);
break;
case DATA_REFRESH:
callouts.onRefresh(gridTab);
break;
case DATA_NEW:
|
callouts.onNew(gridTab);
break;
case DATA_DELETE:
callouts.onDelete(gridTab);
break;
case DATA_SAVE:
callouts.onSave(gridTab);
break;
case DATA_IGNORE:
callouts.onIgnore(gridTab);
break;
default:
// tolerate all other events, event if they are meaningless for us
// throw new AdempiereException("EventType " + eventType + " is not supported");
break;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTabCalloutStateChangeListener.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.