instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void setLastASNNumber(String value) { this.lastASNNumber = value; } /** * Gets the value of the lastASNDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getLastASNDate() { return lastASNDate; } /** * Sets the value of the lastASNDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setLastASNDate(XMLGregorianCalendar value) { this.lastASNDate = value; } /** * Gets the value of the lastASNDeliveryDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getLastASNDeliveryDate() { return lastASNDeliveryDate; } /** * Sets the value of the lastASNDeliveryDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setLastASNDeliveryDate(XMLGregorianCalendar value) { this.lastASNDeliveryDate = value; } /** * Gets the value of the lastReceivedQuantity property. * * @return * possible object is * {@link ConditionalUnitType } * */ public ConditionalUnitType getLastReceivedQuantity() { return lastReceivedQuantity; } /** * Sets the value of the lastReceivedQuantity property. * * @param value * allowed object is * {@link ConditionalUnitType } * */ public void setLastReceivedQuantity(ConditionalUnitType value) { this.lastReceivedQuantity = value; } /**
* Gets the value of the lastASNDispatchDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getLastASNDispatchDate() { return lastASNDispatchDate; } /** * Sets the value of the lastASNDispatchDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setLastASNDispatchDate(XMLGregorianCalendar value) { this.lastASNDispatchDate = value; } /** * Gets the value of the lastDispatchedQuantity property. * * @return * possible object is * {@link ConditionalUnitType } * */ public ConditionalUnitType getLastDispatchedQuantity() { return lastDispatchedQuantity; } /** * Sets the value of the lastDispatchedQuantity property. * * @param value * allowed object is * {@link ConditionalUnitType } * */ public void setLastDispatchedQuantity(ConditionalUnitType value) { this.lastDispatchedQuantity = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ForecastASNReferenceType.java
2
请完成以下Java代码
public CostAmount subtract(@NonNull final CostAmount amtToSubtract) { assertCurrencyMatching(amtToSubtract); if (amtToSubtract.isZero()) { return this; } return add(amtToSubtract.negate()); } public CostAmount toZero() { if (isZero()) { return this; } else { return new CostAmount(value.toZero(), sourceValue != null ? sourceValue.toZero() : null); } } public Money toMoney() { return value; } @Nullable public Money toSourceMoney() {
return sourceValue; } public BigDecimal toBigDecimal() {return value.toBigDecimal();} public boolean compareToEquals(@NonNull final CostAmount other) { return this.value.compareTo(other.value) == 0; } public static CurrencyId getCommonCurrencyIdOfAll(@Nullable final CostAmount... costAmounts) { return CurrencyId.getCommonCurrencyIdOfAll(CostAmount::getCurrencyId, "Amount", costAmounts); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmount.java
1
请完成以下Java代码
private InputStream getInputStream(int size, InputStreamSupplier streamSupplier) throws IOException { InputStream inputStream = streamSupplier.get(); return (this.entry.getMethod() != ZipEntry.DEFLATED) ? inputStream : new ZipInflaterInputStream(inputStream, this.inflater, size); } private void assertSameContent(DataInputStream expected) throws IOException { int len; while ((len = this.in.read(this.inBuffer)) > 0) { try { expected.readFully(this.compareBuffer, 0, len); if (Arrays.equals(this.inBuffer, 0, len, this.compareBuffer, 0, len)) { continue; } } catch (EOFException ex) { // Continue and throw exception due to mismatched content length. } fail("content"); } if (expected.read() != -1) { fail("content"); } }
private void fail(String check) { throw new IllegalStateException("Content mismatch when reading security info for entry '%s' (%s check)" .formatted(this.entry.getName(), check)); } @Override public void close() throws IOException { this.inflater.end(); this.in.close(); } @FunctionalInterface interface InputStreamSupplier { InputStream get() throws IOException; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\JarEntriesStream.java
1
请在Spring Boot框架中完成以下Java代码
public Greeting greeting() { Greeting greeting = new Greeting(); greeting.setMessage("Hello World !!"); return greeting; } @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); bean.setOrder(2); return bean; } @Bean public BeanNameViewResolver beanNameViewResolver(){ BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver(); beanNameViewResolver.setOrder(1); return beanNameViewResolver; } @Bean
public View sample() { return new JstlView("/WEB-INF/view/sample.jsp"); } @Bean public View sample2() { return new JstlView("/WEB-INF/view2/sample2.jsp"); } @Bean public View sample3(){ return new JstlView("/WEB-INF/view3/sample3.jsp"); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-4\src\main\java\com\baeldung\config\WebConfig.java
2
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set AD_User_Roles. @param AD_User_Roles_ID AD_User_Roles */ @Override
public void setAD_User_Roles_ID (int AD_User_Roles_ID) { if (AD_User_Roles_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Roles_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Roles_ID, Integer.valueOf(AD_User_Roles_ID)); } /** Get AD_User_Roles. @return AD_User_Roles */ @Override public int getAD_User_Roles_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_Roles_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_AD_User_Roles.java
1
请完成以下Java代码
public static List<Term> segment(char[] text) { List<Term> resultList = SEGMENT.seg(text); ListIterator<Term> listIterator = resultList.listIterator(); while (listIterator.hasNext()) { if (!CoreStopWordDictionary.shouldInclude(listIterator.next())) { listIterator.remove(); } } return resultList; } /** * 切分为句子形式 * * @param text * @return */ public static List<List<Term>> seg2sentence(String text) { List<List<Term>> sentenceList = SEGMENT.seg2sentence(text); for (List<Term> sentence : sentenceList) { ListIterator<Term> listIterator = sentence.listIterator(); while (listIterator.hasNext()) { if (!CoreStopWordDictionary.shouldInclude(listIterator.next())) { listIterator.remove(); } } } return sentenceList; } /** * 分词断句 输出句子形式 * * @param text 待分词句子 * @param shortest 是否断句为最细的子句(将逗号也视作分隔符) * @return 句子列表,每个句子由一个单词列表组成 */ public static List<List<Term>> seg2sentence(String text, boolean shortest) {
return SEGMENT.seg2sentence(text, shortest); } /** * 切分为句子形式 * * @param text * @param filterArrayChain 自定义过滤器链 * @return */ public static List<List<Term>> seg2sentence(String text, Filter... filterArrayChain) { List<List<Term>> sentenceList = SEGMENT.seg2sentence(text); for (List<Term> sentence : sentenceList) { ListIterator<Term> listIterator = sentence.listIterator(); while (listIterator.hasNext()) { if (filterArrayChain != null) { Term term = listIterator.next(); for (Filter filter : filterArrayChain) { if (!filter.shouldInclude(term)) { listIterator.remove(); break; } } } } } return sentenceList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\NotionalTokenizer.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(type, therapyId, therapyTypeId, woundLocation, patientId, createdBy, createdAt, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AttachmentMetadata {\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n"); sb.append(" therapyTypeId: ").append(toIndentedString(therapyTypeId)).append("\n"); sb.append(" woundLocation: ").append(toIndentedString(woundLocation)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n"); sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\AttachmentMetadata.java
2
请完成以下Java代码
public SqlLookupDescriptorFactory setDisplayType(final ReferenceId displayType) { this.displayType = displayType; this.filtersBuilder.setDisplayType(ReferenceId.toRepoId(displayType)); return this; } public SqlLookupDescriptorFactory setAD_Reference_Value_ID(final ReferenceId AD_Reference_Value_ID) { this.AD_Reference_Value_ID = AD_Reference_Value_ID; return this; } public SqlLookupDescriptorFactory setAdValRuleIds(@NonNull final Map<LookupDescriptorProvider.LookupScope, AdValRuleId> adValRuleIds) { this.filtersBuilder.setAdValRuleIds(adValRuleIds); return this; } private CompositeSqlLookupFilter getFilters() { return filtersBuilder.getOrBuild(); } private static boolean computeIsHighVolume(@NonNull final ReferenceId diplayType) { final int displayTypeInt = diplayType.getRepoId(); return DisplayType.TableDir != displayTypeInt && DisplayType.Table != displayTypeInt && DisplayType.List != displayTypeInt && DisplayType.Button != displayTypeInt; } /** * Advice the lookup to show all records on which current user has at least read only access */ public SqlLookupDescriptorFactory setReadOnlyAccess() { this.requiredAccess = Access.READ; return this; } private Access getRequiredAccess(@NonNull final TableName tableName) { if (requiredAccess != null) { return requiredAccess; } // AD_Client_ID/AD_Org_ID (security fields): shall display only those entries on which current user has read-write access
if (I_AD_Client.Table_Name.equals(tableName.getAsString()) || I_AD_Org.Table_Name.equals(tableName.getAsString())) { return Access.WRITE; } // Default: all entries on which current user has at least readonly access return Access.READ; } SqlLookupDescriptorFactory addValidationRules(final Collection<IValidationRule> validationRules) { this.filtersBuilder.addFilter(validationRules, null); return this; } SqlLookupDescriptorFactory setPageLength(final Integer pageLength) { this.pageLength = pageLength; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptorFactory.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Page URL. @param PageURL Page URL */ public void setPageURL (String PageURL) { set_Value (COLUMNNAME_PageURL, PageURL); } /** Get Page URL. @return Page URL */ public String getPageURL () { return (String)get_Value(COLUMNNAME_PageURL); } /** Set Counter Count. @param W_CounterCount_ID Web Counter Count Management
*/ public void setW_CounterCount_ID (int W_CounterCount_ID) { if (W_CounterCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID)); } /** Get Counter Count. @return Web Counter Count Management */ public int getW_CounterCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_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_W_CounterCount.java
1
请在Spring Boot框架中完成以下Java代码
public GatewayMetricsFilter gatewayMetricFilter(MeterRegistry meterRegistry, List<GatewayTagsProvider> tagsProviders, GatewayMetricsProperties properties) { return new GatewayMetricsFilter(meterRegistry, tagsProviders, properties.getPrefix()); } @Bean @ConditionalOnBean(MeterRegistry.class) @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".metrics.enabled", matchIfMissing = true) public RouteDefinitionMetrics routeDefinitionMetrics(MeterRegistry meterRegistry, RouteDefinitionLocator routeDefinitionLocator, GatewayMetricsProperties properties) { return new RouteDefinitionMetrics(meterRegistry, routeDefinitionLocator, properties.getPrefix()); } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(ObservationRegistry.class) @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".observability.enabled", matchIfMissing = true) static class ObservabilityConfiguration { @Bean @ConditionalOnMissingBean ObservedRequestHttpHeadersFilter observedRequestHttpHeadersFilter(ObservationRegistry observationRegistry, ObjectProvider<GatewayObservationConvention> gatewayObservationConvention) { return new ObservedRequestHttpHeadersFilter(observationRegistry, gatewayObservationConvention.getIfAvailable(() -> null)); }
@Bean @ConditionalOnMissingBean ObservedResponseHttpHeadersFilter observedResponseHttpHeadersFilter() { return new ObservedResponseHttpHeadersFilter(); } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) ObservationClosingWebExceptionHandler observationClosingWebExceptionHandler() { return new ObservationClosingWebExceptionHandler(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayMetricsAutoConfiguration.java
2
请完成以下Java代码
private RESTApiTableInfoMap getMap() { return cache.getOrLoad(0, this::retrieveMap); } private RESTApiTableInfoMap retrieveMap() { final String sql = "SELECT " + " t." + I_AD_Table.COLUMNNAME_TableName + ", c." + I_AD_Column.COLUMNNAME_ColumnName + " FROM " + I_AD_Column.Table_Name + " c " + " INNER JOIN " + I_AD_Table.Table_Name + " t ON (t.AD_Table_ID=c.AD_Table_ID)" + " WHERE c." + I_AD_Column.COLUMNNAME_IsRestAPICustomColumn + "='Y'" + " AND c.IsActive='Y' AND t.IsActive='Y'" + " ORDER BY t." + I_AD_Table.COLUMNNAME_TableName + ", c." + I_AD_Column.COLUMNNAME_ColumnName; final HashMap<String, RESTApiTableInfoBuilder> builders = new HashMap<>(); DB.forEachRow(sql, null, rs -> { final String tableName = rs.getString(I_AD_Table.COLUMNNAME_TableName); final String columnName = rs.getString(I_AD_Column.COLUMNNAME_ColumnName); builders.computeIfAbsent(tableName, RESTApiTableInfo::newBuilderForTableName) .customRestAPIColumnName(columnName); }); return builders.values().stream() .map(RESTApiTableInfoBuilder::build) .collect(RESTApiTableInfoMap.collect());
} @EqualsAndHashCode @ToString private static class RESTApiTableInfoMap { private final ImmutableMap<String, RESTApiTableInfo> byTableName; private RESTApiTableInfoMap(final List<RESTApiTableInfo> list) { this.byTableName = Maps.uniqueIndex(list, RESTApiTableInfo::getTableName); } public static Collector<RESTApiTableInfo, ?, RESTApiTableInfoMap> collect() { return GuavaCollectors.collectUsingListAccumulator(RESTApiTableInfoMap::new); } @Nullable private RESTApiTableInfo getByTableNameOrNull(final String tableName) { return this.byTableName.get(tableName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\custom_columns\CustomColumnRepository.java
1
请完成以下Java代码
public int compare(Integer o1, Integer o2) { return o2 - o1; } }); // add our values to the map for (final Entry<String, String> entry : valuesForPrefix.entrySet()) { final int sizeInt = parseInt(entry.getKey(), sysConfigPrefix); if (sizeInt < 0) { // ignore it; note that we already logged a warning. continue; } final ConstantWorkpackagePrio constrantPrio = ConstantWorkpackagePrio.fromString(entry.getValue()); if (constrantPrio == null) { logger.warn("Unable to parse the the priority string {}.\nPlease fix the value of the AD_SysConfig record with name={}", entry.getValue(), entry.getKey()); continue; } sortedMap.put(sizeInt, constrantPrio); }
return sortedMap; } }); return sortedMap; } private int parseInt(final String completeString, final String prefix) { final String sizeStr = completeString.substring(prefix.length()); int size = -1; try { size = Integer.parseInt(sizeStr); } catch (NumberFormatException e) { logger.warn("Unable to parse the prio int value from AD_SysConfig.Name={}. Ignoring its value.", completeString); } return size; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\impl\SysconfigBackedSizeBasedWorkpackagePrioConfig.java
1
请完成以下Java代码
public int getScore() { return score; } public void setScore(int score) { this.score = score; } } static class UppercasingRequestConverter implements RequestConverterFunction { @Override public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType, ParameterizedType expectedParameterizedResultType) throws Exception { if (expectedResultType.isAssignableFrom(String.class)) { return request.content(StandardCharsets.UTF_8).toUpperCase(); } return RequestConverterFunction.fallthrough(); } } static class UppercasingResponseConverter implements ResponseConverterFunction { @Override public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers, @Nullable Object result, HttpHeaders trailers) { if (result instanceof String) {
return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, ((String) result).toUpperCase(), trailers); } return ResponseConverterFunction.fallthrough(); } } static class ConflictExceptionHandler implements ExceptionHandlerFunction { @Override public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) { if (cause instanceof IllegalStateException) { return HttpResponse.of(HttpStatus.CONFLICT); } return ExceptionHandlerFunction.fallthrough(); } } } }
repos\tutorials-master\server-modules\armeria\src\main\java\com\baeldung\armeria\AnnotatedServer.java
1
请完成以下Java代码
public static class VEditorDialogButtonAlignJsonSerializer extends UIResourceJsonSerializer<VEditorDialogButtonAlign> { @Override public JsonElement serialize(VEditorDialogButtonAlign src, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jo = new JsonObject(); jo.addProperty(PROPERTY_Classname, src.getClass().getName()); jo.addProperty("value", src.toString()); return jo; } @Override public VEditorDialogButtonAlign deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject jo = json.getAsJsonObject();
final String value = jo.get("value").getAsString(); try { return VEditorDialogButtonAlign.valueOf(value); } catch (Exception e) { logger.warn("Failed parsing value {}. Using default", value); } return VEditorDialogButtonAlign.DEFAULT_Value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\UIDefaultsSerializer.java
1
请完成以下Java代码
protected Map<String, String> getAsyncLeaveTransitionMetadata() { Map<String, String> metadata = new HashMap<>(); metadata.put(OperationSerializationMetadata.FIELD_PLAN_ITEM_INSTANCE_ID, planItemInstanceEntity.getId()); metadata.put(OperationSerializationMetadata.FIELD_EXIT_TYPE, exitType); metadata.put(OperationSerializationMetadata.FIELD_EXIT_EVENT_TYPE, exitEventType); return metadata; } @Override public boolean abortOperationIfNewStateEqualsOldState() { return true; } @Override public String getOperationName() { return "[Terminate plan item]";
} public String getExitType() { return exitType; } public void setExitType(String exitType) { this.exitType = exitType; } public String getExitEventType() { return exitEventType; } public void setExitEventType(String exitEventType) { this.exitEventType = exitEventType; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\TerminatePlanItemInstanceOperation.java
1
请在Spring Boot框架中完成以下Java代码
public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getIdPrefix() { // id prefix is empty because sequence is used instead of id prefix return ""; } @Override public void setLogNumber(long logNumber) { this.logNumber = logNumber; } @Override public long getLogNumber() { return logNumber; } @Override public String getType() { return type; } @Override public String getTaskId() { return taskId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public String getUserId() { return userId; } @Override public String getData() {
return data; } @Override public String getExecutionId() { return executionId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String toString() { return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")"; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java
2
请完成以下Java代码
public ResponseEntity<JsonDataEntryResponse> getByRecordId( // with swagger 2.9.2, parameters are always ordered alphabetically, see https://github.com/springfox/springfox/issues/2418 @PathVariable("windowId") final int windowId, @PathVariable("recordId") final int recordId) { final Stopwatch w = Stopwatch.createStarted(); final String adLanguage = RestApiUtilsV1.getAdLanguage(); final ResponseEntity<JsonDataEntryResponse> jsonDataEntry = getByRecordId0(AdWindowId.ofRepoId(windowId), recordId, adLanguage); w.stop(); log.trace("getJsonDataEntry by {windowId '{}' and recordId '{}'} duration: {}", windowId, recordId, w); return jsonDataEntry; } @VisibleForTesting ResponseEntity<JsonDataEntryResponse> getByRecordId0(final AdWindowId windowId, final int recordId, final String adLanguage) { final DataEntryLayout layout = layoutRepo.getByWindowId(windowId); if (layout.isEmpty())
{ return JsonDataEntryResponse.notFound(String.format("No dataentry for windowId '%d'.", windowId.getRepoId())); } final DataEntryRecordsMap records = dataRecords.get(recordId, layout.getSubTabIds()); if (records.getSubTabIds().isEmpty()) { return JsonDataEntryResponse.notFound(String.format("No dataentry for windowId '%d' and recordId '%s'.", windowId.getRepoId(), recordId)); } final JsonDataEntry jsonDataEntry = JsonDataEntryFactory.builder() .layout(layout) .records(records) .adLanguage(adLanguage) .build(); return JsonDataEntryResponse.ok(jsonDataEntry); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\dataentry\impl\DataEntryRestController.java
1
请完成以下Java代码
public class LockTest { Object lock = new Object(); public static void main(String[] args) { LockTest lockTest = new LockTest(); User a = new User(), b = new User(); ThreadTaskUtils.run(() -> lockTest.deadlock(a, b)); ThreadTaskUtils.run(() -> lockTest.deadlock(b, a)); } /** * 死锁解决办法,通过内在排序,保证加锁的顺序性 * * @param a a * @param b b */ private void lock1(User a, User b) { // 使用原生的HashCode方法,防止hashCode方法被重写导致的一些问题, // 如果能确保use对象中的id是唯一且不会重复,可以直接使用userId int aHashCode = System.identityHashCode(a); int bHashCode = System.identityHashCode(b); if (aHashCode > bHashCode) { synchronized (a) { sleep(1000); synchronized (b) { sleep(1000); System.out.println(Thread.currentThread().getName() + " 死锁示例"); } } } else if (aHashCode < bHashCode) { synchronized (b) { sleep(1000); synchronized (a) { sleep(1000); System.out.println(Thread.currentThread().getName() + " 死锁示例"); } } } else { // 引入一个外部锁,解决hash冲突的方法 synchronized (lock) { synchronized (a) { sleep(1000); synchronized (b) { sleep(1000); System.out.println(Thread.currentThread().getName() + " 死锁示例"); } } } } } Random random = new Random(); /** * 使用tryLock尝试拿锁 * * @param a a * @param b b */ private void lock2(User a, User b) { while (true) { try { if (a.getLock().tryLock()) { try { if (b.getLock().tryLock()) { System.out.println(Thread.currentThread().getName() + " 死锁示例"); break; } } finally { b.getLock().unlock();
} } } finally { a.getLock().unlock(); } // 拿锁失败以后,休眠随机数,以避免活锁 sleep(random.nextInt()); } } private void deadlock(User a, User b) { synchronized (a) { sleep(1000); synchronized (b) { sleep(1000); System.out.println(Thread.currentThread().getName() + " 死锁示例"); } } } public static void sleep(int probe) { try { Thread.sleep(probe); } catch (InterruptedException e) { e.printStackTrace(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\LockTest.java
1
请完成以下Java代码
public void setMovementQty (final BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } @Override public BigDecimal getMovementQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCUsPerLU (final @Nullable BigDecimal QtyCUsPerLU) { set_Value (COLUMNNAME_QtyCUsPerLU, QtyCUsPerLU); } @Override public BigDecimal getQtyCUsPerLU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerLU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCUsPerLU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerLU_InInvoiceUOM) { set_Value (COLUMNNAME_QtyCUsPerLU_InInvoiceUOM, QtyCUsPerLU_InInvoiceUOM); } @Override public BigDecimal getQtyCUsPerLU_InInvoiceUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerLU_InInvoiceUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCUsPerTU (final @Nullable BigDecimal QtyCUsPerTU) { set_Value (COLUMNNAME_QtyCUsPerTU, QtyCUsPerTU); } @Override public BigDecimal getQtyCUsPerTU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCUsPerTU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerTU_InInvoiceUOM) { set_Value (COLUMNNAME_QtyCUsPerTU_InInvoiceUOM, QtyCUsPerTU_InInvoiceUOM); }
@Override public BigDecimal getQtyCUsPerTU_InInvoiceUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU_InInvoiceUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyItemCapacity (final @Nullable BigDecimal QtyItemCapacity) { set_Value (COLUMNNAME_QtyItemCapacity, QtyItemCapacity); } @Override public BigDecimal getQtyItemCapacity() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyTU (final int QtyTU) { set_Value (COLUMNNAME_QtyTU, QtyTU); } @Override public int getQtyTU() { return get_ValueAsInt(COLUMNNAME_QtyTU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack_Item.java
1
请完成以下Java代码
public class IterativeCombinationGenerator { private static final int N = 5; private static final int R = 2; /** * Generate all combinations of r elements from a set * @param n the number of elements in input set * @param r the number of elements in a combination * @return the list containing all combinations */ public List<int[]> generate(int n, int r) { List<int[]> combinations = new ArrayList<>(); int[] combination = new int[r]; // initialize with lowest lexicographic combination for (int i = 0; i < r; i++) { combination[i] = i; } while (combination[r - 1] < n) { combinations.add(combination.clone()); // generate next combination in lexicographic order
int t = r - 1; while (t != 0 && combination[t] == n - r + t) { t--; } combination[t]++; for (int i = t + 1; i < r; i++) { combination[i] = combination[i - 1] + 1; } } return combinations; } public static void main(String[] args) { IterativeCombinationGenerator generator = new IterativeCombinationGenerator(); List<int[]> combinations = generator.generate(N, R); System.out.println(combinations.size()); for (int[] combination : combinations) { System.out.println(Arrays.toString(combination)); } } }
repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\algorithms\combination\IterativeCombinationGenerator.java
1
请在Spring Boot框架中完成以下Java代码
CommandLineMetadataController commandLineMetadataController(InitializrMetadataProvider metadataProvider, TemplateRenderer templateRenderer) { return new CommandLineMetadataController(metadataProvider, templateRenderer); } @Bean @ConditionalOnMissingBean SpringCliDistributionController cliDistributionController(InitializrMetadataProvider metadataProvider) { return new SpringCliDistributionController(metadataProvider); } @Bean InitializrModule InitializrJacksonModule() { return new InitializrModule(); } } /** * Initializr cache configuration. */ @Configuration @ConditionalOnClass(javax.cache.CacheManager.class) static class InitializrCacheConfiguration { @Bean JCacheManagerCustomizer initializrCacheManagerCustomizer() { return new InitializrJCacheManagerCustomizer(); } } @Order(0)
private static final class InitializrJCacheManagerCustomizer implements JCacheManagerCustomizer { @Override public void customize(javax.cache.CacheManager cacheManager) { createMissingCache(cacheManager, "initializr.metadata", () -> config().setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES))); createMissingCache(cacheManager, "initializr.dependency-metadata", this::config); createMissingCache(cacheManager, "initializr.project-resources", this::config); createMissingCache(cacheManager, "initializr.templates", this::config); } private void createMissingCache(javax.cache.CacheManager cacheManager, String cacheName, Supplier<MutableConfiguration<Object, Object>> config) { boolean cacheExist = StreamSupport.stream(cacheManager.getCacheNames().spliterator(), true) .anyMatch((name) -> name.equals(cacheName)); if (!cacheExist) { cacheManager.createCache(cacheName, config.get()); } } private MutableConfiguration<Object, Object> config() { return new MutableConfiguration<>().setStoreByValue(false) .setManagementEnabled(true) .setStatisticsEnabled(true); } } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\autoconfigure\InitializrAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void save(SmsCode smsCode, ServletWebRequest request, String mobile) throws Exception { redisTemplate.opsForValue().set(key(request, mobile), smsCode.getCode(), TIME_OUT, TimeUnit.SECONDS); } /** * 获取验证码 * * @param request ServletWebRequest * @return 验证码 */ public String get(ServletWebRequest request, String mobile) throws Exception { return redisTemplate.opsForValue().get(key(request, mobile)); } /**
* 移除验证码 * * @param request ServletWebRequest */ public void remove(ServletWebRequest request, String mobile) throws Exception { redisTemplate.delete(key(request, mobile)); } private String key(ServletWebRequest request, String mobile) throws Exception { String deviceId = request.getHeader("deviceId"); if (StringUtils.isBlank(deviceId)) { throw new Exception("请在请求头中设置deviceId"); } return SMS_CODE_PREFIX + deviceId + ":" + mobile; } }
repos\SpringAll-master\64.Spring-Security-OAuth2-Customize\src\main\java\cc\mrbird\security\service\RedisCodeService.java
2
请在Spring Boot框架中完成以下Java代码
private boolean isIncluded(String name) { return this.include.isEmpty() || this.include.contains("*") || isIncludedName(name); } private boolean isIncludedName(String name) { if (this.include.contains(name)) { return true; } if (name.contains("/")) { String parent = name.substring(0, name.lastIndexOf("/")); return isIncludedName(parent); } return false; } private boolean isExcluded(String name) { return this.exclude.contains("*") || isExcludedName(name); } private boolean isExcludedName(String name) { if (this.exclude.contains(name)) { return true; } if (name.contains("/")) { String parent = name.substring(0, name.lastIndexOf("/")); return isExcludedName(parent);
} return false; } private Set<String> clean(@Nullable Set<String> names) { if (names == null) { return Collections.emptySet(); } Set<String> cleaned = names.stream().map(this::clean).collect(Collectors.toCollection(LinkedHashSet::new)); return Collections.unmodifiableSet(cleaned); } @Contract("!null -> !null") private @Nullable String clean(@Nullable String name) { return (name != null) ? name.trim() : null; } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\IncludeExcludeGroupMemberPredicate.java
2
请完成以下Java代码
public int getTabNo() { return m_vo.TabNo; } /** * Enable events delaying. * So, from now on, all events will be enqueued instead of directly fired. * Later, when {@link #releaseDelayedEvents()} is called, all enqueued events will be fired. */ public void delayEvents() { m_propertyChangeListeners.blockEvents(); } /** * Fire all enqueued events (if any) and disable events delaying. * * @see #delayEvents(). */ public void releaseDelayedEvents() { m_propertyChangeListeners.releaseEvents(); } @Override public boolean isRecordCopyingMode() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.isDataNewCopy(); } @Override public boolean isRecordCopyingModeIncludingDetails() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.getTableModel().isCopyWithDetails(); }
@Override public void fireDataStatusEEvent(final String AD_Message, final String info, final boolean isError) { final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: AD_Message={}, info={}, isError={}", this, AD_Message, info, isError); return; } gridTab.fireDataStatusEEvent(AD_Message, info, isError); } @Override public void fireDataStatusEEvent(final ValueNamePair errorLog) { final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: errorLog={}", this, errorLog); return; } gridTab.fireDataStatusEEvent(errorLog); } @Override public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id) { throw new UnsupportedOperationException(); } @Override public ICalloutRecord getCalloutRecord() { final GridTab gridTab = getGridTab(); Check.assumeNotNull(gridTab, "gridTab not null"); return gridTab; } @Override public int getContextAsInt(String name) { return Env.getContextAsInt(getCtx(), getWindowNo(), name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridField.java
1
请完成以下Java代码
public class GridTabSummaryInfoFactory implements IGridTabSummaryInfoFactory { private final Map<ArrayKey, IGridTabSummaryInfoProvider> providers = new HashMap<>(); private final IGridTabSummaryInfoProvider defaultProvider = new DefaultGridTabSummaryInfoProvider(); @Override public void register(final String tableName, final IGridTabSummaryInfoProvider summaryInfoProvider) { final boolean forceOverride = false; register(tableName, summaryInfoProvider, forceOverride); } @Override public void register(final String tableName, final IGridTabSummaryInfoProvider summaryInfoProvider, final boolean forceOverride) { Check.assumeNotEmpty(tableName, "tableName not empty"); Check.assumeNotNull(summaryInfoProvider, "summaryInfoProvider not null"); final ArrayKey key = mkKey(tableName); if (!forceOverride && providers.containsKey(key)) { throw new AdempiereException("The provider " + summaryInfoProvider + " is already registered: "); } providers.put(key, summaryInfoProvider); } private ArrayKey mkKey(final String tableName) { return Util.mkKey(tableName); }
@Override public IGridTabSummaryInfoProvider getSummaryInfoProvider(final GridTab gridTab) { Check.assumeNotNull(gridTab, "gridTab not null"); final ArrayKey key = mkKey(gridTab.getTableName()); final IGridTabSummaryInfoProvider provider = providers.get(key); if (provider == null) { return defaultProvider; } return provider; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\api\impl\GridTabSummaryInfoFactory.java
1
请完成以下Java代码
public static boolean equalsByRepoId(final int repoId1, final int repoId2) { final int repoId1Norm = repoId1 > 0 ? repoId1 : -1; final int repoId2Norm = repoId2 > 0 ? repoId2 : -1; return repoId1Norm == repoId2Norm; } private LocatorId(final int repoId, @NonNull final WarehouseId warehouseId) { Check.assumeGreaterThanZero(repoId, "M_Locator_ID"); this.repoId = repoId; this.warehouseId = warehouseId; } @JsonValue public String toJson() { return warehouseId.getRepoId() + "_" + repoId; } @JsonCreator public static LocatorId fromJson(final String json) { final String[] parts = json.split("_"); if (parts.length != 2)
{ throw new IllegalArgumentException("Invalid json: " + json); } final int warehouseId = Integer.parseInt(parts[0]); final int locatorId = Integer.parseInt(parts[1]); return ofRepoId(warehouseId, locatorId); } public void assetWarehouseId(@NonNull final WarehouseId expectedWarehouseId) { if (!WarehouseId.equals(this.warehouseId, expectedWarehouseId)) { throw new AdempiereException("Expected " + expectedWarehouseId + " for " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\LocatorId.java
1
请完成以下Java代码
public Bytes getAttestationObject() { return this.attestationObject; } /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-authenticatorattestationresponse-gettransports">transports</a> * returns the <a href= * "https://www.w3.org/TR/webauthn-3/#dom-authenticatorattestationresponse-transports-slot">transports</a> * @return the transports */ public @Nullable List<AuthenticatorTransport> getTransports() { return this.transports; } /** * Creates a new instance. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public static AuthenticatorAttestationResponseBuilder builder() { return new AuthenticatorAttestationResponseBuilder(); } /** * Builds {@link AuthenticatorAssertionResponse}. * * @author Rob Winch * @since 6.4 */ public static final class AuthenticatorAttestationResponseBuilder { @SuppressWarnings("NullAway.Init") private Bytes attestationObject; private @Nullable List<AuthenticatorTransport> transports; @SuppressWarnings("NullAway.Init") private Bytes clientDataJSON; private AuthenticatorAttestationResponseBuilder() { } /** * Sets the {@link #getAttestationObject()} property. * @param attestationObject the attestation object. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder attestationObject(Bytes attestationObject) { this.attestationObject = attestationObject; return this; }
/** * Sets the {@link #getTransports()} property. * @param transports the transports * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder transports(AuthenticatorTransport... transports) { return transports(Arrays.asList(transports)); } /** * Sets the {@link #getTransports()} property. * @param transports the transports * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder transports(List<AuthenticatorTransport> transports) { this.transports = transports; return this; } /** * Sets the {@link #getClientDataJSON()} property. * @param clientDataJSON the client data JSON. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponseBuilder clientDataJSON(Bytes clientDataJSON) { this.clientDataJSON = clientDataJSON; return this; } /** * Builds a {@link AuthenticatorAssertionResponse}. * @return the {@link AuthenticatorAttestationResponseBuilder} */ public AuthenticatorAttestationResponse build() { return new AuthenticatorAttestationResponse(this.clientDataJSON, this.attestationObject, this.transports); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AuthenticatorAttestationResponse.java
1
请完成以下Java代码
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findApiKeyById(tenantId, new ApiKeyId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(apiKeyDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public void deleteApiKey(TenantId tenantId, ApiKey apiKey, boolean force) { UUID apiKeyId = apiKey.getUuidId(); validateId(apiKeyId, id -> INCORRECT_API_KEY_ID + id); apiKeyDao.removeById(tenantId, apiKeyId); publishEvictEvent(new ApiKeyEvictEvent(apiKey.getValue())); } @Override public void deleteByTenantId(TenantId tenantId) { log.trace("Executing deleteApiKeysByTenantId, tenantId [{}]", tenantId); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); Set<String> values = apiKeyDao.deleteByTenantId(tenantId); values.forEach(value -> publishEvictEvent(new ApiKeyEvictEvent(value))); } @Override public void deleteByUserId(TenantId tenantId, UserId userId) { log.trace("Executing deleteApiKeysByUserId, tenantId [{}]", tenantId); validateId(userId, id -> INCORRECT_USER_ID + id); Set<String> values = apiKeyDao.deleteByUserId(tenantId, userId); values.forEach(value -> publishEvictEvent(new ApiKeyEvictEvent(value))); }
@Override public ApiKey findApiKeyByValue(String value) { log.trace("Executing findApiKeyByValue [{}]", value); var cacheKey = ApiKeyCacheKey.of(value); return cache.getAndPutInTransaction(cacheKey, () -> apiKeyDao.findByValue(value), true); } private String generateApiKeySecret() { return prefix + StringUtils.generateSafeToken(Math.min(valueBytesSize, MAX_API_KEY_VALUE_LENGTH)); } @Override public EntityType getEntityType() { return EntityType.API_KEY; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\pat\ApiKeyServiceImpl.java
1
请完成以下Spring Boot application配置
#server server.port=9000 spring.mvc.servlet.path=/ server.servlet.context-path=/ server.error.whitelabel.enabled=false #spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration #for Spring Boot 2.0+ #spri
ng.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
repos\tutorials-master\spring-boot-modules\spring-boot-basic-customization\src\main\resources\application-errorhandling.properties
2
请完成以下Java代码
public static CommissionPoints sum(@NonNull final Collection<CommissionPoints> augents) { final BigDecimal sum = augents.stream() .map(CommissionPoints::toBigDecimal) .reduce(ONE, BigDecimal::add); return new CommissionPoints(sum); } private CommissionPoints(@NonNull final BigDecimal points) { this.points = points; } @JsonValue public BigDecimal toBigDecimal() { return points; } public CommissionPoints multiply(@NonNull final BigDecimal multiplicant) { if (multiplicant.compareTo(ONE) == 0) { return this; } return new CommissionPoints(points.multiply(multiplicant)); } public CommissionPoints add(@NonNull final CommissionPoints augent) { if (augent.isZero()) { return this; } return CommissionPoints.of(toBigDecimal().add(augent.toBigDecimal())); } public CommissionPoints subtract(@NonNull final CommissionPoints augent) {
if (augent.isZero()) { return this; } return CommissionPoints.of(toBigDecimal().subtract(augent.toBigDecimal())); } @JsonIgnore public boolean isZero() { final boolean isZero = points.signum() == 0; return isZero; } public CommissionPoints computePercentageOf( @NonNull final Percent commissionPercent, final int precision) { final BigDecimal percentagePoints = commissionPercent.computePercentageOf(points, precision); return CommissionPoints.of(percentagePoints); } public CommissionPoints negateIf(final boolean condition) { if (condition) { return CommissionPoints.of(points.negate()); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\CommissionPoints.java
1
请完成以下Java代码
public BooleanWithReason checkEligibleToAddAsSourceHUs(@NonNull final Set<HuId> huIds) { final String notEligibleReason = handlingUnitsBL.getByIds(huIds) .stream() .map(this::checkEligibleToAddAsSourceHU) .filter(BooleanWithReason::isFalse) .map(BooleanWithReason::getReasonAsString) .collect(Collectors.joining(" | ")); return Check.isBlank(notEligibleReason) ? BooleanWithReason.TRUE : BooleanWithReason.falseBecause(notEligibleReason); } @NonNull private BooleanWithReason checkEligibleToAddAsSourceHU(@NonNull final I_M_HU hu) { if (!X_M_HU.HUSTATUS_Active.equals(hu.getHUStatus())) { return BooleanWithReason.falseBecause("HU is not active"); } if (!handlingUnitsBL.isTopLevel(hu)) { return BooleanWithReason.falseBecause("HU is not top level"); } return BooleanWithReason.TRUE; }
public BooleanWithReason checkEligibleToAddToManufacturingOrder(@NonNull final PPOrderId ppOrderId) { final I_PP_Order ppOrder = ppOrderBL.getById(ppOrderId); final DocStatus ppOrderDocStatus = DocStatus.ofNullableCodeOrUnknown(ppOrder.getDocStatus()); if (!ppOrderDocStatus.isCompleted()) { return BooleanWithReason.falseBecause(MSG_ManufacturingOrderNotCompleted, ppOrder.getDocumentNo()); } if (ppOrderIssueScheduleService.matchesByOrderId(ppOrderId)) { return BooleanWithReason.falseBecause(MSG_ManufacturingJobAlreadyStarted, ppOrder.getDocumentNo()); } return BooleanWithReason.TRUE; } @NonNull public ImmutableSet<HuId> getSourceHUIds(@NonNull final PPOrderId ppOrderId) { return ppOrderSourceHURepository.getSourceHUIds(ppOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\source_hu\PPOrderSourceHUService.java
1
请完成以下Java代码
public class ExemptTaxNotFoundException extends AdempiereException { /** * */ private static final long serialVersionUID = -5489066603806460132L; private static final String AD_Message = "TaxNoExemptFound"; public ExemptTaxNotFoundException(int AD_Org_ID) { super(buildMessage(AD_Org_ID)); } private static final String buildMessage(int AD_Org_ID) { StringBuffer msg = new StringBuffer("@").append(AD_Message).append("@"); msg.append("@AD_Org_ID@:").append(getOrgString(AD_Org_ID));
// return msg.toString(); } private static final String getOrgString(int AD_Org_ID) { if (AD_Org_ID <= 0) { return "*"; } return Services.get(IOrgDAO.class).retrieveOrgName(AD_Org_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\ExemptTaxNotFoundException.java
1
请完成以下Java代码
public final class OAuth2TokenClaimsContext implements OAuth2TokenContext { private final Map<Object, Object> context; private OAuth2TokenClaimsContext(Map<Object, Object> context) { this.context = Collections.unmodifiableMap(new HashMap<>(context)); } @SuppressWarnings("unchecked") @Nullable @Override public <V> V get(Object key) { return hasKey(key) ? (V) this.context.get(key) : null; } @Override public boolean hasKey(Object key) { Assert.notNull(key, "key cannot be null"); return this.context.containsKey(key); } /** * Returns the {@link OAuth2TokenClaimsSet.Builder claims} allowing the ability to * add, replace, or remove. * @return the {@link OAuth2TokenClaimsSet.Builder} */ public OAuth2TokenClaimsSet.Builder getClaims() { return get(OAuth2TokenClaimsSet.Builder.class); }
/** * Constructs a new {@link Builder} with the provided claims. * @param claimsBuilder the claims to initialize the builder * @return the {@link Builder} */ public static Builder with(OAuth2TokenClaimsSet.Builder claimsBuilder) { return new Builder(claimsBuilder); } /** * A builder for {@link OAuth2TokenClaimsContext}. */ public static final class Builder extends AbstractBuilder<OAuth2TokenClaimsContext, Builder> { private Builder(OAuth2TokenClaimsSet.Builder claimsBuilder) { Assert.notNull(claimsBuilder, "claimsBuilder cannot be null"); put(OAuth2TokenClaimsSet.Builder.class, claimsBuilder); } /** * Builds a new {@link OAuth2TokenClaimsContext}. * @return the {@link OAuth2TokenClaimsContext} */ @Override public OAuth2TokenClaimsContext build() { return new OAuth2TokenClaimsContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenClaimsContext.java
1
请完成以下Java代码
protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin").password(passwordEncoder().encode("admin123")).roles("ADMIN") .and() .withUser("hamdamboy").password(passwordEncoder().encode("hamdamboy")).roles("USER"); } /** * REST control file and folders, especially using specific * if using ** (double star) that is all files in the existing folder. * **/ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/index").permitAll()
.antMatchers("/profile/**").authenticated() .antMatchers("/admin/**").hasRole("ADMIN") // Admin .antMatchers("/management/**").hasAnyRole("ADMIN", "MANAGER") .antMatchers("/api/public/**").hasRole("ADMIN") // REST condition. // .antMatchers("/api/public/test1").authenticated() // .antMatchers("/api/public/test2").authenticated() .and() .httpBasic(); } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\3. SpringSecureRestControl\src\main\java\spring\security\security\SpringSecurity.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isZero() {return relativeValue.signum() == 0;} public InvoiceTotal subtract(@NonNull final InvoiceTotal other) { if (other.isZero()) {return this;} final Money otherValue = other.withAPAdjusted(isAPAdjusted()).withCMAdjusted(isCMAdjusted()).toMoney(); return ofRelativeValue(this.relativeValue.subtract(otherValue), multiplier); } public InvoiceTotal subtractRealValue(@Nullable final Money realValueToSubtract) { if (realValueToSubtract == null || realValueToSubtract.signum() == 0) { return this; } final Money resultRealValue = toRealValueAsMoney().subtract(realValueToSubtract); final Money resultRelativeValue = multiplier.convertToRelativeValue(resultRealValue); return InvoiceTotal.ofRelativeValue(resultRelativeValue, multiplier); } public Money toMoney() {return relativeValue;} public @NonNull BigDecimal toBigDecimal() {return toMoney().toBigDecimal();} public Money toRealValueAsMoney() {return multiplier.convertToRealValue(relativeValue);} public BigDecimal toRealValueAsBigDecimal() {return toRealValueAsMoney().toBigDecimal();} public boolean isAP() {return multiplier.isAP();} public boolean isAPAdjusted() {return multiplier.isAPAdjusted();} public boolean isCreditMemo() {return multiplier.isCreditMemo();} public boolean isCMAdjusted() {return multiplier.isCreditMemoAdjusted();} public InvoiceTotal withAPAdjusted(final boolean isAPAdjusted) { return isAPAdjusted ? withAPAdjusted() : withoutAPAdjusted(); } public InvoiceTotal withAPAdjusted() { if (multiplier.isAPAdjusted()) { return this; } else if (multiplier.isAP()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withAPAdjusted(true)); } else { return new InvoiceTotal(relativeValue, multiplier.withAPAdjusted(true)); } } public InvoiceTotal withoutAPAdjusted()
{ if (!multiplier.isAPAdjusted()) { return this; } else if (multiplier.isAP()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withAPAdjusted(false)); } else { return new InvoiceTotal(relativeValue, multiplier.withAPAdjusted(false)); } } public InvoiceTotal withCMAdjusted(final boolean isCMAdjusted) { return isCMAdjusted ? withCMAdjusted() : withoutCMAdjusted(); } public InvoiceTotal withCMAdjusted() { if (multiplier.isCreditMemoAdjusted()) { return this; } else if (multiplier.isCreditMemo()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withCMAdjusted(true)); } else { return new InvoiceTotal(relativeValue, multiplier.withCMAdjusted(true)); } } public InvoiceTotal withoutCMAdjusted() { if (!multiplier.isCreditMemoAdjusted()) { return this; } else if (multiplier.isCreditMemo()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withCMAdjusted(false)); } else { return new InvoiceTotal(relativeValue, multiplier.withCMAdjusted(false)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceTotal.java
2
请在Spring Boot框架中完成以下Java代码
public class MongoInsertEventListener extends AbstractMongoEventListener<IncIdEntity> { /** * sequence - 集合名 */ private static final String SEQUENCE_COLLECTION_NAME = "sequence"; /** * sequence - 自增值的字段名 */ private static final String SEQUENCE_FIELD_VALUE = "value"; @Autowired private MongoTemplate mongoTemplate; @Override public void onBeforeConvert(BeforeConvertEvent<IncIdEntity> event) { IncIdEntity entity = event.getSource(); // 判断 id 为空 if (entity.getId() == null) { // 获得下一个编号 Number id = this.getNextId(entity); // 设置到实体中 // noinspection unchecked entity.setId(id); } } /** * 获得实体的下一个主键 ID 编号 * * @param entity 实体对象 * @return ID 编号 */ private Number getNextId(IncIdEntity entity) { // 使用实体名的简单类名,作为 ID 编号 String id = entity.getClass().getSimpleName(); // 创建 Query 对象
Query query = new Query(Criteria.where("_id").is(id)); // 创建 Update 对象 Update update = new Update(); update.inc(SEQUENCE_FIELD_VALUE, 1); // 自增值 // 创建 FindAndModifyOptions 对象 FindAndModifyOptions options = new FindAndModifyOptions(); options.upsert(true); // 如果不存在时,则进行插入 options.returnNew(true); // 返回新值 // 执行操作 @SuppressWarnings("unchecked") HashMap<String, Object> result = mongoTemplate.findAndModify(query, update, options, HashMap.class, SEQUENCE_COLLECTION_NAME); // 返回主键 return (Number) result.get(SEQUENCE_FIELD_VALUE); } }
repos\SpringBoot-Labs-master\lab-16-spring-data-mongo\lab-16-spring-data-mongodb\src\main\java\cn\iocoder\springboot\lab16\springdatamongodb\mongo\MongoInsertEventListener.java
2
请完成以下Java代码
public void setPA_Measure_ID (int PA_Measure_ID) { if (PA_Measure_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID)); } /** Get Measure. @return Concrete Performance Measurement */ public int getPA_Measure_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */
public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Achievement.java
1
请完成以下Java代码
public void hyperlinkUpdate( HyperlinkEvent event ) { if( event.getEventType() == HyperlinkEvent.EventType.ACTIVATED ) { //System.out.println("parsed url: " + event.getURL());// +" from: " +event.getDescription()); htmlUpdate(event.getURL()); } } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */ @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { popupMenu.show((Component)e.getSource(), e.getX(), e.getY()); } } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent) */ @Override public void mouseEntered(MouseEvent e) { } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent) */ @Override public void mouseExited(MouseEvent e) { } /* (non-Javadoc) * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent) */ @Override public void mousePressed(MouseEvent e) { } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) */ @Override public void mouseReleased(MouseEvent e) { } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == mRefresh) { if (m_goals != null) { for (MGoal m_goal : m_goals) { m_goal.updateGoal(true); } } htmlUpdate(lastUrl); Container parent = getParent(); if (parent != null) { parent.invalidate(); } invalidate(); if (parent != null) { parent.repaint(); } else { repaint(); } } } class PageLoader implements Runnable { private JEditorPane html; private URL url; private Cursor cursor;
PageLoader( JEditorPane html, URL url, Cursor cursor ) { this.html = html; this.url = url; this.cursor = cursor; } @Override public void run() { if( url == null ) { // restore the original cursor html.setCursor( cursor ); // PENDING(prinz) remove this hack when // automatic validation is activated. Container parent = html.getParent(); parent.repaint(); } else { Document doc = html.getDocument(); try { html.setPage( url ); } catch( IOException ioe ) { html.setDocument( doc ); } finally { // schedule the cursor to revert after // the paint has happended. url = null; SwingUtilities.invokeLater( this ); } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\HtmlDashboard.java
1
请完成以下Java代码
final class TOTPUtils { public static boolean validate(@NonNull final SecretKey secretKey, @NonNull final OTP otp) {return validate(getStep(), secretKey, otp);} private static boolean validate(final long step, @NonNull final SecretKey secretKey, @NonNull final OTP otp) { return OTP.equals(computeOTP(step, secretKey), otp) || OTP.equals(computeOTP(step - 1, secretKey), otp); } private static long getStep() { // 30 seconds StepSize (ID TOTP) return SystemTime.millis() / 30000; } private static OTP computeOTP(final long step, @NonNull final SecretKey secretKey) { String steps = Long.toHexString(step).toUpperCase(); while (steps.length() < 16) { steps = "0" + steps; } // Get the HEX in a Byte[] final byte[] msg = hexStr2Bytes(steps); final byte[] k = hexStr2Bytes(secretKey.toHexString()); final byte[] hash = hmac_sha1(k, msg); // put selected bytes into result int final int offset = hash[hash.length - 1] & 0xf; final int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); final int otp = binary % 1000000; String result = Integer.toString(otp); while (result.length() < 6) { result = "0" + result; } return OTP.ofString(result); } /** * @return hex string converted to byte array */
private static byte[] hexStr2Bytes(final CharSequence hex) { // Adding one byte to get the right conversion // values starting with "0" can be converted final byte[] bArray = new BigInteger("10" + hex, 16).toByteArray(); final byte[] ret = new byte[bArray.length - 1]; // Copy all the REAL bytes, not the "first" System.arraycopy(bArray, 1, ret, 0, ret.length); return ret; } /** * This method uses the JCE to provide the crypto algorithm. HMAC computes a Hashed Message Authentication Code with the crypto hash * algorithm as a parameter. * * @param keyBytes the bytes to use for the HMAC key * @param text the message or text to be authenticated. */ private static byte[] hmac_sha1(final byte[] keyBytes, final byte[] text) { try { final Mac hmac = Mac.getInstance("HmacSHA1"); final SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); hmac.init(macKey); return hmac.doFinal(text); } catch (final GeneralSecurityException gse) { throw new UndeclaredThrowableException(gse); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\totp\TOTPUtils.java
1
请完成以下Java代码
public BigDecimal getPages() { return pages; } public void setPages(BigDecimal pages) { this.pages = pages; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; }
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\deserialization\jsondeserialize\Book.java
1
请完成以下Java代码
public TaskCompletionBuilder transientVariableLocal(String variableName, Object variableValue) { if (this.transientVariablesLocal == null) { this.transientVariablesLocal = new HashMap<>(); } this.transientVariablesLocal.put(variableName, variableValue); return this; } @Override public TaskCompletionBuilder taskId(String id) { this.taskId = id; return this; } @Override public TaskCompletionBuilder formDefinitionId(String formDefinitionId) { this.formDefinitionId = formDefinitionId; return this; } @Override public TaskCompletionBuilder outcome(String outcome) { this.outcome = outcome; return this; }
protected void completeTask() { this.commandExecutor.execute(new CompleteTaskCmd(this.taskId, variables, variablesLocal, transientVariables, transientVariablesLocal)); } protected void completeTaskWithForm() { this.commandExecutor.execute(new CompleteTaskWithFormCmd(this.taskId, formDefinitionId, outcome, variables, variablesLocal, transientVariables, transientVariablesLocal)); } @Override public void complete() { if (this.formDefinitionId != null) { completeTaskWithForm(); } else { completeTask(); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\task\TaskCompletionBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getScopeId() { return job.getScopeId(); } @Override public String getSubScopeId() { return job.getSubScopeId(); } @Override public String getScopeType() { return job.getScopeType(); } @Override public String getScopeDefinitionId() { return job.getScopeDefinitionId(); } @Override public String getCorrelationId() { return job.getCorrelationId(); } @Override public boolean isExclusive() { return job.isExclusive(); } @Override public Date getCreateTime() { return job.getCreateTime(); } @Override public String getId() { return job.getId(); } @Override public int getRetries() { return job.getRetries(); } @Override public String getExceptionMessage() { return job.getExceptionMessage(); } @Override public String getTenantId() { return job.getTenantId(); } @Override
public String getJobHandlerType() { return job.getJobHandlerType(); } @Override public String getJobHandlerConfiguration() { return job.getJobHandlerConfiguration(); } @Override public String getCustomValues() { return job.getCustomValues(); } @Override public String getLockOwner() { return job.getLockOwner(); } @Override public Date getLockExpirationTime() { return job.getLockExpirationTime(); } @Override public String toString() { return new StringJoiner(", ", AcquiredExternalWorkerJobImpl.class.getSimpleName() + "[", "]") .add("job=" + job) .toString(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\AcquiredExternalWorkerJobImpl.java
2
请完成以下Java代码
public int getC_Location_ID() { return get_ValueAsInt(COLUMNNAME_C_Location_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setESR_PostBank (final boolean ESR_PostBank) { set_Value (COLUMNNAME_ESR_PostBank, ESR_PostBank); } @Override public boolean isESR_PostBank() { return get_ValueAsBoolean(COLUMNNAME_ESR_PostBank); } @Override public void setIsCashBank (final boolean IsCashBank) { set_Value (COLUMNNAME_IsCashBank, IsCashBank); } @Override public boolean isCashBank() { return get_ValueAsBoolean(COLUMNNAME_IsCashBank); } @Override public void setIsImportAsSingleSummaryLine (final boolean IsImportAsSingleSummaryLine) { set_Value (COLUMNNAME_IsImportAsSingleSummaryLine, IsImportAsSingleSummaryLine); } @Override public boolean isImportAsSingleSummaryLine() { return get_ValueAsBoolean(COLUMNNAME_IsImportAsSingleSummaryLine); } @Override public void setIsOwnBank (final boolean IsOwnBank) {
set_Value (COLUMNNAME_IsOwnBank, IsOwnBank); } @Override public boolean isOwnBank() { return get_ValueAsBoolean(COLUMNNAME_IsOwnBank); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setRoutingNo (final java.lang.String RoutingNo) { set_Value (COLUMNNAME_RoutingNo, RoutingNo); } @Override public java.lang.String getRoutingNo() { return get_ValueAsString(COLUMNNAME_RoutingNo); } @Override public void setSwiftCode (final @Nullable java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } @Override public java.lang.String getSwiftCode() { return get_ValueAsString(COLUMNNAME_SwiftCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Bank.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public Article getArticle() { return article; }
public void setArticle(Article article) { this.article = article; } public Magazine getMagazine() { return magazine; } public void setMagazine(Magazine magazine) { this.magazine = magazine; } @Override public String toString() { return "Review{" + "id=" + id + ", content=" + content + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootChooseOnlyOneAssociation\src\main\java\com\bookstore\entity\Review.java
1
请在Spring Boot框架中完成以下Java代码
public static class KubernetesConverterConfiguration { @Bean @ConfigurationProperties(prefix = "spring.boot.admin.discovery.converter") public KubernetesServiceInstanceConverter serviceInstanceConverter( KubernetesDiscoveryProperties discoveryProperties) { return new KubernetesServiceInstanceConverter(discoveryProperties); } } private static class KubernetesDiscoveryClientCondition extends AnyNestedCondition { KubernetesDiscoveryClientCondition() { super(ConfigurationPhase.REGISTER_BEAN);
} @ConditionalOnBean(KubernetesInformerDiscoveryClient.class) static class OfficialKubernetesCondition { } @ConditionalOnBean(KubernetesDiscoveryClient.class) static class Fabric8KubernetesCondition { } } }
repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\config\AdminServerDiscoveryAutoConfiguration.java
2
请完成以下Java代码
public abstract class AbstractSyncSessionCallback implements SessionMsgListener { protected final TbCoapClientState state; protected final CoapExchange exchange; protected final Request request; @Override public void onGetAttributesResponse(TransportProtos.GetAttributeResponseMsg getAttributesResponse) { logUnsupportedCommandMessage(getAttributesResponse); } @Override public void onAttributeUpdate(UUID sessionId, TransportProtos.AttributeUpdateNotificationMsg attributeUpdateNotification) { logUnsupportedCommandMessage(attributeUpdateNotification); } @Override public void onRemoteSessionCloseCommand(UUID sessionId, TransportProtos.SessionCloseNotificationProto sessionCloseNotification) { } @Override public void onDeviceDeleted(DeviceId deviceId) { } @Override public void onToDeviceRpcRequest(UUID sessionId, TransportProtos.ToDeviceRpcRequestMsg toDeviceRequest) { logUnsupportedCommandMessage(toDeviceRequest); } @Override public void onToServerRpcResponse(TransportProtos.ToServerRpcResponseMsg toServerResponse) { logUnsupportedCommandMessage(toServerResponse); } private void logUnsupportedCommandMessage(Object update) { log.trace("[{}] Ignore unsupported update: {}", state.getDeviceId(), update); } public static boolean isConRequest(TbCoapObservationState state) {
if (state != null) { return state.getExchange().advanced().getRequest().isConfirmable(); } else { return false; } } public static boolean isMulticastRequest(TbCoapObservationState state) { if (state != null) { return state.getExchange().advanced().getRequest().isMulticast(); } return false; } protected void respond(Response response) { response.getOptions().setContentFormat(TbCoapContentFormatUtil.getContentFormat(exchange.getRequestOptions().getContentFormat(), state.getContentFormat())); response.setConfirmable(exchange.advanced().getRequest().isConfirmable()); exchange.respond(response); } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\callback\AbstractSyncSessionCallback.java
1
请完成以下Java代码
public void stringBadPractice3() { synchronized (internedStringLock) { // ... } } private final Boolean booleanLock = Boolean.FALSE; public void booleanBadPractice() { synchronized (booleanLock) { // ... } } private int count = 0; private final Integer intLock = count; public void boxedPrimitiveBadPractice() { synchronized (intLock) {
count++; // ... } } public void classBadPractice() throws InterruptedException { AnimalBadPractice animalObj = new AnimalBadPractice("Tommy", "John"); synchronized(animalObj) { while (true) { Thread.sleep(Integer.MAX_VALUE); } } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-4\src\main\java\com\baeldung\synchronizationbadpractices\SynchronizationBadPracticeExample.java
1
请在Spring Boot框架中完成以下Java代码
ClientRegistrationRepository dynamicClientRegistrationRepository( DynamicClientRegistrationRepository.RegistrationRestTemplate restTemplate) { log.info("Creating a dynamic client registration repository"); var registrationDetails = new DynamicClientRegistrationRepository.RegistrationDetails( registrationProperties.getRegistrationEndpoint(), registrationProperties.getRegistrationUsername(), registrationProperties.getRegistrationPassword(), registrationProperties.getRegistrationScopes(), registrationProperties.getGrantTypes(), registrationProperties.getRedirectUris(), registrationProperties.getTokenEndpoint()); // Use standard client registrations as Map<String,ClientRegistration> staticClients = (new OAuth2ClientPropertiesMapper(clientProperties)).asClientRegistrations(); var repo = new DynamicClientRegistrationRepository(registrationDetails, staticClients, restTemplate); repo.doRegistrations(); return repo; } @Bean DynamicClientRegistrationRepository.RegistrationRestTemplate registrationRestTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder.build(DynamicClientRegistrationRepository.RegistrationRestTemplate.class); } // As of Spring Boot 3.2, we could use a record instead of a class. @ConfigurationProperties(prefix = "baeldung.security.client.registration") @Getter @Setter public static final class RegistrationProperties { URI registrationEndpoint; String registrationUsername; String registrationPassword;
List<String> registrationScopes; List<String> grantTypes; List<String> redirectUris; URI tokenEndpoint; } @Bean public OAuth2AuthorizationRequestResolver pkceResolver(ClientRegistrationRepository repo) { var resolver = new DefaultOAuth2AuthorizationRequestResolver(repo, "/oauth2/authorization"); resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce()); return resolver; } @Bean SecurityFilterChain oauth2SecurityFilterChain(HttpSecurity http, OAuth2AuthorizationRequestResolver resolver) throws Exception { http.authorizeHttpRequests((requests) -> { requests.anyRequest().authenticated(); }); http.oauth2Login(a -> a.authorizationEndpoint(c -> c.authorizationRequestResolver(resolver))) ; http.oauth2Client(Customizer.withDefaults()); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-dynamic-client\src\main\java\com\baeldung\spring\security\dynreg\client\config\OAuth2DynamicClientConfiguration.java
2
请完成以下Java代码
public int getM_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Merkmals-Wert. @param M_AttributeValue_ID Product Attribute Value */ @Override public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.pricing.attributebased.I_M_ProductPrice_Attribute getM_ProductPrice_Attribute() { return get_ValueAsPO(COLUMNNAME_M_ProductPrice_Attribute_ID, de.metas.pricing.attributebased.I_M_ProductPrice_Attribute.class); } @Override public void setM_ProductPrice_Attribute(de.metas.pricing.attributebased.I_M_ProductPrice_Attribute M_ProductPrice_Attribute) { set_ValueFromPO(COLUMNNAME_M_ProductPrice_Attribute_ID, de.metas.pricing.attributebased.I_M_ProductPrice_Attribute.class, M_ProductPrice_Attribute); } /** Set Attribute price. @param M_ProductPrice_Attribute_ID Attribute price */ @Override public void setM_ProductPrice_Attribute_ID (int M_ProductPrice_Attribute_ID) { if (M_ProductPrice_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_ID, Integer.valueOf(M_ProductPrice_Attribute_ID)); }
/** Get Attribute price. @return Attribute price */ @Override public int getM_ProductPrice_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Attribute price line. @param M_ProductPrice_Attribute_Line_ID Attribute price line */ @Override public void setM_ProductPrice_Attribute_Line_ID (int M_ProductPrice_Attribute_Line_ID) { if (M_ProductPrice_Attribute_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_Attribute_Line_ID, Integer.valueOf(M_ProductPrice_Attribute_Line_ID)); } /** Get Attribute price line. @return Attribute price line */ @Override public int getM_ProductPrice_Attribute_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_Attribute_Line_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\pricing\attributebased\X_M_ProductPrice_Attribute_Line.java
1
请完成以下Java代码
public int getM_Product_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Training. @param S_Training_ID Repeated Training */ public void setS_Training_ID (int S_Training_ID) { if (S_Training_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID)); } /** Get Training. @return Repeated Training */ public int getS_Training_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_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_S_Training.java
1
请在Spring Boot框架中完成以下Java代码
public long listSize(String key) { return listOperations.size(key); } public Object listIndex(String key, long index) { return listOperations.index(key, index); } public void listRightPush(String key, Object value) { listOperations.rightPush(key, value); } public boolean listRightPush(String key, Object value, long milliseconds) { listOperations.rightPush(key, value); if (milliseconds > 0) { return expire(key, milliseconds); } return false; } public long listRightPushAll(String key, List<Object> value) { return listOperations.rightPushAll(key, value); } public boolean listRightPushAll(String key, List<Object> value, long milliseconds) { listOperations.rightPushAll(key, value); if (milliseconds > 0) {
return expire(key, milliseconds); } return false; } public void listSet(String key, long index, Object value) { listOperations.set(key, index, value); } public long listRemove(String key, long count, Object value) { return listOperations.remove(key, count, value); } //===============================zset================================= public boolean zsAdd(String key, Object value, double score) { return zSetOperations.add(key, value, score); } }
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisOptService.java
2
请在Spring Boot框架中完成以下Java代码
public RelyingPartyRegistration convert(HttpServletRequest request) { return resolve(request, null); } /** * {@inheritDoc} */ @Override public RelyingPartyRegistration resolve(HttpServletRequest request, String relyingPartyRegistrationId) { if (relyingPartyRegistrationId == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("Attempting to resolve from " + this.registrationRequestMatcher + " since registrationId is null"); } relyingPartyRegistrationId = this.registrationRequestMatcher.matcher(request) .getVariables() .get("registrationId"); } if (relyingPartyRegistrationId == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("Returning null registration since registrationId is null"); }
return null; } RelyingPartyRegistration registration = this.relyingPartyRegistrationRepository .findByRegistrationId(relyingPartyRegistrationId); if (registration == null) { return null; } UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); return registration.mutate() .entityId(uriResolver.resolve(registration.getEntityId())) .assertionConsumerServiceLocation(uriResolver.resolve(registration.getAssertionConsumerServiceLocation())) .singleLogoutServiceLocation(uriResolver.resolve(registration.getSingleLogoutServiceLocation())) .singleLogoutServiceResponseLocation( uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation())) .build(); } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\DefaultRelyingPartyRegistrationResolver.java
2
请完成以下Java代码
public class SqlOptions { /** * advice the SQL code generators to use table alias (e.g. "master") instead of fully qualified table name */ public static SqlOptions usingTableAlias(@NonNull final String sqlTableAlias) { if (USE_TABLE_ALIAS_MASTER.tableAlias.equals(sqlTableAlias)) { return USE_TABLE_ALIAS_MASTER; } return builder() .useTableAlias(true) .tableAlias(sqlTableAlias) .build(); } /** * advice the SQL code generators to use fully qualified table name instead of table alias */ public static SqlOptions usingTableName(final String tableName) { return SqlOptions.builder() .useTableAlias(false) .tableName(tableName) .build(); } private static final SqlOptions USE_TABLE_ALIAS_MASTER = SqlOptions.builder().useTableAlias(true).tableAlias("master").build(); private final boolean useTableAlias; private final String tableAlias; private final String tableName; @Builder private SqlOptions( final boolean useTableAlias, final String tableAlias, final String tableName) {
this.useTableAlias = useTableAlias; if (useTableAlias) { Check.assumeNotEmpty(tableAlias, "tableAlias is not empty"); this.tableAlias = tableAlias; this.tableName = null; } else { Check.assumeNotEmpty(tableName, "tableName is not empty"); this.tableAlias = null; this.tableName = tableName; } } public boolean isUseTableAlias() { return useTableAlias; } public String getTableAlias() { if (!useTableAlias) { throw new AdempiereException("tableAlias is not available for " + this); } return tableAlias; } public String getTableNameOrAlias() { return useTableAlias ? tableAlias : tableName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlOptions.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public ZonedDateTime getBirthDate() {
return birthDate; } public void setBirthDate(ZonedDateTime birthDate) { this.birthDate = birthDate; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\simple\model\User.java
1
请完成以下Java代码
protected String doIt() { final Duration duration = getDuration(); if (duration.isNegative() || duration.isZero()) { throw new FillMandatoryException("Duration"); } final PPOrderRoutingActivityId orderRoutingActivityId = getOrderRoutingActivityId(); final PPOrderId orderId = orderRoutingActivityId.getOrderId(); checkPreconditionsApplicable(orderId); final I_PP_Order order = getOrderById(orderId); final UomId finishedGoodsUomId = UomId.ofRepoId(order.getC_UOM_ID()); final PPOrderRoutingActivity orderRoutingActivity = orderRoutingRepository.getOrderRoutingActivity(orderRoutingActivityId); costCollectorBL.createActivityControl(ActivityControlCreateRequest.builder() .order(order) .orderActivity(orderRoutingActivity) .movementDate(SystemTime.asZonedDateTime()) .qtyMoved(Quantitys.zero(finishedGoodsUomId)) .durationSetup(Duration.ZERO) .duration(duration) .build()); return MSG_OK; }
private I_PP_Order getOrderById(@NonNull final PPOrderId orderId) { return ordersCache.computeIfAbsent(orderId, orderBL::getById); } private PPOrderRoutingActivityId getOrderRoutingActivityId() { return PPOrderRoutingActivityId.ofRepoId(getOrderId(), orderRoutingActivityRepoId); } private PPOrderId getOrderId() { return PPOrderId.ofRepoId(getRecord_ID()); } private Duration getDuration() { return DurationUtils.toWorkDurationRoundUp(duration, durationUnit.getTemporalUnit()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\PP_Order_RecordWork.java
1
请完成以下Java代码
protected final void revokeAccessFromRecord() { final boolean revokeAllPermissions; final List<Access> permissionsToRevoke; final Access permission = getPermissionOrNull(); if (permission == null) { revokeAllPermissions = true; permissionsToRevoke = ImmutableList.of(); } else { revokeAllPermissions = false; permissionsToRevoke = ImmutableList.of(permission); } userGroupRecordAccessService.revokeAccess(RecordAccessRevokeRequest.builder() .recordRef(getRecordRef()) .principal(getPrincipal()) .revokeAllPermissions(revokeAllPermissions) .permissions(permissionsToRevoke) .issuer(PermissionIssuer.MANUAL) .requestedBy(getUserId()) .build()); } private Principal getPrincipal() { final PrincipalType principalType = PrincipalType.ofCode(principalTypeCode); if (PrincipalType.USER.equals(principalType)) { return Principal.userId(userId); } else if (PrincipalType.USER_GROUP.equals(principalType)) { return Principal.userGroupId(userGroupId); } else { throw new AdempiereException("@Unknown@ @PrincipalType@: " + principalType); } } private Set<Access> getPermissionsToGrant() { final Access permission = getPermissionOrNull(); if (permission == null) { throw new FillMandatoryException(PARAM_PermissionCode); }
if (Access.WRITE.equals(permission)) { return ImmutableSet.of(Access.READ, Access.WRITE); } else { return ImmutableSet.of(permission); } } private Access getPermissionOrNull() { if (Check.isEmpty(permissionCode)) { return null; } else { return Access.ofCode(permissionCode); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\process\UserGroupRecordAccess_Base.java
1
请在Spring Boot框架中完成以下Java代码
private int resolveDatabase() { if (ClassUtils.isPresent("io.lettuce.core.RedisClient", null) && getRedisConnectionFactory() instanceof LettuceConnectionFactory) { return ((LettuceConnectionFactory) getRedisConnectionFactory()).getDatabase(); } if (ClassUtils.isPresent("redis.clients.jedis.Jedis", null) && getRedisConnectionFactory() instanceof JedisConnectionFactory) { return ((JedisConnectionFactory) getRedisConnectionFactory()).getDatabase(); } return RedisIndexedSessionRepository.DEFAULT_DATABASE; } @Autowired(required = false) public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } /** * Ensures that Redis is configured to send keyspace notifications. This is important * to ensure that expiration and deletion of sessions trigger SessionDestroyedEvents. * Without the SessionDestroyedEvent resources may not get cleaned up properly. For * example, the mapping of the Session to WebSocket connections may not get cleaned * up. */ static class EnableRedisKeyspaceNotificationsInitializer implements InitializingBean { private final RedisConnectionFactory connectionFactory; private final ConfigureRedisAction configure; EnableRedisKeyspaceNotificationsInitializer(RedisConnectionFactory connectionFactory, ConfigureRedisAction configure) { this.connectionFactory = connectionFactory;
this.configure = configure; } @Override public void afterPropertiesSet() { if (this.configure == ConfigureRedisAction.NO_OP) { return; } RedisConnection connection = this.connectionFactory.getConnection(); try { this.configure.configure(connection); } finally { try { connection.close(); } catch (Exception ex) { LogFactory.getLog(getClass()).error("Error closing RedisConnection", ex); } } } } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\RedisIndexedHttpSessionConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class MediatedCommissionConfig implements CommissionConfig { @NonNull Percent commissionPercent; @NonNull ProductId commissionProductId; @NonNull Integer pointsPrecision; @NonNull MediatedCommissionContract mediatedCommissionContract; @NonNull MediatedCommissionSettingsLineId mediatedCommissionSettingsLineId; @NonNull public static MediatedCommissionConfig cast(@NonNull final CommissionConfig commissionConfig) { return castOrEmpty(commissionConfig) .orElseThrow(() -> new AdempiereException("Cannot cast the given config to MediatedCommissionConfig") .appendParametersToMessage() .setParameter("config", commissionConfig)); } @NonNull public static Optional<MediatedCommissionConfig> castOrEmpty(@NonNull final CommissionConfig commissionConfig) { if (commissionConfig instanceof MediatedCommissionConfig) { return Optional.of((MediatedCommissionConfig)commissionConfig); } return Optional.empty(); } public static boolean isInstance(@NonNull final CommissionConfig commissionConfig) { return commissionConfig instanceof MediatedCommissionConfig; } @Override @NonNull public CommissionType getCommissionType() { return CommissionType.MEDIATED_COMMISSION;
} @Override public MediatedCommissionContract getContractFor(@NonNull final BPartnerId contractualBPartnerId) { if (contractualBPartnerId.equals(mediatedCommissionContract.getContractOwnerBPartnerId())) { return mediatedCommissionContract; } return null; } @Override @NonNull public ProductId getCommissionProductId() { return commissionProductId; } @NonNull public MediatedCommissionSettingsId getId() { return mediatedCommissionSettingsLineId.getMediatedCommissionSettingsId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\mediated\algorithm\MediatedCommissionConfig.java
2
请在Spring Boot框架中完成以下Java代码
public String getInternalProxies() { return this.internalProxies; } public void setInternalProxies(String internalProxies) { this.internalProxies = internalProxies; } public @Nullable String getProtocolHeader() { return this.protocolHeader; } public void setProtocolHeader(@Nullable String protocolHeader) { this.protocolHeader = protocolHeader; } public String getProtocolHeaderHttpsValue() { return this.protocolHeaderHttpsValue; } public String getHostHeader() { return this.hostHeader; } public void setHostHeader(String hostHeader) { this.hostHeader = hostHeader; } public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) { this.protocolHeaderHttpsValue = protocolHeaderHttpsValue; } public String getPortHeader() { return this.portHeader; } public void setPortHeader(String portHeader) { this.portHeader = portHeader; } public @Nullable String getRemoteIpHeader() { return this.remoteIpHeader; } public void setRemoteIpHeader(@Nullable String remoteIpHeader) { this.remoteIpHeader = remoteIpHeader;
} public @Nullable String getTrustedProxies() { return this.trustedProxies; } public void setTrustedProxies(@Nullable String trustedProxies) { this.trustedProxies = trustedProxies; } } /** * When to use APR. */ public enum UseApr { /** * Always use APR and fail if it's not available. */ ALWAYS, /** * Use APR if it is available. */ WHEN_AVAILABLE, /** * Never use APR. */ NEVER } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\autoconfigure\TomcatServerProperties.java
2
请完成以下Java代码
public List<CostElement> getByClientId(@NonNull final ClientId clientId) { return getIndexedCostElements() .streamByClientId(clientId) .collect(ImmutableList.toImmutableList()); } @Override public Set<CostElementId> getIdsByClientId(@NonNull final ClientId clientId) { return getIndexedCostElements() .streamByClientId(clientId) .map(CostElement::getId) .collect(ImmutableSet.toImmutableSet()); } @Override public Set<CostElementId> getIdsByCostingMethod(@NonNull final CostingMethod costingMethod) { final ClientId clientId = ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx())); return getIndexedCostElements() .streamByClientIdAndCostingMethod(clientId, costingMethod) .map(CostElement::getId) .collect(ImmutableSet.toImmutableSet()); } @Override public List<CostElement> getMaterialCostingElementsForCostingMethod(@NonNull final CostingMethod costingMethod) { final ClientId clientId = ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx())); return getIndexedCostElements() .streamByClientId(clientId) .filter(ce -> ce.isMaterialCostingMethod(costingMethod)) .collect(ImmutableList.toImmutableList()); } @Override public List<CostElement> getActiveMaterialCostingElements(@NonNull final ClientId clientId) { return getIndexedCostElements() .streamByClientId(clientId) .filter(CostElement::isMaterial) .collect(ImmutableList.toImmutableList()); } @Override public Set<CostElementId> getActiveCostElementIds() { return getIndexedCostElements() .stream() .map(CostElement::getId) .collect(ImmutableSet.toImmutableSet()); } private Stream<CostElement> streamByCostingMethod(@NonNull final CostingMethod costingMethod) { final ClientId clientId = ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx()));
return getIndexedCostElements() .streamByClientId(clientId) .filter(ce -> ce.getCostingMethod() == costingMethod); } private static class IndexedCostElements { private final ImmutableMap<CostElementId, CostElement> costElementsById; private IndexedCostElements(final Collection<CostElement> costElements) { costElementsById = Maps.uniqueIndex(costElements, CostElement::getId); } public Optional<CostElement> getById(final CostElementId id) { return Optional.ofNullable(costElementsById.get(id)); } public Stream<CostElement> streamByClientId(@NonNull final ClientId clientId) { return stream().filter(ce -> ClientId.equals(ce.getClientId(), clientId)); } public Stream<CostElement> streamByClientIdAndCostingMethod(@NonNull final ClientId clientId, @NonNull final CostingMethod costingMethod) { return streamByClientId(clientId).filter(ce -> costingMethod.equals(ce.getCostingMethod())); } public Stream<CostElement> stream() { return costElementsById.values().stream(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CostElementRepository.java
1
请完成以下Java代码
protected CaseInstanceBatchMigrationResult convertFromBatch(Batch batch, ObjectMapper objectMapper) { CaseInstanceBatchMigrationResult result = new CaseInstanceBatchMigrationResult(); result.setBatchId(batch.getId()); result.setSourceCaseDefinitionId(batch.getBatchSearchKey()); result.setTargetCaseDefinitionId(batch.getBatchSearchKey2()); result.setStatus(batch.getStatus()); result.setCompleteTime(batch.getCompleteTime()); return result; } protected CaseInstanceBatchMigrationPartResult convertFromBatchPart(BatchPart batchPart, ObjectMapper objectMapper, CmmnEngineConfiguration engineConfiguration) { CaseInstanceBatchMigrationPartResult partResult = new CaseInstanceBatchMigrationPartResult(); partResult.setBatchId(batchPart.getId()); partResult.setCaseInstanceId(batchPart.getScopeId()); partResult.setSourceCaseDefinitionId(batchPart.getBatchSearchKey()); partResult.setTargetCaseDefinitionId(batchPart.getBatchSearchKey2()); if (batchPart.getCompleteTime() != null) { partResult.setStatus(CaseInstanceBatchMigrationResult.STATUS_COMPLETED); } partResult.setResult(batchPart.getStatus()); if (CaseInstanceBatchMigrationResult.RESULT_FAIL.equals(batchPart.getStatus()) && batchPart.getResultDocumentJson(engineConfiguration.getEngineCfgKey()) != null) { try { JsonNode resultNode = objectMapper.readTree(batchPart.getResultDocumentJson(engineConfiguration.getEngineCfgKey())); if (resultNode.has(BATCH_RESULT_MESSAGE_LABEL)) { String resultMessage = resultNode.get(BATCH_RESULT_MESSAGE_LABEL).asString(); partResult.setMigrationMessage(resultMessage);
} if (resultNode.has(BATCH_RESULT_STACKTRACE_LABEL)) { String resultStacktrace = resultNode.get(BATCH_RESULT_STACKTRACE_LABEL).asString(); partResult.setMigrationStacktrace(resultStacktrace); } } catch (JacksonException e) { throw new FlowableException("Error reading batch part " + batchPart.getId()); } } return partResult; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetCaseInstanceMigrationBatchResultCmd.java
1
请完成以下Java代码
public static class JSONDisplayQRCodeAction extends JSONResultAction { private final String code; protected JSONDisplayQRCodeAction(@NonNull final String code) { super("displayQRCode"); this.code = code; } } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Getter public static class JSONNewRecordAction extends JSONResultAction { @NonNull private final WindowId windowId; @NonNull private final Map<String, String> fieldValues; @NonNull private final String targetTab;
public JSONNewRecordAction( @NonNull final WindowId windowId, @Nullable final Map<String, String> fieldValues, @NonNull final ProcessExecutionResult.WebuiNewRecord.TargetTab targetTab) { super("newRecord"); this.windowId = windowId; this.fieldValues = fieldValues != null && !fieldValues.isEmpty() ? new HashMap<>(fieldValues) : ImmutableMap.of(); this.targetTab = targetTab.name(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONProcessInstanceResult.java
1
请完成以下Java代码
public void setValues(Activity otherActivity) { super.setValues(otherActivity); setFailedJobRetryTimeCycleValue(otherActivity.getFailedJobRetryTimeCycleValue()); setDefaultFlow(otherActivity.getDefaultFlow()); setForCompensation(otherActivity.isForCompensation()); if (otherActivity.getLoopCharacteristics() != null) { setLoopCharacteristics(otherActivity.getLoopCharacteristics().clone()); } if (otherActivity.getIoSpecification() != null) { setIoSpecification(otherActivity.getIoSpecification().clone()); } dataInputAssociations = new ArrayList<DataAssociation>(); if (otherActivity.getDataInputAssociations() != null && !otherActivity.getDataInputAssociations().isEmpty()) { for (DataAssociation association : otherActivity.getDataInputAssociations()) { dataInputAssociations.add(association.clone());
} } dataOutputAssociations = new ArrayList<DataAssociation>(); if (otherActivity.getDataOutputAssociations() != null && !otherActivity.getDataOutputAssociations().isEmpty()) { for (DataAssociation association : otherActivity.getDataOutputAssociations()) { dataOutputAssociations.add(association.clone()); } } boundaryEvents.clear(); for (BoundaryEvent event : otherActivity.getBoundaryEvents()) { boundaryEvents.add(event); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Activity.java
1
请完成以下Java代码
public String getUsername() { return this.environment.getUsername(); } @Override public @Nullable String getPassword() { return this.environment.getPassword(); } @Override public String getJdbcUrl() { return this.jdbcUrl; } private static String addApplicationNameIfNecessary(String jdbcUrl, Environment environment) { if (jdbcUrl.contains("&ApplicationName=") || jdbcUrl.contains("?ApplicationName=")) { return jdbcUrl; } String applicationName = environment.getProperty("spring.application.name"); if (!StringUtils.hasText(applicationName)) { return jdbcUrl; }
StringBuilder jdbcUrlBuilder = new StringBuilder(jdbcUrl); if (!jdbcUrl.contains("?")) { jdbcUrlBuilder.append("?"); } else if (!jdbcUrl.endsWith("&")) { jdbcUrlBuilder.append("&"); } return jdbcUrlBuilder.append("ApplicationName") .append('=') .append(URLEncoder.encode(applicationName, StandardCharsets.UTF_8)) .toString(); } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\PostgresJdbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public Set<K> keySet() { return cache.asMap().keySet(); } // keySet /** * @see java.util.Map#size() */ @Override public long size() { return cache.size(); } // size /** * @see java.util.Map#values() */ public Collection<V> values() { return cache.asMap().values(); } // values @Override protected final void finalize() throws Throwable { // NOTE: to avoid memory leaks we need to programatically clear our internal state try (final IAutoCloseable ignored = CacheMDC.putCache(this)) { logger.debug("Running finalize");
cache.invalidateAll(); } } public CCacheStats stats() { final CacheStats guavaStats = cache.stats(); return CCacheStats.builder() .cacheId(cacheId) .name(cacheName) .labels(labels) .config(config) .debugAcquireStacktrace(debugAcquireStacktrace) // .size(cache.size()) .hitCount(guavaStats.hitCount()) .missCount(guavaStats.missCount()) .build(); } private boolean isNoCache() { return allowDisablingCacheByThreadLocal && ThreadLocalCacheController.instance.isNoCache(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCache.java
1
请完成以下Java代码
public class UserAuthentication extends Authentication { private static final long serialVersionUID = 1L; protected List<String> groupIds; protected List<String> tenantIds; protected Set<String> authorizedApps; protected Date cacheValidationTime; public UserAuthentication(String userId, String processEngineName) { super(userId, processEngineName); } public List<String> getGroupIds() { return groupIds; } public boolean isAuthorizedForApp(String app) { return authorizedApps.contains(Authorization.ANY) || authorizedApps.contains(app); } public Set<String> getAuthorizedApps() { return authorizedApps; }
public List<String> getTenantIds() { return tenantIds; } public void setTenantIds(List<String> tenantIds) { this.tenantIds = tenantIds; } public void setGroupIds(List<String> groupIds) { this.groupIds = groupIds; } public void setAuthorizedApps(Set<String> authorizedApps) { this.authorizedApps = authorizedApps; } public Date getCacheValidationTime() { return cacheValidationTime; } public void setCacheValidationTime(Date cacheValidationTime) { this.cacheValidationTime = cacheValidationTime; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\UserAuthentication.java
1
请在Spring Boot框架中完成以下Java代码
public void setReferenceNo(String value) { this.referenceNo = value; } /** * Gets the value of the setupPlaceNo property. * * @return * possible object is * {@link String } * */ public String getSetupPlaceNo() { return setupPlaceNo; } /** * Sets the value of the setupPlaceNo property. * * @param value * allowed object is * {@link String } * */ public void setSetupPlaceNo(String value) { this.setupPlaceNo = value; } /** * Gets the value of the siteName property. * * @return * possible object is * {@link String } * */ public String getSiteName() { return siteName; } /** * Sets the value of the siteName property. * * @param value * allowed object is * {@link String } * */
public void setSiteName(String value) { this.siteName = value; } /** * Gets the value of the contact property. * * @return * possible object is * {@link String } * */ public String getContact() { return contact; } /** * Sets the value of the contact property. * * @param value * allowed object is * {@link String } * */ public void setContact(String value) { this.contact = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop119VType.java
2
请完成以下Java代码
public String getFilename() { return filename; } /** * Sets the value of the filename property. * * @param value * allowed object is * {@link String } * */ public void setFilename(String value) { this.filename = value; } /** * Gets the value of the mimeType property. * * @return * possible object is * {@link String } * */ public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) {
this.mimeType = value; } /** * Gets the value of the viewer property. * * @return * possible object is * {@link String } * */ public String getViewer() { return viewer; } /** * Sets the value of the viewer property. * * @param value * allowed object is * {@link String } * */ public void setViewer(String value) { this.viewer = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DocumentType.java
1
请完成以下Java代码
public void setO(String organization) { ((InetOrgPerson) this.instance).o = organization; } public void setOu(String ou) { ((InetOrgPerson) this.instance).ou = ou; } public void setRoomNumber(String no) { ((InetOrgPerson) this.instance).roomNumber = no; } public void setTitle(String title) { ((InetOrgPerson) this.instance).title = title; } public void setCarLicense(String carLicense) { ((InetOrgPerson) this.instance).carLicense = carLicense; } public void setDepartmentNumber(String departmentNumber) { ((InetOrgPerson) this.instance).departmentNumber = departmentNumber; } public void setDisplayName(String displayName) { ((InetOrgPerson) this.instance).displayName = displayName; } public void setEmployeeNumber(String no) { ((InetOrgPerson) this.instance).employeeNumber = no; } public void setDestinationIndicator(String destination) { ((InetOrgPerson) this.instance).destinationIndicator = destination; } public void setHomePhone(String homePhone) { ((InetOrgPerson) this.instance).homePhone = homePhone; }
public void setStreet(String street) { ((InetOrgPerson) this.instance).street = street; } public void setPostalCode(String postalCode) { ((InetOrgPerson) this.instance).postalCode = postalCode; } public void setPostalAddress(String postalAddress) { ((InetOrgPerson) this.instance).postalAddress = postalAddress; } public void setMobile(String mobile) { ((InetOrgPerson) this.instance).mobile = mobile; } public void setHomePostalAddress(String homePostalAddress) { ((InetOrgPerson) this.instance).homePostalAddress = homePostalAddress; } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\InetOrgPerson.java
1
请完成以下Java代码
public void setJwtValidatorFactory(Function<ClientRegistration, OAuth2TokenValidator<Jwt>> jwtValidatorFactory) { Assert.notNull(jwtValidatorFactory, "jwtValidatorFactory cannot be null"); this.jwtValidatorFactory = jwtValidatorFactory; } /** * Sets the resolver that provides the expected {@link JwsAlgorithm JWS algorithm} * used for the signature or MAC on the {@link OidcIdToken ID Token}. The default * resolves to {@link SignatureAlgorithm#RS256 RS256} for all * {@link ClientRegistration clients}. * @param jwsAlgorithmResolver the resolver that provides the expected * {@link JwsAlgorithm JWS algorithm} for a specific {@link ClientRegistration client} */ public void setJwsAlgorithmResolver(Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver) { Assert.notNull(jwsAlgorithmResolver, "jwsAlgorithmResolver cannot be null"); this.jwsAlgorithmResolver = jwsAlgorithmResolver; }
/** * Sets the factory that provides a {@link Converter} used for type conversion of * claim values for an {@link OidcIdToken}. The default is {@link ClaimTypeConverter} * for all {@link ClientRegistration clients}. * @param claimTypeConverterFactory the factory that provides a {@link Converter} used * for type conversion of claim values for a specific {@link ClientRegistration * client} */ public void setClaimTypeConverterFactory( Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory) { Assert.notNull(claimTypeConverterFactory, "claimTypeConverterFactory cannot be null"); this.claimTypeConverterFactory = claimTypeConverterFactory; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\ReactiveOidcIdTokenDecoderFactory.java
1
请完成以下Java代码
public class SecurityDataFetcherExceptionResolver extends DataFetcherExceptionResolverAdapter { private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); public SecurityDataFetcherExceptionResolver() { setThreadLocalContextAware(true); } /** * Set the resolver to use to check if an authentication is anonymous that * in turn determines whether {@code AccessDeniedException} is classified * as "unauthorized" or "forbidden". * @param trustResolver the resolver to use */ public void setAuthenticationTrustResolver(AuthenticationTrustResolver trustResolver) {
this.trustResolver = trustResolver; } @Override protected @Nullable GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment environment) { if (ex instanceof AuthenticationException) { return SecurityExceptionResolverUtils.resolveUnauthorized(environment); } if (ex instanceof AccessDeniedException) { SecurityContext securityContext = SecurityContextHolder.getContext(); return SecurityExceptionResolverUtils.resolveAccessDenied(environment, this.trustResolver, securityContext); } return null; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SecurityDataFetcherExceptionResolver.java
1
请完成以下Java代码
public HuId getLuIdNotNull() { return Check.assumeNotNull(luId, "LU shall be set for {}", this); } public interface CaseConsumer { void noLU(); void newLU(final HuPackingInstructionsId luPackingInstructionsId); void existingLU(final HuId luId, final HUQRCode luQRCode); } public interface CaseMapper<T> { T noLU(); T newLU(final HuPackingInstructionsId luPackingInstructionsId); T existingLU(final HuId luId, final HUQRCode luQRCode); } public static void apply(@Nullable final LUPickingTarget target, @NonNull final CaseConsumer consumer) { if (target == null) { consumer.noLU(); } else if (target.isNewLU()) { consumer.newLU(target.getLuPIIdNotNull()); } else if (target.isExistingLU()) { consumer.existingLU(target.getLuIdNotNull(), target.getLuQRCode()); } else { throw new AdempiereException("Unsupported target type: " + target); } } public static <T> T apply(@Nullable final LUPickingTarget target, @NonNull final CaseMapper<T> mapper)
{ if (target == null) { return mapper.noLU(); } else if (target.isNewLU()) { return mapper.newLU(target.getLuPIIdNotNull()); } else if (target.isExistingLU()) { return mapper.existingLU(target.getLuIdNotNull(), target.getLuQRCode()); } else { throw new AdempiereException("Unsupported target type: " + target); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\LUPickingTarget.java
1
请完成以下Java代码
public Mono<ZipCode> findById(@PathVariable String zipcode) { return getById(zipcode); } @GetMapping("/by_city") public Flux<ZipCode> postZipCode(@RequestParam String city) { return zipRepo.findByCity(city); } @PostMapping public Mono<ZipCode> create(@RequestBody ZipCode zipCode) { return getById(zipCode.getZip()) .switchIfEmpty(Mono.defer(createZipCode(zipCode))) .onErrorResume(this::isKeyDuplicated, this.recoverWith(zipCode)); } private Mono<ZipCode> getById(String zipCode) {
return zipRepo.findById(zipCode); } private boolean isKeyDuplicated(Throwable ex) { return ex instanceof DataIntegrityViolationException || ex instanceof UncategorizedR2dbcException; } private Function<? super Throwable, ? extends Mono<ZipCode>> recoverWith(ZipCode zipCode) { return throwable -> zipRepo.findById(zipCode.getZip()); } private Supplier<Mono<? extends ZipCode>> createZipCode(ZipCode zipCode) { return () -> { zipCode.setId(zipCode.getZip()); return zipRepo.save(zipCode); }; } }
repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\spring-project\src\main\java\com\baeldung\spring_project\ZipCodeApi.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_LabelPrinter[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Label printer. @param AD_LabelPrinter_ID Label Printer Definition */ public void setAD_LabelPrinter_ID (int AD_LabelPrinter_ID) { if (AD_LabelPrinter_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, Integer.valueOf(AD_LabelPrinter_ID)); } /** Get Label printer. @return Label Printer Definition */ public int getAD_LabelPrinter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_LabelPrinter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); }
/** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinter.java
1
请完成以下Java代码
public GatewayFilter apply(Config config) { String status = Objects.requireNonNull(config.status, "status must not be null"); HttpStatusHolder statusHolder = HttpStatusHolder.parse(status); return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // option 1 (runs in filter order) /* * exchange.getResponse().beforeCommit(() -> { * exchange.getResponse().setStatusCode(finalStatus); return Mono.empty(); * }); return chain.filter(exchange); */ // option 2 (runs in reverse filter order) return chain.filter(exchange).then(Mono.fromRunnable(() -> { // check not really needed, since it is guarded in setStatusCode, // but it's a good example HttpStatusCode statusCode = exchange.getResponse().getStatusCode(); boolean isStatusCodeUpdated = setResponseStatus(exchange, statusHolder); if (isStatusCodeUpdated && originalStatusHeaderName != null && statusCode != null) { exchange.getResponse() .getHeaders() .set(originalStatusHeaderName, singletonList(statusCode.value()).toString()); } })); } @Override public String toString() { return filterToStringCreator(SetStatusGatewayFilterFactory.this).append("status", config.getStatus()) .toString(); } };
} public @Nullable String getOriginalStatusHeaderName() { return originalStatusHeaderName; } public void setOriginalStatusHeaderName(String originalStatusHeaderName) { this.originalStatusHeaderName = originalStatusHeaderName; } public static class Config { // TODO: relaxed HttpStatus converter private @Nullable String status; public @Nullable String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetStatusGatewayFilterFactory.java
1
请完成以下Java代码
default <ST> RT addInSubQueryFilter(final ModelColumn<T, ?> column, final ModelColumn<ST, ?> subQueryColumn, final IQuery<ST> subQuery) { return addFilter(InSubQueryFilter.<T>builder() .tableName(getModelTableName()) .subQuery(subQuery) .matchingColumnNames(column.getColumnName(), subQueryColumn.getColumnName()) .build()); } default <ST> RT addNotInSubQueryFilter(final ModelColumn<T, ?> column, final ModelColumn<ST, ?> subQueryColumn, final IQuery<ST> subQuery) { final IQueryFilter<T> filter = InSubQueryFilter.<T>builder() .tableName(getModelTableName()) .subQuery(subQuery) .matchingColumnNames(column.getColumnName(), subQueryColumn.getColumnName()) .build(); final IQueryFilter<T> notFilter = NotQueryFilter.of(filter); return addFilter(notFilter); } default RT addIntervalIntersection( @NonNull final String lowerBoundColumnName, @NonNull final String upperBoundColumnName, @Nullable final ZonedDateTime lowerBoundValue, @Nullable final ZonedDateTime upperBoundValue) { addIntervalIntersection( lowerBoundColumnName, upperBoundColumnName, lowerBoundValue != null ? lowerBoundValue.toInstant() : null, upperBoundValue != null ? upperBoundValue.toInstant() : null);
return self(); } default RT addIntervalIntersection( @NonNull final String lowerBoundColumnName, @NonNull final String upperBoundColumnName, @Nullable final Instant lowerBoundValue, @Nullable final Instant upperBoundValue) { addFilter(new DateIntervalIntersectionQueryFilter<>( ModelColumnNameValue.forColumnName(lowerBoundColumnName), ModelColumnNameValue.forColumnName(upperBoundColumnName), lowerBoundValue, upperBoundValue)); return self(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\ICompositeQueryFilterProxy.java
1
请完成以下Java代码
/* package */class ShipmentScheduleDeliveryDayAllocable implements IDeliveryDayAllocable { // // Services private final IShipmentScheduleEffectiveBL shipmentScheduleEffectiveBL = Services.get(IShipmentScheduleEffectiveBL.class); private final IShipmentScheduleDeliveryDayBL shipmentScheduleDeliveryDayBL = Services.get(IShipmentScheduleDeliveryDayBL.class); private final I_M_ShipmentSchedule sched; public ShipmentScheduleDeliveryDayAllocable(final I_M_ShipmentSchedule sched) { Check.assumeNotNull(sched, "sched not null"); this.sched = sched; } public I_M_ShipmentSchedule getM_ShipmentSchedule() { return sched; } @Override public String getTableName() { return I_M_ShipmentSchedule.Table_Name; } @Override public int getRecord_ID() { return sched.getM_ShipmentSchedule_ID(); } @Override public ZonedDateTime getDeliveryDate() {
return shipmentScheduleDeliveryDayBL.getDeliveryDateCurrent(sched); } @Override public BPartnerLocationId getBPartnerLocationId() { return shipmentScheduleEffectiveBL.getBPartnerLocationId(sched); } @Override public int getM_Product_ID() { return sched.getM_Product_ID(); } @Override public boolean isToBeFetched() { // Shipment Schedules are about sending materials to customer return false; } @Override public int getAD_Org_ID() { return sched.getAD_Org_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\ShipmentScheduleDeliveryDayAllocable.java
1
请完成以下Java代码
public java.lang.String getTextMsg () { return (java.lang.String)get_Value(COLUMNNAME_TextMsg); } /** Set View ID. @param ViewId View ID */ @Override public void setViewId (java.lang.String ViewId) { set_Value (COLUMNNAME_ViewId, ViewId); } /** Get View ID. @return View ID */ @Override public java.lang.String getViewId () { return (java.lang.String)get_Value(COLUMNNAME_ViewId); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ @Override public void setWhereClause (java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ @Override public java.lang.String getWhereClause () { return (java.lang.String)get_Value(COLUMNNAME_WhereClause); }
/** * NotificationSeverity AD_Reference_ID=541947 * Reference name: NotificationSeverity */ public static final int NOTIFICATIONSEVERITY_AD_Reference_ID=541947; /** Notice = Notice */ public static final String NOTIFICATIONSEVERITY_Notice = "Notice"; /** Warning = Warning */ public static final String NOTIFICATIONSEVERITY_Warning = "Warning"; /** Error = Error */ public static final String NOTIFICATIONSEVERITY_Error = "Error"; @Override public void setNotificationSeverity (final java.lang.String NotificationSeverity) { set_Value (COLUMNNAME_NotificationSeverity, NotificationSeverity); } @Override public java.lang.String getNotificationSeverity() { return get_ValueAsString(COLUMNNAME_NotificationSeverity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Note.java
1
请完成以下Java代码
private Object tryConsume(MethodInvocation invocation, Consumer<MessageAndChannel> successHandler, BiConsumer<MessageAndChannel, Throwable> errorHandler) throws Throwable { MessageAndChannel mac = new MessageAndChannel((Message) invocation.getArguments()[1], (Channel) invocation.getArguments()[0]); Object ret = null; try { ret = invocation.proceed(); successHandler.accept(mac); } catch (Throwable e) { errorHandler.accept(mac, e); } return ret; } private void ack(MessageAndChannel mac) { try { mac.channel.basicAck(mac.message.getMessageProperties() .getDeliveryTag(), false); } catch (Exception e) { throw new RuntimeException(e); } } private int tryGetRetryCountOrFail(MessageAndChannel mac, Throwable originalError) throws Throwable { MessageProperties props = mac.message.getMessageProperties(); String xRetriedCountHeader = (String) props.getHeader("x-retried-count"); final int xRetriedCount = xRetriedCountHeader == null ? 0 : Integer.valueOf(xRetriedCountHeader); if (retryQueues.retriesExhausted(xRetriedCount)) { mac.channel.basicReject(props.getDeliveryTag(), false); throw originalError; } return xRetriedCount; } private void sendToNextRetryQueue(MessageAndChannel mac, int retryCount) throws Exception { String retryQueueName = retryQueues.getQueueName(retryCount); rabbitTemplate.convertAndSend(retryQueueName, mac.message, m -> { MessageProperties props = m.getMessageProperties();
props.setExpiration(String.valueOf(retryQueues.getTimeToWait(retryCount))); props.setHeader("x-retried-count", String.valueOf(retryCount + 1)); props.setHeader("x-original-exchange", props.getReceivedExchange()); props.setHeader("x-original-routing-key", props.getReceivedRoutingKey()); return m; }); mac.channel.basicReject(mac.message.getMessageProperties() .getDeliveryTag(), false); } private class MessageAndChannel { private Message message; private Channel channel; private MessageAndChannel(Message message, Channel channel) { this.message = message; this.channel = channel; } } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\exponentialbackoff\RetryQueuesInterceptor.java
1
请完成以下Java代码
protected ELResolver initProcessApplicationElResolver() { return DefaultElResolverLookup.lookupResolver(this); } public ExecutionListener getExecutionListener() { return null; } public TaskListener getTaskListener() { return null; } /** * see {@link ProcessApplicationScriptEnvironment#getScriptEngineForName(String, boolean)} */ public ScriptEngine getScriptEngineForName(String name, boolean cache) { return getProcessApplicationScriptEnvironment().getScriptEngineForName(name, cache); } /** * see {@link ProcessApplicationScriptEnvironment#getEnvironmentScripts()} */ public Map<String, List<ExecutableScript>> getEnvironmentScripts() { return getProcessApplicationScriptEnvironment().getEnvironmentScripts(); } protected ProcessApplicationScriptEnvironment getProcessApplicationScriptEnvironment() { if (processApplicationScriptEnvironment == null) { synchronized (this) { if (processApplicationScriptEnvironment == null) { processApplicationScriptEnvironment = new ProcessApplicationScriptEnvironment(this); } } } return processApplicationScriptEnvironment; } public VariableSerializers getVariableSerializers() {
return variableSerializers; } public void setVariableSerializers(VariableSerializers variableSerializers) { this.variableSerializers = variableSerializers; } /** * <p>Provides the default Process Engine name to deploy to, if no Process Engine * was defined in <code>processes.xml</code>.</p> * * @return the default deploy-to Process Engine name. * The default value is "default". */ public String getDefaultDeployToEngineName() { return defaultDeployToEngineName; } /** * <p>Programmatically set the name of the Process Engine to deploy to if no Process Engine * is defined in <code>processes.xml</code>. This allows to circumvent the "default" Process * Engine name and set a custom one.</p> * * @param defaultDeployToEngineName */ protected void setDefaultDeployToEngineName(String defaultDeployToEngineName) { this.defaultDeployToEngineName = defaultDeployToEngineName; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\AbstractProcessApplication.java
1
请完成以下Java代码
private void validateDestinations(List<DestinationTopic> destinationsToAdd) { for (int i = 0; i < destinationsToAdd.size(); i++) { DestinationTopic destination = destinationsToAdd.get(i); if (destination.isReusableRetryTopic()) { // Allow multiple DLTs after REUSABLE_RETRY_TOPIC boolean isLastOrFollowedOnlyByDlts = (i == destinationsToAdd.size() - 1) || destinationsToAdd.subList(i + 1, destinationsToAdd.size()) .stream() .allMatch(DestinationTopic::isDltTopic); Assert.isTrue(isLastOrFollowedOnlyByDlts, () -> String.format("In the destination topic chain, the type %s can only be " + "specified as the last retry topic (followed only by DLT topics).", Type.REUSABLE_RETRY_TOPIC)); } } } private Map<String, DestinationTopicHolder> correlatePairSourceAndDestinationValues( List<DestinationTopic> destinationList) { return IntStream .range(0, destinationList.size()) .boxed() .collect(Collectors.toMap(index -> destinationList.get(index).getDestinationName(), index -> new DestinationTopicHolder(destinationList.get(index), getNextDestinationTopic(destinationList, index)))); } private DestinationTopic getNextDestinationTopic(List<DestinationTopic> destinationList, int index) { return index != destinationList.size() - 1 ? destinationList.get(index + 1) : new DestinationTopic(destinationList.get(index).getDestinationName() + NO_OPS_SUFFIX, destinationList.get(index), NO_OPS_SUFFIX, DestinationTopic.Type.NO_OPS); } @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (Objects.equals(event.getApplicationContext(), this.applicationContext)) { this.contextRefreshed = true; } } /** * Return true if the application context is refreshed. * @return true if refreshed. * @since 2.7.8 */ public boolean isContextRefreshed() {
return this.contextRefreshed; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public static class DestinationTopicHolder { private final DestinationTopic sourceDestination; private final DestinationTopic nextDestination; DestinationTopicHolder(DestinationTopic sourceDestination, DestinationTopic nextDestination) { this.sourceDestination = sourceDestination; this.nextDestination = nextDestination; } protected DestinationTopic getNextDestination() { return this.nextDestination; } protected DestinationTopic getSourceDestination() { return this.sourceDestination; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DefaultDestinationTopicResolver.java
1
请完成以下Java代码
public class ElContextDelegate extends ELContext { protected final org.camunda.bpm.impl.juel.jakarta.el.ELContext delegateContext; protected final ELResolver elResolver; public ElContextDelegate(org.camunda.bpm.impl.juel.jakarta.el.ELContext delegateContext, ELResolver elResolver) { this.delegateContext = delegateContext; this.elResolver = elResolver; } @Override public ELResolver getELResolver() { return elResolver; } @Override public FunctionMapper getFunctionMapper() { return null; } @Override public VariableMapper getVariableMapper() { return null; } // delegate methods //////////////////////////// @Override @SuppressWarnings("rawtypes") public Object getContext(Class key) { return delegateContext.getContext(key); } @Override public boolean equals(Object obj) { return delegateContext.equals(obj); } @Override public Locale getLocale() { return delegateContext.getLocale(); }
@Override public boolean isPropertyResolved() { return delegateContext.isPropertyResolved(); } @Override @SuppressWarnings("rawtypes") public void putContext(Class key, Object contextObject) { delegateContext.putContext(key, contextObject); } @Override public void setLocale(Locale locale) { delegateContext.setLocale(locale); } @Override public void setPropertyResolved(boolean resolved) { delegateContext.setPropertyResolved(resolved); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\el\ElContextDelegate.java
1
请在Spring Boot框架中完成以下Java代码
public SmsHomeAdvertise getItem(Long id) { return advertiseMapper.selectByPrimaryKey(id); } @Override public int update(Long id, SmsHomeAdvertise advertise) { advertise.setId(id); return advertiseMapper.updateByPrimaryKeySelective(advertise); } @Override public List<SmsHomeAdvertise> list(String name, Integer type, String endTime, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); SmsHomeAdvertiseExample example = new SmsHomeAdvertiseExample(); SmsHomeAdvertiseExample.Criteria criteria = example.createCriteria(); if (!StrUtil.isEmpty(name)) { criteria.andNameLike("%" + name + "%"); } if (type != null) { criteria.andTypeEqualTo(type); } if (!StrUtil.isEmpty(endTime)) { String startStr = endTime + " 00:00:00";
String endStr = endTime + " 23:59:59"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start = null; try { start = sdf.parse(startStr); } catch (ParseException e) { e.printStackTrace(); } Date end = null; try { end = sdf.parse(endStr); } catch (ParseException e) { e.printStackTrace(); } if (start != null && end != null) { criteria.andEndTimeBetween(start, end); } } example.setOrderByClause("sort desc"); return advertiseMapper.selectByExample(example); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsHomeAdvertiseServiceImpl.java
2
请完成以下Java代码
public KeyPair getKeyPair(String alias) { return getKeyPair(alias, this.password); } public KeyPair getKeyPair(String alias, char[] password) { try { synchronized (this.lock) { if (this.store == null) { synchronized (this.lock) { this.store = KeyStore.getInstance(this.type); try (InputStream stream = this.resource.getInputStream()) { this.store.load(stream, this.password); } } } } RSAPrivateCrtKey key = (RSAPrivateCrtKey) this.store.getKey(alias, password); Certificate certificate = this.store.getCertificate(alias); PublicKey publicKey = null;
if (certificate != null) { publicKey = certificate.getPublicKey(); } else if (key != null) { RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); publicKey = KeyFactory.getInstance("RSA").generatePublic(spec); } return new KeyPair(publicKey, key); } catch (Exception ex) { throw new IllegalStateException("Cannot load keys from store: " + this.resource, ex); } } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\KeyStoreKeyFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public static List<Map<String, Object>> getList() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); AccountFundDirectionEnum[] val = AccountFundDirectionEnum.values(); for (AccountFundDirectionEnum e : val) { Map<String, Object> map = new HashMap<String, Object>(); map.put("label", e.getLabel()); map.put("name", e.name()); list.add(map);
} return list; } public static AccountFundDirectionEnum getEnum(String name) { AccountFundDirectionEnum resultEnum = null; AccountFundDirectionEnum[] enumAry = AccountFundDirectionEnum.values(); for (int i = 0; i < enumAry.length; i++) { if (enumAry[i].name().equals(name)) { resultEnum = enumAry[i]; break; } } return resultEnum; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\enums\AccountFundDirectionEnum.java
2
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) {
if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_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_A_RegistrationProduct.java
1
请完成以下Java代码
public void applyListener(@NonNull final I_C_Async_Batch asyncBatch) { final String internalName = asyncBatchBL.getAsyncBatchTypeInternalName(asyncBatch).orElse(null); if(internalName != null) { final IAsyncBatchListener listener = getListener(internalName); listener.createNotice(asyncBatch); } } private IAsyncBatchListener getListener(final String ascyncBatchType) { IAsyncBatchListener l = listenersList.get(ascyncBatchType); // retrieve default implementation if (l == null) { l = listenersList.get(AsyncBatchDAO.ASYNC_BATCH_TYPE_DEFAULT); } return l; } private final List<INotifyAsyncBatch> asycnBatchNotifiers = new ArrayList<>(); @Override
public void registerAsyncBatchNotifier(INotifyAsyncBatch notifyAsyncBatch) { Check.assume(!asycnBatchNotifiers.contains(notifyAsyncBatch), "Every notifier is added only once"); asycnBatchNotifiers.add(notifyAsyncBatch); } @Override public void notify(I_C_Async_Batch asyncBatch) { for (INotifyAsyncBatch notifier : asycnBatchNotifiers) { notifier.sendNotifications(asyncBatch); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchListeners.java
1
请完成以下Java代码
private static I_C_BPartner createNewTemplateBPartner(final int clientId) { final I_C_BPartner bpartner = InterfaceWrapperHelper.newInstanceOutOfTrx(I_C_BPartner.class); final I_C_BPartner template = getBPartnerCashTrx(clientId); if (template != null) { InterfaceWrapperHelper.copyValues(bpartner, bpartner); } // Reset bpartner.setValue(""); bpartner.setName(""); bpartner.setName2(null); bpartner.setDUNS(""); bpartner.setFirstSale(null); // bpartner.setPotentialLifeTimeValue(BigDecimal.ZERO); bpartner.setAcqusitionCost(BigDecimal.ZERO); bpartner.setShareOfCustomer(0); bpartner.setSalesVolume(0); return bpartner; } // getTemplate
/** * @return Cash Trx Business Partner or null */ private static I_C_BPartner getBPartnerCashTrx(final int clientId) { final IClientDAO clientDAO = Services.get(IClientDAO.class); final I_AD_ClientInfo clientInfo = clientDAO.retrieveClientInfo(Env.getCtx(), clientId); final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(clientInfo.getC_BPartnerCashTrx_ID()); if(bpartnerId == null) { return null; } return Services.get(IBPartnerDAO.class).getById(bpartnerId); } // getBPartnerCashTrx } // VBPartner
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VBPartner.java
1
请完成以下Java代码
public org.compiere.model.I_AD_Column getAD_Column() { return get_ValueAsPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class); } @Override public void setAD_Column(final org.compiere.model.I_AD_Column AD_Column) { set_ValueFromPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class, AD_Column); } @Override public void setAD_Column_ID (final int AD_Column_ID) { if (AD_Column_ID < 1) set_Value (COLUMNNAME_AD_Column_ID, null); else set_Value (COLUMNNAME_AD_Column_ID, AD_Column_ID); } @Override public int getAD_Column_ID() { return get_ValueAsInt(COLUMNNAME_AD_Column_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setWEBUI_Board_CardField_ID (final int WEBUI_Board_CardField_ID) { if (WEBUI_Board_CardField_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, WEBUI_Board_CardField_ID); } @Override public int getWEBUI_Board_CardField_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_CardField_ID); }
@Override public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board() { return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); } @Override public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board) { set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_CardField.java
1
请完成以下Java代码
public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setPIName (final @Nullable java.lang.String PIName) { set_ValueNoCheck (COLUMNNAME_PIName, PIName); } @Override public java.lang.String getPIName() { return get_ValueAsString(COLUMNNAME_PIName); } @Override public void setValue (final @Nullable java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override
public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_ValueNoCheck (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Instance_Properties_v.java
1
请在Spring Boot框架中完成以下Java代码
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { // 1. 从请求头中获取 ClientId String header = request.getHeader("Authorization"); if (header == null || !header.startsWith("Basic ")) { throw new UnapprovedClientAuthenticationException("请求头中无client信息"); } String[] tokens = this.extractAndDecodeHeader(header, request); String clientId = tokens[0]; String clientSecret = tokens[1]; TokenRequest tokenRequest = null; // 2. 通过 ClientDetailsService 获取 ClientDetails ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); // 3. 校验 ClientId和 ClientSecret的正确性 if (clientDetails == null) { throw new UnapprovedClientAuthenticationException("clientId:" + clientId + "对应的信息不存在"); } else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) { throw new UnapprovedClientAuthenticationException("clientSecret不正确"); } else { // 4. 通过 TokenRequest构造器生成 TokenRequest tokenRequest = new TokenRequest(new HashMap<>(), clientId, clientDetails.getScope(), "custom"); } // 5. 通过 TokenRequest的 createOAuth2Request方法获取 OAuth2Request OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); // 6. 通过 Authentication和 OAuth2Request构造出 OAuth2Authentication OAuth2Authentication auth2Authentication = new OAuth2Authentication(oAuth2Request, authentication); // 7. 通过 AuthorizationServerTokenServices 生成 OAuth2AccessToken OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(auth2Authentication); // 8. 返回 Token log.info("登录成功");
response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(new ObjectMapper().writeValueAsString(token)); } private String[] extractAndDecodeHeader(String header, HttpServletRequest request) { byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8); byte[] decoded; try { decoded = Base64.getDecoder().decode(base64Token); } catch (IllegalArgumentException var7) { throw new BadCredentialsException("Failed to decode basic authentication token"); } String token = new String(decoded, StandardCharsets.UTF_8); int delim = token.indexOf(":"); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } else { return new String[]{token.substring(0, delim), token.substring(delim + 1)}; } } }
repos\SpringAll-master\65.Spring-Security-OAuth2-Config\src\main\java\cc\mrbird\security\handler\MyAuthenticationSucessHandler.java
2
请完成以下Java代码
public class AddResponseHeaderGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory { private static final String OVERRIDE_KEY = "override"; @Override public Class getConfigClass() { return Config.class; } @Override public NameValueConfig newConfig() { return new Config(); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList(GatewayFilter.NAME_KEY, GatewayFilter.VALUE_KEY, OVERRIDE_KEY); } @Override public GatewayFilter apply(NameValueConfig config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { return chain.filter(exchange).then(Mono.fromRunnable(() -> addHeader(exchange, config))); } @Override public String toString() { String name = config.getName(); String value = config.getValue(); if (config instanceof Config) { return filterToStringCreator(AddResponseHeaderGatewayFilterFactory.this) .append(GatewayFilter.NAME_KEY, name != null ? name : "") .append(GatewayFilter.VALUE_KEY, value != null ? value : "") .append(OVERRIDE_KEY, ((Config) config).isOverride()) .toString(); } return filterToStringCreator(AddResponseHeaderGatewayFilterFactory.this) .append(name != null ? name : "", value != null ? value : "") .toString(); } }; } void addHeader(ServerWebExchange exchange, NameValueConfig config) { // if response has been commited, no more response headers will bee added. if (!exchange.getResponse().isCommitted()) { String name = Objects.requireNonNull(config.getName(), "name must not be null"); String rawValue = Objects.requireNonNull(config.getValue(), "value must not be null"); final String value = ServerWebExchangeUtils.expand(exchange, rawValue); HttpHeaders headers = exchange.getResponse().getHeaders(); boolean override = true; // default is true if (config instanceof Config) {
override = ((Config) config).isOverride(); } if (override) { headers.add(name, value); } else { boolean headerIsMissingOrBlank = headers.getOrEmpty(name) .stream() .allMatch(h -> !StringUtils.hasText(h)); if (headerIsMissingOrBlank) { headers.add(name, value); } } } } public static class Config extends AbstractNameValueGatewayFilterFactory.NameValueConfig { private boolean override = true; public boolean isOverride() { return override; } public Config setOverride(boolean override) { this.override = override; return this; } @Override public String toString() { return new ToStringCreator(this).append(NAME_KEY, name) .append(VALUE_KEY, value) .append(OVERRIDE_KEY, override) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\AddResponseHeaderGatewayFilterFactory.java
1
请完成以下Java代码
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 Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; }
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Boolean getCompleted() { return completed; } public void setCompleted(Boolean completed) { this.completed = completed; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign\src\main\java\com\baeldung\cloud\openfeign\model\Todo.java
1
请完成以下Java代码
protected void validateType(JavaType type, DeserializationTypeValidator validator) { if (validator != null) { List<String> invalidTypes = new ArrayList<>(); validateType(type, validator, invalidTypes); if (!invalidTypes.isEmpty()) { throw new SpinRuntimeException("The following classes are not whitelisted for deserialization: " + invalidTypes); } } } protected void validateType(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) { if (!type.isPrimitive()) { if (!type.isArrayType()) { validateTypeInternal(type, validator, invalidTypes); } if (type.isMapLikeType()) { validateType(type.getKeyType(), validator, invalidTypes);
} if (type.isContainerType() || type.hasContentType()) { validateType(type.getContentType(), validator, invalidTypes); } } } protected void validateTypeInternal(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) { String className = type.getRawClass().getName(); if (!validator.validate(className) && !invalidTypes.contains(className)) { invalidTypes.add(className); } } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\JacksonJsonDataFormatMapper.java
1
请完成以下Java代码
public int getRef_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_InOutLine getReversalLine() throws RuntimeException { return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name) .getPO(getReversalLine_ID(), get_TrxName()); } /** Set Reversal Line. @param ReversalLine_ID Use to keep the reversal line ID for reversing costing purpose */ public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, null); else set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Reversal Line. @return Use to keep the reversal line ID for reversing costing purpose */ public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verworfene Menge. @param ScrappedQty Durch QA verworfene Menge */ public void setScrappedQty (BigDecimal ScrappedQty) { set_ValueNoCheck (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Verworfene Menge. @return Durch QA verworfene Menge */ public BigDecimal getScrappedQty () {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Zielmenge. @param TargetQty Zielmenge der Warenbewegung */ public void setTargetQty (BigDecimal TargetQty) { set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty); } /** Get Zielmenge. @return Zielmenge der Warenbewegung */ public BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_M_InOutLine_Overview.java
1
请完成以下Java代码
public static Consumer<OAuth2AuthorizationRequest.Builder> withPkce() { return OAuth2AuthorizationRequestCustomizers::applyPkce; } private static void applyPkce(OAuth2AuthorizationRequest.Builder builder) { if (isPkceAlreadyApplied(builder)) { return; } String codeVerifier = DEFAULT_SECURE_KEY_GENERATOR.generateKey(); builder.attributes((attrs) -> attrs.put(PkceParameterNames.CODE_VERIFIER, codeVerifier)); builder.additionalParameters((params) -> { try { String codeChallenge = createHash(codeVerifier); params.put(PkceParameterNames.CODE_CHALLENGE, codeChallenge); params.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); } catch (NoSuchAlgorithmException ex) { params.put(PkceParameterNames.CODE_CHALLENGE, codeVerifier); } });
} private static boolean isPkceAlreadyApplied(OAuth2AuthorizationRequest.Builder builder) { AtomicBoolean pkceApplied = new AtomicBoolean(false); builder.additionalParameters((params) -> { if (params.containsKey(PkceParameterNames.CODE_CHALLENGE)) { pkceApplied.set(true); } }); return pkceApplied.get(); } private static String createHash(String value) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII)); return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestCustomizers.java
1
请在Spring Boot框架中完成以下Java代码
public void afterReturning(Object result) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); Map<String, String> map = MDC.getCopyOfContextMap(); if (map != null) { JSONObject jsonObject = new JSONObject(true); jsonObject.put("uri", request.getRequestURI()); jsonObject.put("took", System.currentTimeMillis() - Long.parseLong(map.getOrDefault("startTime", String.valueOf(System.currentTimeMillis())))); jsonObject.put("userId", map.getOrDefault("userId", "")); jsonObject.put("req", JSON.parseObject(map.getOrDefault("req", ""))); if (result != null) { jsonObject.put("res", JSON.parseObject(result.toString())); } log.info(jsonObject.toJSONString()); } } /** * 读取请求信息,转换为json */ private JSONObject getRequestInfo(HttpServletRequest req) { JSONObject requestInfo = new JSONObject(); try { StringBuffer requestURL = req.getRequestURL(); requestInfo.put("requestURL", requestURL);
String method = req.getMethod(); requestInfo.put("method", method); if (req.getQueryString() != null) { requestInfo.put("queryString", URLDecoder.decode(req.getQueryString(), "UTF-8")); } String remoteAddr = req.getRemoteAddr(); requestInfo.put("remoteAddr", remoteAddr); if (req instanceof ContentCachingRequestWrapper) { ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) req; String bodyStr = new String(wrapper.getContentAsByteArray(), StandardCharsets.UTF_8); if (bodyStr.startsWith("{")) { JSONObject jsonObject = JSON.parseObject(bodyStr); requestInfo.put("requestBody", jsonObject); } } } catch (Exception e) { log.error("解析请求失败", e); requestInfo.put("parseError", e.getMessage()); } return requestInfo; } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\config\filter\WebLogAspect.java
2
请完成以下Java代码
class SplitLargeFile { public List<File> splitByFileSize(File largeFile, int maxSizeOfSplitFiles, String splitedFileDirPath) throws IOException { List<File> listOfSplitFiles = new ArrayList<>(); try (InputStream in = Files.newInputStream(largeFile.toPath())) { final byte[] buffer = new byte[maxSizeOfSplitFiles]; int dataRead = in.read(buffer); while (dataRead > -1) { File splitFile = getSplitFile(FilenameUtils.removeExtension(largeFile.getName()), buffer, dataRead, splitedFileDirPath); listOfSplitFiles.add(splitFile); dataRead = in.read(buffer); } } return listOfSplitFiles; } private File getSplitFile(String largeFileName, byte[] buffer, int length, String splitedFileDirPath) throws IOException { File splitFile = File.createTempFile(largeFileName + "-", "-split", new File(splitedFileDirPath)); try (FileOutputStream fos = new FileOutputStream(splitFile)) { fos.write(buffer, 0, length); } return splitFile; }
public List<File> splitByNumberOfFiles(File largeFile, int noOfFiles, String splitedFileDirPath) throws IOException { return splitByFileSize(largeFile, getSizeInBytes(largeFile.length(), noOfFiles), splitedFileDirPath); } private int getSizeInBytes(long largefileSizeInBytes, int numberOfFilesforSplit) { if (largefileSizeInBytes % numberOfFilesforSplit != 0) { largefileSizeInBytes = ((largefileSizeInBytes / numberOfFilesforSplit) + 1) * numberOfFilesforSplit; } long x = largefileSizeInBytes / numberOfFilesforSplit; if (x > Integer.MAX_VALUE) { throw new NumberFormatException("size too large"); } return (int) x; } }
repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\splitlargefile\SplitLargeFile.java
1
请完成以下Java代码
public class AddOnePage { public static void main(String[] args) { // Create a new document object Document document = new Document(); // Load a sample document from a file document.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx"); // Get the body of the last section of the document Body body = document.getLastSection().getBody(); // Insert a page break after the last paragraph in the body body.getLastParagraph().appendBreak(BreakType.Page_Break); // Create a new paragraph style ParagraphStyle paragraphStyle = new ParagraphStyle(document); paragraphStyle.setName("CustomParagraphStyle1"); paragraphStyle.getParagraphFormat().setLineSpacing(12); paragraphStyle.getParagraphFormat().setAfterSpacing(8); paragraphStyle.getCharacterFormat().setFontName("Microsoft YaHei"); paragraphStyle.getCharacterFormat().setFontSize(12); // Add the paragraph style to the document's style collection document.getStyles().add(paragraphStyle); // Create a new paragraph and set the text content Paragraph paragraph = new Paragraph(document); paragraph.appendText("Thank you for using our Spire.Doc for Java product. The trial version will add a red watermark to the generated result document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted."); // Apply the paragraph style paragraph.applyStyle(paragraphStyle.getName()); // Add the paragraph to the body's content collection body.getChildObjects().add(paragraph); // Create another new paragraph and set the text content paragraph = new Paragraph(document); paragraph.appendText("To fully experience our product, we provide a one-month temporary license for each of our customers for free. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");
// Apply the paragraph style paragraph.applyStyle(paragraphStyle.getName()); // Add the paragraph to the body's content collection body.getChildObjects().add(paragraph); // Save the document to a specified path document.saveToFile("/Users/liuhaihua/tmp/Add a Page.docx", FileFormat.Docx); // Close the document document.close(); // Dispose of the document object's resources document.dispose(); } }
repos\springboot-demo-master\spire-doc\src\main\java\com\et\spire\doc\AddOnePage.java
1