instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public Long getId() {
return this.id;
}
public String getUsername() {
return this.username;
}
public String getEmail() {
return this.email;
}
public List<Post> getPosts() {
return this.posts;
}
public void setId(Long id) {
this.id = id;
} | public void setUsername(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public String toString() {
return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", posts=" + this.getPosts()
+ ")";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\lazy\list\moderatedomain\User.java | 1 |
请完成以下Java代码 | class PackingHUsViewKey
{
public static PackingHUsViewKey ofPackingHUsViewId(final ViewId packingHUsViewId)
{
return new PackingHUsViewKey(packingHUsViewId);
}
public static ViewId extractPickingSlotClearingViewId(final ViewId packingHUsViewId)
{
return ViewId.ofParts(PickingSlotsClearingViewFactory.WINDOW_ID, packingHUsViewId.getViewIdPart());
}
public static ViewId incrementPackingHUsViewIdVersion(final ViewId packingHUsViewId)
{
final int version = packingHUsViewId.getPartAsInt(4);
return createPackingHUsViewIdFromParts(
packingHUsViewId.getPart(1),
packingHUsViewId.getPartAsInt(2),
packingHUsViewId.getPartAsInt(3),
version + 1);
}
private static ViewId createPackingHUsViewIdFromParts(
@NonNull final String pickingSlotsClearingViewIdPart,
final int bpartnerId,
final int bpartnerLocationId,
final int version)
{
return ViewId.ofParts(
PackingHUsViewFactory.WINDOW_ID, // part 0
pickingSlotsClearingViewIdPart, // part 1
String.valueOf(Math.max(bpartnerId, 0)), // part 2
String.valueOf(Math.max(bpartnerLocationId, 0)), // part 3
String.valueOf(Math.max(version, 0)) // part 4
);
}
int bpartnerId;
int bpartnerLocationId;
ViewId packingHUsViewId;
@lombok.Builder
private PackingHUsViewKey(
@NonNull final String pickingSlotsClearingViewIdPart, | final int bpartnerId,
final int bpartnerLocationId)
{
this.bpartnerId = Math.max(bpartnerId, 0);
this.bpartnerLocationId = Math.max(bpartnerLocationId, 0);
this.packingHUsViewId = createPackingHUsViewIdFromParts(
pickingSlotsClearingViewIdPart,
this.bpartnerId,
this.bpartnerLocationId,
0);
}
private PackingHUsViewKey(@NonNull final ViewId packingHUsViewId)
{
Check.assumeEquals(packingHUsViewId.getWindowId(), PackingHUsViewFactory.WINDOW_ID, "Invalid packingHUsViewId: {}", packingHUsViewId);
this.bpartnerId = packingHUsViewId.getPartAsInt(2);
this.bpartnerLocationId = packingHUsViewId.getPartAsInt(3);
this.packingHUsViewId = packingHUsViewId;
}
public ViewId getPickingSlotsClearingViewId()
{
return extractPickingSlotClearingViewId(packingHUsViewId);
}
public boolean isBPartnerIdMatching(final int bpartnerIdToMatch)
{
return (bpartnerIdToMatch <= 0 && bpartnerId <= 0)
|| bpartnerIdToMatch == bpartnerId;
}
public boolean isBPartnerLocationIdMatching(final int bpartnerLocationIdToMatch)
{
return (bpartnerLocationIdToMatch <= 0 && bpartnerLocationId <= 0)
|| bpartnerLocationIdToMatch == bpartnerLocationId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PackingHUsViewKey.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxWait() {
return maxWait;
}
public void setMaxWait(Integer maxWait) {
this.maxWait = maxWait;
}
public Long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public Boolean getTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(Boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Boolean getTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(Boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow; | }
public Boolean getTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(Boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public Boolean getPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public Integer getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
} | repos\spring-boot-quick-master\quick-multi-data\src\main\java\com\quick\mulit\config\DruidConfigPrimaryProperties.java | 2 |
请完成以下Java代码 | public <T> T get(Contextual<T> contextual, CreationalContext<T> arg1) {
Bean<T> bean = (Bean<T>) contextual;
String variableName = bean.getName();
BusinessProcess businessProcess = getBusinessProcess();
Object variable = businessProcess.getVariable(variableName);
if (variable != null) {
if (LOGGER.isDebugEnabled()) {
if (businessProcess.isAssociated()) {
LOGGER.debug("Getting instance of bean '{}' from Execution[{}]", variableName, businessProcess.getExecutionId());
} else {
LOGGER.debug("Getting instance of bean '{}' from transient bean store", variableName);
}
}
return (T) variable;
} else {
if (LOGGER.isDebugEnabled()) {
if (businessProcess.isAssociated()) {
LOGGER.debug("Creating instance of bean '{}' in business process context representing Execution[{}]", variableName, businessProcess.getExecutionId());
} else {
LOGGER.debug("Creating instance of bean '{}' in transient bean store", variableName);
}
}
T beanInstance = bean.create(arg1); | businessProcess.setVariable(variableName, beanInstance);
return beanInstance;
}
}
@Override
public boolean isActive() {
// we assume the business process is always 'active'. If no
// task/execution is
// associated, temporary instances of @BusinessProcessScoped beans are
// cached in the
// conversation / request
return true;
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\context\BusinessProcessContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MultipartConfigElement multipartConfigElement() {
return this.multipartProperties.createMultipartConfig();
}
/**
* 注册解析器
*/
@Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
@ConditionalOnMissingBean(MultipartResolver.class)
public StandardServletMultipartResolver multipartResolver() {
StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily());
return multipartResolver;
}
/**
* 华东机房
*/
@Bean
public com.qiniu.storage.Configuration qiniuConfig() {
return new com.qiniu.storage.Configuration(Zone.zone0());
}
/**
* 构建一个七牛上传工具实例
*/ | @Bean
public UploadManager uploadManager() {
return new UploadManager(qiniuConfig());
}
/**
* 认证信息实例
*/
@Bean
public Auth auth() {
return Auth.create(accessKey, secretKey);
}
/**
* 构建七牛空间管理实例
*/
@Bean
public BucketManager bucketManager() {
return new BucketManager(auth(), qiniuConfig());
}
} | repos\spring-boot-demo-master\demo-upload\src\main\java\com\xkcoding\upload\config\UploadConfig.java | 2 |
请完成以下Java代码 | protected String getPlanItemDefinitionXmlElementValue(TimerEventListener timerEventListener) {
return ELEMENT_TIMER_EVENT_LISTENER;
}
@Override
protected void writePlanItemDefinitionSpecificAttributes(TimerEventListener timerEventListener, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(timerEventListener, xtw);
if (StringUtils.isNotEmpty(timerEventListener.getAvailableConditionExpression())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE,
CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_AVAILABLE_CONDITION,
timerEventListener.getAvailableConditionExpression());
}
}
@Override
protected void writePlanItemDefinitionBody(CmmnModel model, TimerEventListener timerEventListener, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception {
if (StringUtils.isNotEmpty(timerEventListener.getTimerExpression())) { | xtw.writeStartElement(ELEMENT_TIMER_EXPRESSION);
xtw.writeCData(timerEventListener.getTimerExpression());
xtw.writeEndElement();
}
if (StringUtils.isNotEmpty(timerEventListener.getTimerStartTriggerSourceRef())) {
xtw.writeStartElement(ELEMENT_PLAN_ITEM_START_TRIGGER);
xtw.writeAttribute(ATTRIBUTE_PLAN_ITEM_START_TRIGGER_SRC_REF, timerEventListener.getTimerStartTriggerSourceRef());
xtw.writeStartElement(ELEMENT_STANDARD_EVENT);
xtw.writeCData(timerEventListener.getTimerStartTriggerStandardEvent());
xtw.writeEndElement();
xtw.writeEndElement();
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\TimerEventListenerExport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getLINENUMBER() {
return linenumber;
}
/**
* Sets the value of the linenumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLINENUMBER(String value) {
this.linenumber = value;
}
/**
* Gets the value of the productqual property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPRODUCTQUAL() {
return productqual;
}
/**
* Sets the value of the productqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRODUCTQUAL(String value) {
this.productqual = value;
}
/**
* Gets the value of the productid property.
* | * @return
* possible object is
* {@link String }
*
*/
public String getPRODUCTID() {
return productid;
}
/**
* Sets the value of the productid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRODUCTID(String value) {
this.productid = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DPRIN1.java | 2 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (getSelectedRowIds().isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No MaterialCockpitrows are selected");
}
final Set<Integer> cockpitRowIds = getSelectedCockpitRecordIdsRecursively();
if (cockpitRowIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("The selected rows are just dummys with all-zero");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final Set<Integer> cockpitRowIds = getSelectedCockpitRecordIdsRecursively();
final List<TableRecordReference> cockpitDetailRecords = retrieveCockpitDetailRecordReferences(cockpitRowIds);
getResult().setRecordsToOpen(cockpitDetailRecords, MaterialCockpitUtil.WINDOWID_MaterialCockpit_Detail_String);
return MSG_OK; | }
private List<TableRecordReference> retrieveCockpitDetailRecordReferences(final Set<Integer> cockpitRowIds)
{
Check.assumeNotEmpty(cockpitRowIds, "cockpitRowIds is not empty");
return Services.get(IQueryBL.class)
.createQueryBuilder(I_MD_Cockpit_DocumentDetail.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_MD_Cockpit_DocumentDetail.COLUMN_MD_Cockpit_ID, cockpitRowIds)
.create()
.listIds()
.stream()
.map(cockpitDetailRecordId -> TableRecordReference.of(I_MD_Cockpit_DocumentDetail.Table_Name, cockpitDetailRecordId))
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\process\MD_Cockpit_DocumentDetail_Display.java | 1 |
请完成以下Java代码 | public void before(JoinPoint joinPoint) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 befor:" + log.value() + ":::" + JSON.toJSONString(joinPoint.getArgs()));
}
@After(value = "pointCutMethod() || pointCutType()")
public void after(JoinPoint joinPoint) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 after:" + log.value());
}
@AfterReturning(value = "pointCutMethod() || pointCutType()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 afterReturning:" + log.value() + ":::" + JSON.toJSONString(result));
}
@AfterThrowing(value = "pointCutMethod() || pointCutType()", throwing = "t")
public void afterThrowing(JoinPoint joinPoint, Throwable t) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作 | MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 afterThrowing:" + log.value() + ":::" + JSON.toJSONString(t.getStackTrace()));
}
// @Around(value = "pointCutMethod() || pointCutType()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 Around before:" + log.value() + ":::" + JSON.toJSONString(joinPoint.getArgs()));
Object result = joinPoint.proceed();
System.out.println("日志切面 Around after:" + log.value() + ":::" + JSON.toJSONString(result));
return result;
}
} | repos\spring-boot-student-master\spring-boot-student-spring\src\main\java\com\xiaolyuh\aop\aspect\LogAspect.java | 1 |
请完成以下Java代码 | public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSnapshot_UUID (final java.lang.String Snapshot_UUID)
{
set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID);
}
@Override
public java.lang.String getSnapshot_UUID()
{
return get_ValueAsString(COLUMNNAME_Snapshot_UUID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage_Snapshot.java | 1 |
请完成以下Java代码 | public void setGln(final String gln)
{
this.gln = gln;
this.glnSet = true;
}
public void setShipTo(final Boolean shipTo)
{
this.shipTo = shipTo;
this.shipToSet = true;
}
public void setShipToDefault(final Boolean shipToDefault)
{
this.shipToDefault = shipToDefault;
this.shipToDefaultSet = true;
}
public void setBillTo(final Boolean billTo)
{
this.billTo = billTo;
this.billToSet = true;
}
public void setBillToDefault(final Boolean billToDefault)
{
this.billToDefault = billToDefault;
this.billToDefaultSet = true;
}
public void setEphemeral(final Boolean ephemeral)
{
this.ephemeral = ephemeral;
this.ephemeralSet = true; | }
public void setEmail(@Nullable final String email)
{
this.email = email;
this.emailSet = true;
}
public void setPhone(final String phone)
{
this.phone = phone;
this.phoneSet = true;
}
public void setVisitorsAddress(final Boolean visitorsAddress)
{
this.visitorsAddress = visitorsAddress;
this.visitorsAddressSet = true;
}
public void setVisitorsAddressDefault(final Boolean visitorsAddressDefault)
{
this.visitorsAddressDefault = visitorsAddressDefault;
this.visitorsAddressDefaultSet = true;
}
public void setVatId(final String vatId)
{
this.vatId = vatId;
this.vatIdSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestLocation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Optional<FTSFilterDescriptor> getByTargetTableName(@NonNull final String targetTableName)
{
return Optional.ofNullable(descriptorsByTargetTableName.get(targetTableName));
}
public FTSFilterDescriptor getById(final FTSFilterDescriptorId id)
{
final FTSFilterDescriptor filter = descriptorsById.get(id);
if (filter == null)
{
throw new AdempiereException("No filter found for " + id);
}
return filter;
}
}
@ToString
private static class AvailableSelectionKeyColumnNames
{
private final ArrayList<String> availableIntKeys = new ArrayList<>(I_T_ES_FTS_Search_Result.COLUMNNAME_IntKeys);
private final ArrayList<String> availableStringKeys = new ArrayList<>(I_T_ES_FTS_Search_Result.COLUMNNAME_StringKeys);
public String reserveNext(@NonNull final FTSJoinColumn.ValueType valueType)
{
final ArrayList<String> availableKeys; | if (valueType == FTSJoinColumn.ValueType.INTEGER)
{
availableKeys = availableIntKeys;
}
else if (valueType == FTSJoinColumn.ValueType.STRING)
{
availableKeys = availableStringKeys;
}
else
{
availableKeys = new ArrayList<>();
}
if (availableKeys.isEmpty())
{
throw new AdempiereException("No more available key columns left for valueType=" + valueType + " in " + this);
}
return availableKeys.remove(0);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSFilterDescriptorRepository.java | 2 |
请完成以下Spring Boot application配置 | server.port=8081
spring.application.name=Spring Boot Client
spring.boot.admin.client.url=http://localhost:8080
management.endpoints.web.exposure.include=*
spring.bo | ot.admin.client.username=admin
spring.boot.admin.client.password=111111 | repos\Spring-Boot-In-Action-master\spring_boot_admin2.0_demo\sba_client_2_0\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public AbstractQueryDto<?> getQuery() {
return query;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "resourceType", defaultImpl=TaskQueryDto.class)
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = TaskQueryDto.class, name = EntityTypes.TASK)})
public void setQuery(AbstractQueryDto<?> query) {
this.query = query;
}
public Map<String, Object> getProperties() { | return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
@JsonInclude(Include.NON_NULL)
public Long getItemCount() {
return itemCount;
}
public void setItemCount(Long itemCount) {
this.itemCount = itemCount;
}
public static FilterDto fromFilter(Filter filter) {
FilterDto dto = new FilterDto();
dto.id = filter.getId();
dto.resourceType = filter.getResourceType();
dto.name = filter.getName();
dto.owner = filter.getOwner();
if (EntityTypes.TASK.equals(filter.getResourceType())) {
dto.query = TaskQueryDto.fromQuery(filter.getQuery());
}
dto.properties = filter.getProperties();
return dto;
}
public void updateFilter(Filter filter, ProcessEngine engine) {
if (getResourceType() != null && !getResourceType().equals(filter.getResourceType())) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Unable to update filter from resource type '" + filter.getResourceType() + "' to '" + getResourceType() + "'");
}
filter.setName(getName());
filter.setOwner(getOwner());
filter.setQuery(query.toQuery(engine));
filter.setProperties(getProperties());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\FilterDto.java | 1 |
请完成以下Java代码 | public void afterModelLinked(final MTLinkRequest request)
{
final I_C_AllocationLine allocationLine = InterfaceWrapperHelper.create(request.getModel(), I_C_AllocationLine.class);
final PaymentId paymentId = PaymentId.ofRepoIdOrNull(allocationLine.getC_Payment_ID());
if(paymentId == null)
{
return;
}
final IPaymentBL paymentBL = Services.get(IPaymentBL.class);
final I_C_Payment payment = paymentBL.getById(paymentId);
if (payment == null)
{
return;
}
final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class);
materialTrackingBL.linkModelToMaterialTracking(
MTLinkRequest.builder()
.model(payment)
.materialTrackingRecord(request.getMaterialTrackingRecord())
.build());
}
/**
* UnLink allocation line's Payment from given material tracking
*/
@Override
public void afterModelUnlinked(final Object model, final I_M_Material_Tracking materialTrackingOld)
{
final I_C_AllocationLine allocationLine = InterfaceWrapperHelper.create(model, I_C_AllocationLine.class);
final PaymentId paymentId = PaymentId.ofRepoIdOrNull(allocationLine.getC_Payment_ID()); | if(paymentId == null)
{
return;
}
final IPaymentBL paymentBL = Services.get(IPaymentBL.class);
final I_C_Payment payment = paymentBL.getById(paymentId);
if (payment == null)
{
return;
}
final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class);
materialTrackingBL.unlinkModelFromMaterialTrackings(payment, materialTrackingOld);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\spi\impl\listeners\PaymentAllocationLineMaterialTrackingListener.java | 1 |
请完成以下Java代码 | public class SimplifiedToHongKongChineseDictionary extends BaseChineseDictionary
{
static AhoCorasickDoubleArrayTrie<String> trie = new AhoCorasickDoubleArrayTrie<String>();
static
{
long start = System.currentTimeMillis();
String datPath = HanLP.Config.tcDictionaryRoot + "s2hk";
if (!load(datPath, trie))
{
TreeMap<String, String> s2t = new TreeMap<String, String>();
TreeMap<String, String> t2hk = new TreeMap<String, String>();
if (!load(s2t, false, HanLP.Config.tcDictionaryRoot + "s2t.txt") ||
!load(t2hk, false, HanLP.Config.tcDictionaryRoot + "t2hk.txt"))
{
throw new IllegalArgumentException("简体转香港繁体词典加载失败");
}
combineChain(s2t, t2hk); | trie.build(s2t);
saveDat(datPath, trie, s2t.entrySet());
}
logger.info("简体转香港繁体词典加载成功,耗时" + (System.currentTimeMillis() - start) + "ms");
}
public static String convertToTraditionalHongKongChinese(String simplifiedChineseString)
{
return segLongest(simplifiedChineseString.toCharArray(), trie);
}
public static String convertToTraditionalHongKongChinese(char[] simplifiedChinese)
{
return segLongest(simplifiedChinese, trie);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ts\SimplifiedToHongKongChineseDictionary.java | 1 |
请完成以下Java代码 | public IAllocationRequest addQty(final IAllocationRequest request)
{
throw new AdempiereException("Adding Qty is not supported on this level");
}
@Override
public IAllocationRequest removeQty(final IAllocationRequest request)
{
throw new AdempiereException("Removing Qty is not supported on this level");
}
/**
* Returns always false because negative storages are not supported (see {@link #removeQty(IAllocationRequest)})
*
* @return false
*/
@Override
public boolean isAllowNegativeStorage()
{
return false;
}
@Override
public void markStaled()
{ | // nothing, so far, itemStorage is always database coupled, no in memory values
}
@Override
public boolean isEmpty()
{
return huStorage.isEmpty(getProductId());
}
@Override
public I_M_HU getM_HU()
{
return huStorage.getM_HU();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUProductStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class ChannelRequestMatcherRegistry
extends AbstractConfigAttributeRequestMatcherRegistry<RequiresChannelUrl> {
private ChannelRequestMatcherRegistry(ApplicationContext context) {
setApplicationContext(context);
}
@Override
protected RequiresChannelUrl chainRequestMatchersInternal(List<RequestMatcher> requestMatchers) {
return new RequiresChannelUrl(requestMatchers);
}
/**
* Adds an {@link ObjectPostProcessor} for this class.
* @param objectPostProcessor
* @return the {@link ChannelSecurityConfigurer} for further customizations
*/
public ChannelRequestMatcherRegistry withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
addObjectPostProcessor(objectPostProcessor);
return this;
}
/**
* Sets the {@link ChannelProcessor} instances to use in
* {@link ChannelDecisionManagerImpl}
* @param channelProcessors
* @return the {@link ChannelSecurityConfigurer} for further customizations
*/
public ChannelRequestMatcherRegistry channelProcessors(List<ChannelProcessor> channelProcessors) {
ChannelSecurityConfigurer.this.channelProcessors = channelProcessors;
return this;
}
/**
* Sets the {@link RedirectStrategy} instances to use in
* {@link RetryWithHttpEntryPoint} and {@link RetryWithHttpsEntryPoint}
* @param redirectStrategy
* @return the {@link ChannelSecurityConfigurer} for further customizations
*/
public ChannelRequestMatcherRegistry redirectStrategy(RedirectStrategy redirectStrategy) {
ChannelSecurityConfigurer.this.redirectStrategy = redirectStrategy;
return this;
}
}
/**
* @deprecated no replacement planned
*/ | @Deprecated
public class RequiresChannelUrl {
protected List<? extends RequestMatcher> requestMatchers;
RequiresChannelUrl(List<? extends RequestMatcher> requestMatchers) {
this.requestMatchers = requestMatchers;
}
public ChannelRequestMatcherRegistry requiresSecure() {
return requires("REQUIRES_SECURE_CHANNEL");
}
public ChannelRequestMatcherRegistry requiresInsecure() {
return requires("REQUIRES_INSECURE_CHANNEL");
}
public ChannelRequestMatcherRegistry requires(String attribute) {
return addAttribute(attribute, this.requestMatchers);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\ChannelSecurityConfigurer.java | 2 |
请完成以下Java代码 | protected ScopeImpl getScope(InterpretableExecution execution) {
return (ScopeImpl) execution.getActivity();
}
@Override
protected String getEventName() {
return org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_START;
}
@Override
protected void eventNotificationsCompleted(InterpretableExecution execution) {
ActivityImpl activity = (ActivityImpl) execution.getActivity();
ProcessDefinitionImpl processDefinition = execution.getProcessDefinition();
StartingExecution startingExecution = execution.getStartingExecution();
if (activity == startingExecution.getInitial()) {
execution.disposeStartingExecution();
execution.performOperation(ACTIVITY_EXECUTE); | } else {
List<ActivityImpl> initialActivityStack = processDefinition.getInitialActivityStack(startingExecution.getInitial());
int index = initialActivityStack.indexOf(activity);
activity = initialActivityStack.get(index + 1);
InterpretableExecution executionToUse = null;
if (activity.isScope()) {
executionToUse = (InterpretableExecution) execution.getExecutions().get(0);
} else {
executionToUse = execution;
}
executionToUse.setActivity(activity);
executionToUse.performOperation(PROCESS_START_INITIAL);
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationProcessStartInitial.java | 1 |
请完成以下Java代码 | public void setInsertClassSql(String insertClass) {
this.insertClass = insertClass;
}
public void setInsertEntrySql(String insertEntry) {
this.insertEntry = insertEntry;
}
public void setInsertObjectIdentitySql(String insertObjectIdentity) {
this.insertObjectIdentity = insertObjectIdentity;
}
public void setInsertSidSql(String insertSid) {
this.insertSid = insertSid;
}
public void setClassPrimaryKeyQuery(String selectClassPrimaryKey) {
this.selectClassPrimaryKey = selectClassPrimaryKey;
}
public void setObjectIdentityPrimaryKeyQuery(String selectObjectIdentityPrimaryKey) {
this.selectObjectIdentityPrimaryKey = selectObjectIdentityPrimaryKey;
}
public void setSidPrimaryKeyQuery(String selectSidPrimaryKey) {
this.selectSidPrimaryKey = selectSidPrimaryKey;
}
public void setUpdateObjectIdentity(String updateObjectIdentity) {
this.updateObjectIdentity = updateObjectIdentity;
}
/**
* @param foreignKeysInDatabase if false this class will perform additional FK
* constrain checking, which may cause deadlocks (the default is true, so deadlocks | * are avoided but the database is expected to enforce FKs)
*/
public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) {
this.foreignKeysInDatabase = foreignKeysInDatabase;
}
@Override
public void setAclClassIdSupported(boolean aclClassIdSupported) {
super.setAclClassIdSupported(aclClassIdSupported);
if (aclClassIdSupported) {
// Change the default insert if it hasn't been overridden
if (this.insertClass.equals(DEFAULT_INSERT_INTO_ACL_CLASS)) {
this.insertClass = DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID;
}
else {
log.debug("Insert class statement has already been overridden, so not overridding the default");
}
}
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\JdbcMutableAclService.java | 1 |
请完成以下Java代码 | public boolean hasAccess(final Access access)
{
return accesses.contains(access);
}
@Override
public Permission mergeWith(final Permission permissionFrom)
{
final TableColumnPermission columnPermissionFrom = checkCompatibleAndCast(permissionFrom);
return asNewBuilder()
.addAccesses(columnPermissionFrom.accesses)
.build();
}
public int getAD_Table_ID()
{
return resource.getAD_Table_ID();
}
public int getAD_Column_ID()
{
return resource.getAD_Column_ID();
}
public static class Builder
{
private TableColumnResource resource;
private final Set<Access> accesses = new LinkedHashSet<>();
public TableColumnPermission build()
{
return new TableColumnPermission(this);
}
public Builder setFrom(final TableColumnPermission columnPermission)
{
setResource(columnPermission.getResource());
setAccesses(columnPermission.accesses);
return this;
}
public Builder setResource(final TableColumnResource resource)
{
this.resource = resource;
return this;
}
public final Builder addAccess(final Access access)
{ | accesses.add(access);
return this;
}
public final Builder removeAccess(final Access access)
{
accesses.remove(access);
return this;
}
public final Builder setAccesses(final Set<Access> acceses)
{
accesses.clear();
accesses.addAll(acceses);
return this;
}
public final Builder addAccesses(final Set<Access> acceses)
{
accesses.addAll(acceses);
return this;
}
public final Builder removeAllAccesses()
{
accesses.clear();
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnPermission.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected URI newEndpoint(String endpoint) {
return URI.create(endpoint);
}
@Override
protected byte[] newBody(List<byte[]> list) {
return this.encoding.encode(list);
}
@Override
protected void postSpans(URI endpoint, byte[] body) throws IOException {
Map<String, String> headers = getDefaultHeaders();
if (needsCompression(body)) {
body = compress(body);
headers.put("Content-Encoding", "gzip");
}
postSpans(endpoint, headers, body);
}
abstract void postSpans(URI endpoint, Map<String, String> headers, byte[] body) throws IOException;
Map<String, String> getDefaultHeaders() {
Map<String, String> headers = new LinkedHashMap<>(); | headers.put("b3", "0");
headers.put("Content-Type", this.encoding.mediaType());
return headers;
}
private boolean needsCompression(byte[] body) {
return body.length > COMPRESSION_THRESHOLD.toBytes();
}
private byte[] compress(byte[] input) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(result)) {
gzip.write(input);
}
return result.toByteArray();
}
} | repos\spring-boot-4.0.1\module\spring-boot-zipkin\src\main\java\org\springframework\boot\zipkin\autoconfigure\HttpSender.java | 2 |
请完成以下Java代码 | protected ValidatingMigrationInstructions wrapMigrationInstructions(MigrationPlan migrationPlan, ProcessDefinitionImpl sourceProcessDefinition, ProcessDefinitionImpl targetProcessDefinition, MigrationPlanValidationReportImpl planReport) {
ValidatingMigrationInstructions validatingMigrationInstructions = new ValidatingMigrationInstructions();
for (MigrationInstruction migrationInstruction : migrationPlan.getInstructions()) {
MigrationInstructionValidationReportImpl instructionReport = new MigrationInstructionValidationReportImpl(migrationInstruction);
String sourceActivityId = migrationInstruction.getSourceActivityId();
String targetActivityId = migrationInstruction.getTargetActivityId();
if (sourceActivityId != null && targetActivityId != null) {
ActivityImpl sourceActivity = sourceProcessDefinition.findActivity(sourceActivityId);
ActivityImpl targetActivity = targetProcessDefinition.findActivity(migrationInstruction.getTargetActivityId());
if (sourceActivity != null && targetActivity != null) {
validatingMigrationInstructions.addInstruction(new ValidatingMigrationInstructionImpl(sourceActivity, targetActivity, migrationInstruction.isUpdateEventTrigger()));
}
else {
if (sourceActivity == null) {
instructionReport.addFailure("Source activity '" + sourceActivityId + "' does not exist");
}
if (targetActivity == null) {
instructionReport.addFailure("Target activity '" + targetActivityId + "' does not exist");
}
}
}
else { | if (sourceActivityId == null) {
instructionReport.addFailure("Source activity id is null");
}
if (targetActivityId == null) {
instructionReport.addFailure("Target activity id is null");
}
}
if (instructionReport.hasFailures()) {
planReport.addInstructionReport(instructionReport);
}
}
return validatingMigrationInstructions;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CreateMigrationPlanCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<List<PostResponseDto>> myPosts(Authentication auth) {
List<PostResponseDto> result = postService.myPosts(auth.getName());
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PutMapping("{id}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<String> update(@PathVariable Long id, @RequestBody PostRequestDto req, Authentication auth) {
try {
postService.update(id, req, auth.getName());
return new ResponseEntity<>("updated", HttpStatus.OK);
} catch (AccessDeniedException ade) {
return new ResponseEntity<>(ade.getMessage(), HttpStatus.FORBIDDEN);
}
} | @DeleteMapping("{id}")
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
public ResponseEntity<?> delete(@PathVariable Long id, Authentication auth) {
try {
boolean isAdmin = auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
postService.delete(id, isAdmin, auth.getName());
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (AccessDeniedException ade) {
return new ResponseEntity<>(ade.getMessage(), HttpStatus.FORBIDDEN);
} catch (NoSuchElementException nse) {
return new ResponseEntity<>(nse.getMessage(), HttpStatus.NOT_FOUND);
}
}
} | repos\tutorials-master\spring-security-modules\spring-security-authorization\spring-security-url-http-method-auth\src\main\java\com\baeldung\springsecurity\controller\PostController.java | 2 |
请完成以下Java代码 | public List<JobEntity> findJobsByProcessInstanceId(final String processInstanceId) {
return getDbSqlSession().selectList("selectJobsByProcessInstanceId", processInstanceId);
}
@Override
@SuppressWarnings("unchecked")
public List<JobEntity> findExpiredJobs(Page page) {
Date now = getClock().getCurrentTime();
return getDbSqlSession().selectList("selectExpiredJobs", now, page);
}
@Override
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) {
final String query = "selectJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
}
@Override | public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectJobCountByQueryCriteria", jobQuery);
}
@Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateJobTenantIdForDeployment", params);
}
@Override
public void resetExpiredJob(String jobId) {
Map<String, Object> params = new HashMap<String, Object>(2);
params.put("id", jobId);
getDbSqlSession().update("resetExpiredJob", params);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisJobDataManager.java | 1 |
请完成以下Java代码 | public class TenantScope implements Scope {
private Map<String, Object> scopedObjects = Collections.synchronizedMap(new HashMap<String, Object>());
private Map<String, Runnable> destructionCallbacks = Collections.synchronizedMap(new HashMap<String, Runnable>());
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
if (!scopedObjects.containsKey(name)) {
scopedObjects.put(name, objectFactory.getObject());
}
return scopedObjects.get(name);
}
@Override
public Object remove(String name) {
destructionCallbacks.remove(name);
return scopedObjects.remove(name); | }
@Override
public void registerDestructionCallback(String name, Runnable callback) {
destructionCallbacks.put(name, callback);
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return "tenant";
}
} | repos\tutorials-master\spring-core-3\src\main\java\com\baeldung\customscope\TenantScope.java | 1 |
请完成以下Java代码 | public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setC_Print_PackageInfo_ID (int C_Print_PackageInfo_ID)
{
if (C_Print_PackageInfo_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Print_PackageInfo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Print_PackageInfo_ID, Integer.valueOf(C_Print_PackageInfo_ID));
}
@Override
public int getC_Print_PackageInfo_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_PackageInfo_ID);
}
@Override
public void setName (java.lang.String Name)
{
throw new IllegalArgumentException ("Name is virtual column"); }
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public void setPageFrom (int PageFrom)
{
set_Value (COLUMNNAME_PageFrom, Integer.valueOf(PageFrom));
}
@Override
public int getPageFrom()
{
return get_ValueAsInt(COLUMNNAME_PageFrom);
}
@Override
public void setPageTo (int PageTo)
{
set_Value (COLUMNNAME_PageTo, Integer.valueOf(PageTo));
}
@Override
public int getPageTo()
{
return get_ValueAsInt(COLUMNNAME_PageTo); | }
@Override
public void setPrintServiceName (java.lang.String PrintServiceName)
{
throw new IllegalArgumentException ("PrintServiceName is virtual column"); }
@Override
public java.lang.String getPrintServiceName()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName);
}
@Override
public void setTrayNumber (int TrayNumber)
{
throw new IllegalArgumentException ("TrayNumber is virtual column"); }
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_PackageInfo.java | 1 |
请完成以下Java代码 | public class CaseFileItemOnPartImpl extends OnPartImpl implements CaseFileItemOnPart {
protected static AttributeReference<CaseFileItem> sourceRefAttribute;
protected static ChildElement<CaseFileItemTransitionStandardEvent> standardEventChild;
public CaseFileItemOnPartImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public CaseFileItem getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(CaseFileItem source) {
sourceRefAttribute.setReferenceTargetElement(this, source);
}
public CaseFileItemTransition getStandardEvent() {
CaseFileItemTransitionStandardEvent child = standardEventChild.getChild(this);
return child.getValue();
}
public void setStandardEvent(CaseFileItemTransition standardEvent) {
CaseFileItemTransitionStandardEvent child = standardEventChild.getChild(this);
child.setValue(standardEvent);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItemOnPart.class, CMMN_ELEMENT_CASE_FILE_ITEM_ON_PART)
.extendsType(OnPart.class)
.namespaceUri(CMMN11_NS) | .instanceProvider(new ModelTypeInstanceProvider<CaseFileItemOnPart>() {
public CaseFileItemOnPart newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseFileItemOnPartImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF)
.idAttributeReference(CaseFileItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
standardEventChild = sequenceBuilder.element(CaseFileItemTransitionStandardEvent.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemOnPartImpl.java | 1 |
请完成以下Java代码 | public boolean getContextAsBoolean(final String name)
{
final Object valueObj = getDocument().getDynAttribute(name);
return DisplayType.toBoolean(valueObj);
}
@Override
public int getContextAsInt(final String name)
{
final Object valueObj = getDocument().getDynAttribute(name);
if (valueObj == null)
{
return -1;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
}
else | {
return Integer.parseInt(valueObj.toString());
}
}
@Override
public ICalloutRecord getCalloutRecord()
{
return getDocument().asCalloutRecord();
}
@Override
public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id)
{
return documentField.getLookupValueById(id) != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldAsCalloutField.java | 1 |
请完成以下Java代码 | private I_PP_Order_BOMLine getCoByProductOrderBOMLine()
{
return coByProductOrderBOMLine;
}
@Override
protected ProductId getProductId()
{
return productId;
}
@Override
protected Object getAllocationRequestReferencedModel()
{
return getCoByProductOrderBOMLine();
}
@Override
protected IAllocationSource createAllocationSource()
{
final I_PP_Order_BOMLine coByProductOrderBOMLine = getCoByProductOrderBOMLine();
final PPOrderBOMLineProductStorage ppOrderBOMLineProductStorage = new PPOrderBOMLineProductStorage(coByProductOrderBOMLine);
return new GenericAllocationSourceDestination(
ppOrderBOMLineProductStorage,
coByProductOrderBOMLine // referenced model
);
}
@Override
protected IDocumentLUTUConfigurationManager createReceiptLUTUConfigurationManager()
{
final I_PP_Order_BOMLine coByProductOrderBOMLine = getCoByProductOrderBOMLine();
return huPPOrderBL.createReceiptLUTUConfigurationManager(coByProductOrderBOMLine);
}
@Override
protected ReceiptCandidateRequestProducer newReceiptCandidateRequestProducer() | {
final I_PP_Order_BOMLine coByProductOrderBOMLine = getCoByProductOrderBOMLine();
final PPOrderBOMLineId coByProductOrderBOMLineId = PPOrderBOMLineId.ofRepoId(coByProductOrderBOMLine.getPP_Order_BOMLine_ID());
final PPOrderId orderId = PPOrderId.ofRepoId(coByProductOrderBOMLine.getPP_Order_ID());
final OrgId orgId = OrgId.ofRepoId(coByProductOrderBOMLine.getAD_Org_ID());
return ReceiptCandidateRequestProducer.builder()
.orderId(orderId)
.coByProductOrderBOMLineId(coByProductOrderBOMLineId)
.orgId(orgId)
.date(getMovementDate())
.locatorId(getLocatorId())
.pickingCandidateId(getPickingCandidateId())
.build();
}
@Override
protected void addAssignedHUs(final Collection<I_M_HU> hus)
{
final I_PP_Order_BOMLine bomLine = getCoByProductOrderBOMLine();
huPPOrderBL.addAssignedHandlingUnits(bomLine, hus);
}
@Override
public IPPOrderReceiptHUProducer withPPOrderLocatorId()
{
final I_PP_Order order = huPPOrderBL.getById(PPOrderId.ofRepoId(coByProductOrderBOMLine.getPP_Order_ID()));
return locatorId(LocatorId.ofRepoId(order.getM_Warehouse_ID(), order.getM_Locator_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\CostCollectorCandidateCoProductHUProducer.java | 1 |
请完成以下Java代码 | public void setTaskId(String taskId) {
this.taskId = taskId;
}
@CamundaQueryParam("jobId")
public void setJobId(String jobId) {
this.jobId = jobId;
}
@CamundaQueryParam("jobDefinitionId")
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
@CamundaQueryParam("batchId")
public void setBatchId(String batchId) {
this.batchId = batchId;
}
@CamundaQueryParam("userId")
public void setUserId(String userId) {
this.userId = userId;
}
@CamundaQueryParam("operationId")
public void setOperationId(String operationId) {
this.operationId = operationId;
}
@CamundaQueryParam("externalTaskId")
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
@CamundaQueryParam("operationType")
public void setOperationType(String operationType) {
this.operationType = operationType;
}
@CamundaQueryParam("entityType")
public void setEntityType(String entityType) {
this.entityType = entityType;
}
@CamundaQueryParam(value = "entityTypeIn", converter = StringArrayConverter.class) | public void setEntityTypeIn(String[] entityTypes) {
this.entityTypes = entityTypes;
}
@CamundaQueryParam("category")
public void setcategory(String category) {
this.category = category;
}
@CamundaQueryParam(value = "categoryIn", converter = StringArrayConverter.class)
public void setCategoryIn(String[] categories) {
this.categories = categories;
}
@CamundaQueryParam("property")
public void setProperty(String property) {
this.property = property;
}
@CamundaQueryParam(value = "afterTimestamp", converter = DateConverter.class)
public void setAfterTimestamp(Date after) {
this.afterTimestamp = after;
}
@CamundaQueryParam(value = "beforeTimestamp", converter = DateConverter.class)
public void setBeforeTimestamp(Date before) {
this.beforeTimestamp = before;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogQueryDto.java | 1 |
请完成以下Java代码 | public boolean isDeleted(DbEntity dbEntity) {
CachedDbEntity cachedDbEntity = getCachedEntity(dbEntity);
if(cachedDbEntity == null) {
return false;
} else {
return cachedDbEntity.getEntityState() == DELETED_MERGED
|| cachedDbEntity.getEntityState() == DELETED_PERSISTENT
|| cachedDbEntity.getEntityState() == DELETED_TRANSIENT;
}
}
/**
* Allows checking whether the provided entity is present in the cache
* and is {@link DbEntityState#TRANSIENT}.
*
* @param dbEntity the entity to check
* @return true if the provided entity is present in the cache and is
* {@link DbEntityState#TRANSIENT}.
*/
public boolean isTransient(DbEntity dbEntity) {
CachedDbEntity cachedDbEntity = getCachedEntity(dbEntity);
if(cachedDbEntity == null) {
return false;
} else {
return cachedDbEntity.getEntityState() == TRANSIENT;
}
}
public List<CachedDbEntity> getCachedEntities() {
List<CachedDbEntity> result = new ArrayList<CachedDbEntity>();
for (Map<String, CachedDbEntity> typeCache : cachedEntites.values()) {
result.addAll(typeCache.values());
}
return result;
}
/**
* Sets an object to a deleted state. It will not be removed from the cache but
* transition to one of the DELETED states, depending on it's current state.
*
* @param dbEntity the object to mark deleted.
*/
public void setDeleted(DbEntity dbEntity) {
CachedDbEntity cachedEntity = getCachedEntity(dbEntity);
if(cachedEntity != null) {
if(cachedEntity.getEntityState() == TRANSIENT) {
cachedEntity.setEntityState(DELETED_TRANSIENT);
} else if(cachedEntity.getEntityState() == PERSISTENT){
cachedEntity.setEntityState(DELETED_PERSISTENT);
} else if(cachedEntity.getEntityState() == MERGED){ | cachedEntity.setEntityState(DELETED_MERGED);
}
} else {
// put a deleted merged into the cache
CachedDbEntity cachedDbEntity = new CachedDbEntity();
cachedDbEntity.setEntity(dbEntity);
cachedDbEntity.setEntityState(DELETED_MERGED);
putInternal(cachedDbEntity);
}
}
public void undoDelete(DbEntity dbEntity) {
CachedDbEntity cachedEntity = getCachedEntity(dbEntity);
if (cachedEntity.getEntityState() == DbEntityState.DELETED_TRANSIENT) {
cachedEntity.setEntityState(DbEntityState.TRANSIENT);
}
else {
cachedEntity.setEntityState(DbEntityState.MERGED);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\cache\DbEntityCache.java | 1 |
请完成以下Java代码 | public int getAD_BoilerPlate_Var_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_BoilerPlate_Var_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Rule getAD_Rule() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Rule_ID, org.compiere.model.I_AD_Rule.class);
}
@Override
public void setAD_Rule(org.compiere.model.I_AD_Rule AD_Rule)
{
set_ValueFromPO(COLUMNNAME_AD_Rule_ID, org.compiere.model.I_AD_Rule.class, AD_Rule);
}
/** Set Rule.
@param AD_Rule_ID Rule */
@Override
public void setAD_Rule_ID (int AD_Rule_ID)
{
if (AD_Rule_ID < 1)
set_Value (COLUMNNAME_AD_Rule_ID, null);
else
set_Value (COLUMNNAME_AD_Rule_ID, Integer.valueOf(AD_Rule_ID));
}
/** Get Rule.
@return Rule */
@Override
public int getAD_Rule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Rule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Validation code.
@param Code
Validation Code
*/
@Override
public void setCode (java.lang.String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validation code.
@return Validation Code
*/
@Override
public java.lang.String getCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_Code);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name); | }
/**
* Type AD_Reference_ID=540047
* Reference name: AD_BoilerPlate_VarType
*/
public static final int TYPE_AD_Reference_ID=540047;
/** SQL = S */
public static final String TYPE_SQL = "S";
/** Rule Engine = R */
public static final String TYPE_RuleEngine = "R";
/** Set Type.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Type.
@return Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Var.java | 1 |
请完成以下Java代码 | public Timestamp getLastSynchronized ()
{
return (Timestamp)get_Value(COLUMNNAME_LastSynchronized);
}
/** 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_CM_BroadcastServer.java | 1 |
请完成以下Java代码 | public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suffix.
@param Suffix | Suffix after the number
*/
public void setSuffix (String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
/** Get Suffix.
@return Suffix after the number
*/
public String getSuffix ()
{
return (String)get_Value(COLUMNNAME_Suffix);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User implements UserDetails {
@Id
private String username;
private String password;
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public List<GrantedAuthority> getAuthorities() {
return null;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean isAccountNonExpired() { | return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
} | repos\piggymetrics-master\auth-service\src\main\java\com\piggymetrics\auth\domain\User.java | 2 |
请完成以下Java代码 | public String getDriver()
{
return driver;
}
public void setDriver(String driver)
{
this.driver = driver;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getUsername() | {
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
} | repos\Spring-Boot-Advanced-Projects-main\spring-propertysource-example\src\main\java\net\alanbinu\springboot2\springpropertysourceexample\DataSourceConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JakartaEEMigrationService {
public static final JakartaEEMigrationService INSTANCE = new JakartaEEMigrationService();
private static final String MIGRATED_FILENAME_PREFIX = "jakartaee-";
private static final String MIGRATED_FILENAME_PATTERN = MIGRATED_FILENAME_PREFIX.concat("%s");
private static <T> T requireObject(T object, Predicate<T> predicate, String message, Object... arguments) {
if (!predicate.test(object)) {
throw new IllegalArgumentException(String.format(message, arguments));
}
return object;
}
public Path migrate(Path warFile) {
Path resolvedWarFile = requireObject(warFile, (Path path) -> Objects.nonNull(path) && Files.exists(path),
"The Path to the WAR file [%s] must not be null and exist", warFile);
String warFileName = resolvedWarFile.getFileName().toString();
String migratedWarFileName = String.format(MIGRATED_FILENAME_PATTERN, warFileName);
File migratedWarFile = new File(resolvedWarFile.getParent().toFile(), migratedWarFileName);
if (!migratedWarFile.isFile()) {
try {
migratedWarFile.createNewFile();
Migration migration = new Migration();
migration.setSource(resolvedWarFile.toFile());
migration.setDestination(migratedWarFile); | migration.setEESpecProfile(EESpecProfile.EE);
migration.execute();
}
catch (IOException cause) {
throw new JavaEEJakartaEEMigrationException(
String.format("Failed to migrate Java EE WAR file [%s] to Jakarta EE", warFile), cause);
}
}
return migratedWarFile.toPath();
}
protected static class JavaEEJakartaEEMigrationException extends RuntimeException {
public JavaEEJakartaEEMigrationException() { }
public JavaEEJakartaEEMigrationException(String message) {
super(message);
}
public JavaEEJakartaEEMigrationException(Throwable cause) {
super(cause);
}
public JavaEEJakartaEEMigrationException(String message, Throwable cause) {
super(message, cause);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-jetty11\src\main\java\org\springframework\geode\cache\service\support\JakartaEEMigrationService.java | 2 |
请完成以下Java代码 | public BigDecimal computeQtyOrdered(@NonNull final I_M_ShipmentSchedule shipmentSchedule)
{
if (shipmentSchedule.isClosed())
{
return shipmentSchedule.getQtyDelivered();
}
final boolean hasQtyOrderedOverride = !InterfaceWrapperHelper.isNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyOrdered_Override);
if (hasQtyOrderedOverride)
{
return shipmentSchedule.getQtyOrdered_Override();
}
return shipmentSchedule.getQtyOrdered_Calculated();
}
@Nullable
@Override
public ZonedDateTime getDeliveryDate(@NonNull final I_M_ShipmentSchedule sched)
{
return TimeUtil.asZonedDateTime(
CoalesceUtil.coalesceSuppliers(
sched::getDeliveryDate_Override,
sched::getDeliveryDate),
OrgId.ofRepoId(sched.getAD_Org_ID()));
}
@Override
public ZonedDateTime getPreparationDate(@NonNull final I_M_ShipmentSchedule sched) | {
final ZonedDateTime preparationDateOverride = TimeUtil.asZonedDateTime(sched.getPreparationDate_Override());
if (preparationDateOverride != null)
{
return preparationDateOverride;
}
if (sched.getPreparationDate() != null)
{
return TimeUtil.asZonedDateTime(sched.getPreparationDate());
}
if (sched.getC_Order_ID() > 0)
{
final I_C_Order order = sched.getC_Order();
return CoalesceUtil.coalesceSuppliers(
() -> TimeUtil.asZonedDateTime(order.getPreparationDate()),
() -> TimeUtil.asZonedDateTime(order.getDatePromised()));
}
return SystemTime.asZonedDateTime();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleEffectiveBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class KotlinxSerializationJsonCodecConfiguration {
@Bean
@ConditionalOnBean(Json.class)
CodecCustomizer kotlinxJsonCodecCustomizer(Json json, ResourceLoader resourceLoader) {
ClassLoader classLoader = resourceLoader.getClassLoader();
boolean hasAnyJsonSupport = ClassUtils.isPresent("tools.jackson.databind.json.JsonMapper", classLoader)
|| ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader)
|| ClassUtils.isPresent("com.google.gson.Gson", classLoader);
return (configurer) -> {
CodecConfigurer.DefaultCodecs defaults = configurer.defaultCodecs();
defaults.kotlinSerializationJsonEncoder(hasAnyJsonSupport ? new KotlinSerializationJsonEncoder(json)
: new KotlinSerializationJsonEncoder(json, (type) -> true));
defaults.kotlinSerializationJsonDecoder(hasAnyJsonSupport ? new KotlinSerializationJsonDecoder(json)
: new KotlinSerializationJsonDecoder(json, (type) -> true));
};
}
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(HttpCodecsProperties.class)
static class DefaultCodecsConfiguration {
@Bean
DefaultCodecCustomizer defaultCodecCustomizer(HttpCodecsProperties httpCodecProperties) {
return new DefaultCodecCustomizer(httpCodecProperties.isLogRequestDetails(),
httpCodecProperties.getMaxInMemorySize());
}
static final class DefaultCodecCustomizer implements CodecCustomizer, Ordered {
private final boolean logRequestDetails;
private final @Nullable DataSize maxInMemorySize;
DefaultCodecCustomizer(boolean logRequestDetails, @Nullable DataSize maxInMemorySize) {
this.logRequestDetails = logRequestDetails;
this.maxInMemorySize = maxInMemorySize;
}
@Override
public void customize(CodecConfigurer configurer) {
PropertyMapper map = PropertyMapper.get();
CodecConfigurer.DefaultCodecs defaultCodecs = configurer.defaultCodecs();
defaultCodecs.enableLoggingRequestDetails(this.logRequestDetails);
map.from(this.maxInMemorySize).asInt(DataSize::toBytes).to(defaultCodecs::maxInMemorySize);
} | @Override
public int getOrder() {
return 0;
}
}
}
static class NoJacksonOrJackson2Preferred extends AnyNestedCondition {
NoJacksonOrJackson2Preferred() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
static class NoJackson {
}
@ConditionalOnProperty(name = "spring.http.codecs.preferred-json-mapper", havingValue = "jackson2")
static class Jackson2Preferred {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-codec\src\main\java\org\springframework\boot\http\codec\autoconfigure\CodecsAutoConfiguration.java | 2 |
请完成以下Java代码 | public void execute(PvmExecutionImpl execution) {
execution.activityInstanceStarted();
execution.continueIfExecutionDoesNotAffectNextOperation(new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
if (execution.getActivity().isScope()) {
execution.dispatchEvent(null);
}
return null;
}
}, new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
ActivityBehavior activityBehavior = getActivityBehavior(execution);
ActivityImpl activity = execution.getActivity();
LOG.debugExecutesActivity(execution, activity, activityBehavior.getClass().getName());
try {
activityBehavior.execute(execution);
} catch (RuntimeException e) { | throw e;
} catch (Exception e) {
throw new PvmException("couldn't execute activity <" + activity.getProperty("type") + " id=\"" + activity.getId() + "\" ...>: " + e.getMessage(), e);
}
return null;
}
}, execution);
}
public String getCanonicalName() {
return "activity-execute";
}
public boolean isAsyncCapable() {
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityExecute.java | 1 |
请完成以下Java代码 | public byte[] cbcEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
}
public byte[] cbcDecrypt(SecretKey key, IvParameterSpec iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
public byte[] cfbEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
}
public byte[] cfbDecrypt(SecretKey key, IvParameterSpec iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
public byte[] ofbEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/OFB32/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
}
public byte[] ofbDecrypt(SecretKey key, IvParameterSpec iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/OFB32/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
public byte[][] ctrEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); | cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return new byte[][] { cipher.getIV(), cipher.doFinal(data) };
}
public byte[] ctrDecrypt(SecretKey key, byte[] iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
return cipher.doFinal(cipherText);
}
public byte[][] gcmEncrypt(SecretKey key, byte[] iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
byte[] ciphertext = cipher.doFinal(data);
return new byte[][] { iv, ciphertext };
}
public byte[] gcmDecrypt(SecretKey key, byte[] iv, byte[] ciphertext) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
byte[] plaintext = cipher.doFinal(ciphertext);
return plaintext;
}
} | repos\tutorials-master\core-java-modules\core-java-security-3\src\main\java\com\baeldung\crypto\CryptoDriver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeService {
private WebClient webClient;
public static String PATH_PARAM_BY_ID = "/employee/{id}";
public static String ADD_EMPLOYEE = "/employee";
public EmployeeService(WebClient webClient) {
this.webClient = webClient;
}
public EmployeeService(String baseUrl) {
this.webClient = WebClient.create(baseUrl);
}
public Mono<Employee> getEmployeeById(Integer employeeId) {
return webClient
.get()
.uri(PATH_PARAM_BY_ID, employeeId)
.retrieve()
.bodyToMono(Employee.class);
}
public Mono<Employee> addNewEmployee(Employee newEmployee) {
return webClient
.post()
.uri(ADD_EMPLOYEE)
.syncBody(newEmployee)
.retrieve().
bodyToMono(Employee.class);
}
public Mono<Employee> updateEmployee(Integer employeeId, Employee updateEmployee) {
return webClient | .put()
.uri(PATH_PARAM_BY_ID,employeeId)
.syncBody(updateEmployee)
.retrieve()
.bodyToMono(Employee.class);
}
public Mono<String> deleteEmployeeById(Integer employeeId) {
return webClient
.delete()
.uri(PATH_PARAM_BY_ID,employeeId)
.retrieve()
.bodyToMono(String.class);
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\reactive\service\EmployeeService.java | 2 |
请完成以下Java代码 | public int getR_MailText_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_MailText_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Subject.
@param Subject
Email Message Subject
*/
public void setSubject (String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Subject.
@return Email Message Subject
*/
public String getSubject ()
{
return (String)get_Value(COLUMNNAME_Subject);
}
public I_W_MailMsg getW_MailMsg() throws RuntimeException | {
return (I_W_MailMsg)MTable.get(getCtx(), I_W_MailMsg.Table_Name)
.getPO(getW_MailMsg_ID(), get_TrxName()); }
/** Set Mail Message.
@param W_MailMsg_ID
Web Store Mail Message Template
*/
public void setW_MailMsg_ID (int W_MailMsg_ID)
{
if (W_MailMsg_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, Integer.valueOf(W_MailMsg_ID));
}
/** Get Mail Message.
@return Web Store Mail Message Template
*/
public int getW_MailMsg_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_MailMsg_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_UserMail.java | 1 |
请完成以下Java代码 | public int getAD_Table_ID()
{
return Services.get(IADTableDAO.class).retrieveTableId(I_C_Async_Batch.Table_Name);
}
@Override
public int getRecord_ID()
{
return asyncBatch.getC_Async_Batch_ID();
}
@Override
public EMail sendEMail(org.compiere.model.I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributesOld)
{
final I_AD_Client client = Services.get(IClientDAO.class).retriveClient(ctx, Env.getAD_Client_ID(ctx));
final BoilerPlateContext attributesEffective;
{
final BoilerPlateContext.Builder attributesBuilder = attributesOld.toBuilder();
attributesBuilder.setSourceDocumentFromObject(asyncBatch);
// try to set language; take first from partner; if does not exists, take it from client
final org.compiere.model.I_AD_User user = InterfaceWrapperHelper.create(ctx, asyncBatch.getCreatedBy(), I_AD_User.class, ITrx.TRXNAME_None);
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(user.getC_BPartner_ID());
final I_C_BPartner partner = bpartnerId != null
? Services.get(IBPartnerDAO.class).getById(bpartnerId)
: null;
String adLanguage = "";
if (partner != null && partner.getC_BPartner_ID() > 0)
{
adLanguage = partner.getAD_Language();
}
if (Check.isEmpty(adLanguage, true))
{
adLanguage = client.getAD_Language();
}
attributesBuilder.setAD_Language(adLanguage);
attributesEffective = attributesBuilder.build();
}
//
final String message = text.getTextSnippetParsed(attributesEffective);
//
if (Check.isEmpty(message, true))
{
return null;
//
}
Check.assume(asyncBatch.getCreatedBy() > 0, "CreatedBy > 0");
notificationBL.send(UserNotificationRequest.builder()
.recipientUserId(UserId.ofRepoId(asyncBatch.getCreatedBy()))
.subjectPlain(text.getSubject())
.contentPlain(message)
.targetAction(TargetRecordAction.of(TableRecordReference.of(asyncBatch)))
.build());
return null; | }
}, false);
isSent = true;
}
catch (Exception e)
{
isSent = false;
}
finally
{
final int asyncBatch_id = asyncBatch.getC_Async_Batch_ID();
final String toEmail = InterfaceWrapperHelper.create(ctx, asyncBatch.getCreatedBy(), I_AD_User.class, trxName).getEMail();
if (isSent)
{
logger.warn("Async batch {} was notified by email {}", asyncBatch_id, toEmail);
}
else
{
logger.warn("Async batch {} was not notified by email {} ", asyncBatch_id, toEmail);
}
}
}
/**
* Send note to the user who created the async batch with the result
*/
public void sendNote(final I_C_Async_Batch asyncBatch)
{
asyncBatchBL.getAsyncBatchType(asyncBatch)
.orElseThrow(() -> new AdempiereException("Async Batch type should not be null for async batch " + asyncBatch.getC_Async_Batch_ID()));
asyncBatchListener.applyListener(asyncBatch);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\async\spi\impl\NotifyAsyncBatch.java | 1 |
请完成以下Java代码 | public void setC_Queue_WorkPackage_Param_ID (int C_Queue_WorkPackage_Param_ID)
{
if (C_Queue_WorkPackage_Param_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Param_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Param_ID, Integer.valueOf(C_Queue_WorkPackage_Param_ID));
}
/** Get Workpackage parameter.
@return Workpackage parameter */
@Override
public int getC_Queue_WorkPackage_Param_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Param_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Date.
@param P_Date
Prozess-Parameter
*/
@Override
public void setP_Date (java.sql.Timestamp P_Date)
{
set_Value (COLUMNNAME_P_Date, P_Date);
}
/** Get Process Date.
@return Prozess-Parameter
*/
@Override
public java.sql.Timestamp getP_Date ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_P_Date);
}
/** Set Process Number.
@param P_Number
Prozess-Parameter
*/
@Override
public void setP_Number (java.math.BigDecimal P_Number)
{
set_Value (COLUMNNAME_P_Number, P_Number);
}
/** Get Process Number.
@return Prozess-Parameter
*/
@Override
public java.math.BigDecimal getP_Number ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Process String.
@param P_String
Prozess-Parameter
*/ | @Override
public void setP_String (java.lang.String P_String)
{
set_Value (COLUMNNAME_P_String, P_String);
}
/** Get Process String.
@return Prozess-Parameter
*/
@Override
public java.lang.String getP_String ()
{
return (java.lang.String)get_Value(COLUMNNAME_P_String);
}
/** Set Parameter Name.
@param ParameterName Parameter Name */
@Override
public void setParameterName (java.lang.String ParameterName)
{
set_ValueNoCheck (COLUMNNAME_ParameterName, ParameterName);
}
/** Get Parameter Name.
@return Parameter Name */
@Override
public java.lang.String getParameterName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ParameterName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Param.java | 1 |
请完成以下Java代码 | public class UserDto {
@JMap
private long id;
@JMap("email")
private String username;
@JMap("birthDate")
private int age;
@JMapConversion(from={"birthDate"}, to={"age"})
public int conversion(LocalDate birthDate){
return Period.between(birthDate, LocalDate.now()).getYears();
}
// constructors
public UserDto() {
super();
}
public UserDto(long id, String username, int age) {
super();
this.id = id;
this.username = username;
this.age = age;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
} | public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]";
}
} | repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\jmapper\UserDto.java | 1 |
请完成以下Java代码 | public String set(@RequestParam("name") String name, @RequestParam("value") String value) {
valueOperations.set(name, value);
return valueOperations.get(name);
}
@RequestMapping("/redis/setObject")
public String setObject(@RequestParam("name") String name) {
User user = new User();
user.setId(RandomUtils.nextInt());
user.setName(name);
user.setBirthday(new Date());
List<String> list = new ArrayList<>();
list.add("sing");
list.add("run");
user.setInteresting(list);
Map<String, Object> map = new HashMap<>();
map.put("hasHouse", "yes");
map.put("hasCar", "no");
map.put("hasKid", "no");
user.setOthers(map);
redisOptService.set(name, user, 30000);
User userValue = (User) redisOptService.get(name);
return userValue.toString();
}
@GetMapping("/redis/lock")
public String lock(@RequestParam("key") String key) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
redisLockService.lock(key);
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace(); | }
System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
redisLockService.unlock(key);
}
).start();
}
return "OK";
}
@GetMapping("/redis/sentinel/set")
public String sentinelSet(@RequestParam("name") String name) {
redisOptService.set("name", name, 60000);
return redisOptService.getStringValue("name");
}
} | repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\RedisController.java | 1 |
请完成以下Java代码 | class NotifierTask implements Runnable {
private final Connection conn;
private final CountDownLatch stopLatch = new CountDownLatch(1);
NotifierTask(Connection conn) {
this.conn = conn;
}
void kill() {
try {
this.conn.close();
stopLatch.await(10, TimeUnit.SECONDS);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public void run() {
startLatch.countDown();
try (Statement st = conn.createStatement()) {
log.debug("notifierTask: enabling notifications for channel {}", channelName);
st.execute("LISTEN " + channelName);
PGConnection pgConn = conn.unwrap(PGConnection.class);
while (!Thread.currentThread()
.isInterrupted()) {
log.debug("notifierTask: wainting for notifications. channel={}", channelName);
PGNotification[] nts = pgConn.getNotifications();
log.debug("notifierTask: processing {} notification(s)", nts.length);
for (PGNotification n : nts) {
Message<?> msg = convertNotification(n);
getDispatcher().dispatch(msg);
}
}
} catch (SQLException sex) {
// TODO: Handle exceptions
} finally {
stopLatch.countDown();
}
}
@SuppressWarnings("unchecked")
private Message<?> convertNotification(PGNotification n) {
String payload = n.getParameter();
try {
JsonNode root = om.readTree(payload); | if (!root.isObject()) {
return new ErrorMessage(new IllegalArgumentException("Message is not a JSON Object"));
}
Map<String, Object> hdr;
JsonNode headers = root.path(HEADER_FIELD);
if (headers.isObject()) {
hdr = om.treeToValue(headers, Map.class);
} else {
hdr = Collections.emptyMap();
}
JsonNode body = root.path(BODY_FIELD);
return MessageBuilder
.withPayload(body.isTextual()?body.asText():body)
.copyHeaders(hdr)
.build();
} catch (Exception ex) {
return new ErrorMessage(ex);
}
}
}
} | repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\postgresqlnotify\PostgresSubscribableChannel.java | 1 |
请完成以下Java代码 | public class GetEnabledActivitiesForAdhocSubProcessCmd implements Command<List<FlowNode>>, Serializable {
private static final long serialVersionUID = 1L;
protected String executionId;
public GetEnabledActivitiesForAdhocSubProcessCmd(String executionId) {
this.executionId = executionId;
}
public List<FlowNode> execute(CommandContext commandContext) {
ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(executionId);
if (execution == null) {
throw new ActivitiObjectNotFoundException(
"No execution found for id '" + executionId + "'",
ExecutionEntity.class
);
}
if (!(execution.getCurrentFlowElement() instanceof AdhocSubProcess)) {
throw new ActivitiException(
"The current flow element of the requested execution is not an ad-hoc sub process"
);
}
List<FlowNode> enabledFlowNodes = new ArrayList<FlowNode>();
AdhocSubProcess adhocSubProcess = (AdhocSubProcess) execution.getCurrentFlowElement();
// if sequential ordering, only one child execution can be active, so no enabled activities
if (adhocSubProcess.hasSequentialOrdering()) {
if (execution.getExecutions().size() > 0) {
return enabledFlowNodes; | }
}
for (FlowElement flowElement : adhocSubProcess.getFlowElements()) {
if (flowElement instanceof FlowNode) {
FlowNode flowNode = (FlowNode) flowElement;
if (flowNode.getIncomingFlows().size() == 0) {
enabledFlowNodes.add(flowNode);
}
}
}
return enabledFlowNodes;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetEnabledActivitiesForAdhocSubProcessCmd.java | 1 |
请完成以下Java代码 | private void removeAddressDocumentById(final DocumentId addressDocId)
{
final Document addressDocRemoved = id2addressDoc.remove(addressDocId);
logger.trace("Removed from repository by ID={}: {}", addressDocId, addressDocRemoved);
}
private Document getInnerAddressDocument(final DocumentId addressDocId)
{
final Document addressDoc = id2addressDoc.get(addressDocId);
if (addressDoc == null)
{
throw new DocumentNotFoundException(DocumentType.Address, AddressDescriptor.DocumentTypeId, addressDocId);
}
return addressDoc;
}
public Document getAddressDocumentForReading(final int addressDocIdInt)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
return getInnerAddressDocument(addressDocId).copy(CopyMode.CheckInReadonly, NullDocumentChangesCollector.instance);
}
private Document getAddressDocumentForWriting(final DocumentId addressDocId, final IDocumentChangesCollector changesCollector)
{
return getInnerAddressDocument(addressDocId).copy(CopyMode.CheckOutWritable, changesCollector);
}
public void processAddressDocumentChanges(final int addressDocIdInt, final List<JSONDocumentChangedEvent> events, final IDocumentChangesCollector changesCollector)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
final Document addressDoc = getAddressDocumentForWriting(addressDocId, changesCollector);
addressDoc.processValueChanges(events, REASON_ProcessAddressDocumentChanges);
trxManager
.getCurrentTrxListenerManagerOrAutoCommit().newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> putAddressDocument(addressDoc));
}
public LookupValue complete(final int addressDocIdInt, @Nullable final List<JSONDocumentChangedEvent> events)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
final Document addressDoc = getAddressDocumentForWriting(addressDocId, NullDocumentChangesCollector.instance); | if (events != null && !events.isEmpty())
{
addressDoc.processValueChanges(events, REASON_ProcessAddressDocumentChanges);
}
final I_C_Location locationRecord = createC_Location(addressDoc);
trxManager
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> removeAddressDocumentById(addressDocId));
final String locationStr = locationBL.mkAddress(locationRecord);
return IntegerLookupValue.of(locationRecord.getC_Location_ID(), locationStr);
}
private I_C_Location createC_Location(final Document locationDoc)
{
final I_C_Location locationRecord = InterfaceWrapperHelper.create(Env.getCtx(), I_C_Location.class, ITrx.TRXNAME_ThreadInherited);
locationDoc.getFieldViews()
.forEach(locationField -> locationField
.getDescriptor()
.getDataBindingNotNull(AddressFieldBinding.class)
.writeValue(locationRecord, locationField));
locationDAO.save(locationRecord);
return locationRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRepository.java | 1 |
请完成以下Java代码 | public DocumentId getASIDescriptorId()
{
return asiDescriptorId;
}
public String getCaption(final String adLanguage)
{
return caption.translate(adLanguage);
}
public String getDescription(final String adLanguage)
{
return description.translate(adLanguage);
}
public List<DocumentLayoutElementDescriptor> getElements()
{
return elements;
}
public static final class Builder
{
public DocumentId asiDescriptorId;
private ITranslatableString caption;
private ITranslatableString description;
private final List<DocumentLayoutElementDescriptor.Builder> elementBuilders = new ArrayList<>();
private Builder()
{
super();
}
public ASILayout build()
{
return new ASILayout(this);
}
private List<DocumentLayoutElementDescriptor> buildElements()
{
return elementBuilders
.stream()
.map(elementBuilder -> elementBuilder.build())
.collect(GuavaCollectors.toImmutableList());
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("asiDescriptorId", asiDescriptorId)
.add("caption", caption)
.add("elements-count", elementBuilders.size())
.toString();
}
public Builder setASIDescriptorId(final DocumentId asiDescriptorId) | {
this.asiDescriptorId = asiDescriptorId;
return this;
}
public Builder setCaption(final ITranslatableString caption)
{
this.caption = caption;
return this;
}
public Builder setDescription(final ITranslatableString description)
{
this.description = description;
return this;
}
public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder)
{
Check.assumeNotNull(elementBuilder, "Parameter elementBuilder is not null");
elementBuilders.add(elementBuilder);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASILayout.java | 1 |
请完成以下Java代码 | public boolean isIgnoreDataAccessException() {
return ignoreDataAccessException;
}
public void setIgnoreDataAccessException(boolean ignoreDataAccessException) {
this.ignoreDataAccessException = ignoreDataAccessException;
}
public CamundaBpmProperties getCamundaBpmProperties() {
return camundaBpmProperties;
}
public void setCamundaBpmProperties(CamundaBpmProperties camundaBpmProperties) {
this.camundaBpmProperties = camundaBpmProperties;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(jdbcTemplate, "a jdbc template must be set");
Assert.notNull(camundaBpmProperties, "Camunda Platform properties must be set");
String historyLevelDefault = camundaBpmProperties.getHistoryLevelDefault();
if (StringUtils.hasText(historyLevelDefault)) {
defaultHistoryLevel = historyLevelDefault;
}
}
@Override
public String determineHistoryLevel() {
Integer historyLevelFromDb = null;
try {
historyLevelFromDb = jdbcTemplate.queryForObject(getSql(), Integer.class);
log.debug("found history '{}' in database", historyLevelFromDb);
} catch (DataAccessException e) {
if (ignoreDataAccessException) {
log.warn("unable to fetch history level from database: {}", e.getMessage());
log.debug("unable to fetch history level from database", e);
} else {
throw e;
}
}
return getHistoryLevelFrom(historyLevelFromDb);
} | protected String getSql() {
String tablePrefix = camundaBpmProperties.getDatabase().getTablePrefix();
if (tablePrefix == null) {
tablePrefix = "";
}
return SQL_TEMPLATE.replace(TABLE_PREFIX_PLACEHOLDER, tablePrefix);
}
protected String getHistoryLevelFrom(Integer historyLevelFromDb) {
String result = defaultHistoryLevel;
if (historyLevelFromDb != null) {
for (HistoryLevel historyLevel : historyLevels) {
if (historyLevel.getId() == historyLevelFromDb.intValue()) {
result = historyLevel.getName();
log.debug("found matching history level '{}'", result);
break;
}
}
}
return result;
}
public void addCustomHistoryLevels(Collection<HistoryLevel> customHistoryLevels) {
historyLevels.addAll(customHistoryLevels);
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\jdbc\HistoryLevelDeterminatorJdbcTemplateImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static final class AdvisorWrapper
implements PointcutAdvisor, MethodInterceptor, Ordered, AopInfrastructureBean {
private final AuthorizationAdvisor advisor;
private AdvisorWrapper(AuthorizationAdvisor advisor) {
this.advisor = advisor;
}
public static AdvisorWrapper of(AuthorizationAdvisor advisor) {
return new AdvisorWrapper(advisor);
}
@Override
public Advice getAdvice() {
return this.advisor.getAdvice();
} | @Override
public Pointcut getPointcut() {
return this.advisor.getPointcut();
}
@Override
public int getOrder() {
return this.advisor.getOrder();
}
@Nullable
@Override
public Object invoke(@NonNull MethodInvocation invocation) throws Throwable {
return this.advisor.invoke(invocation);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\MethodSecurityAdvisorRegistrar.java | 2 |
请完成以下Java代码 | private static int parsePort(String value) {
StringBuilder digits = new StringBuilder();
for (char chr : String.valueOf(value).toCharArray()) {
if (Character.isDigit(chr)) {
digits.append(chr);
}
}
return digits.length() > 0 ? Integer.parseInt(digits.toString()) : DEFAULT_LOCATOR_PORT;
}
/**
* Construct a new {@link Locator} initialized with the {@link String host} and {@link Integer port}
* on which this {@link Locator} is running and listening for connections.
*
* @param host {@link String} containing the name of the host on which this {@link Locator} is running.
* @param port {@link Integer} specifying the port number on which this {@link Locator} is listening.
*/
private Locator(String host, Integer port) {
this.host = host;
this.port = port;
}
/**
* Return the {@link String name} of the host on which this {@link Locator} is running.
*
* Defaults to {@literal localhost}.
*
* @return the {@link String name} of the host on which this {@link Locator} is running.
*/
public String getHost() {
return StringUtils.hasText(this.host) ? this.host : DEFAULT_LOCATOR_HOST;
}
/**
* Returns the {@link Integer port} on which this {@link Locator} is listening.
*
* Defaults to {@literal 10334}.
*
* @return the {@link Integer port} on which this {@link Locator} is listening.
*/
public int getPort() {
return this.port != null ? this.port : DEFAULT_LOCATOR_PORT;
} | @Override
public int compareTo(Locator other) {
int result = this.getHost().compareTo(other.getHost());
return result != 0 ? result : (this.getPort() - other.getPort());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Locator)) {
return false;
}
Locator that = (Locator) obj;
return this.getHost().equals(that.getHost())
&& this.getPort() == that.getPort();
}
@Override
public int hashCode() {
int hashValue = 17;
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getHost());
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPort());
return hashValue;
}
@Override
public String toString() {
return String.format("%s[%d]", getHost(), getPort());
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\CloudCacheService.java | 1 |
请完成以下Java代码 | public String toString()
{
return ObjectUtils.toString(this);
}
private int getDisplayType()
{
Check.assume(displayType > 0, "displayType > 0");
return displayType;
}
public VPanelFormFieldBuilder setDisplayType(int displayType)
{
this.displayType = displayType;
return this;
}
private String getHeader()
{
// null allowed
return header;
}
/**
* @param header String which is Displayed as Label.
*/
public VPanelFormFieldBuilder setHeader(String header)
{
this.header = header;
return this;
}
private String getColumnName()
{
Check.assumeNotEmpty(columnName, "columnName not empty");
return columnName;
}
/**
* @param columnName Will be the name of the GridField.
*/
public VPanelFormFieldBuilder setColumnName(String columnName)
{
this.columnName = columnName;
return this;
}
private boolean isSameLine()
{
return sameLine;
}
/**
* Default: {@link #DEFAULT_SameLine}
*
* @param sameLine If true, the new Field will be added in the same line.
*/
public VPanelFormFieldBuilder setSameLine(boolean sameLine)
{
this.sameLine = sameLine;
return this;
}
private boolean isMandatory()
{
return mandatory;
}
/**
* Default: {@link #DEFAULT_Mandatory}
*
* @param mandatory true if this field shall be marked as mandatory
*/
public VPanelFormFieldBuilder setMandatory(boolean mandatory)
{
this.mandatory = mandatory;
return this;
}
private boolean isAutocomplete() | {
if (autocomplete != null)
{
return autocomplete;
}
// if Search, always auto-complete
if (DisplayType.Search == displayType)
{
return true;
}
return false;
}
public VPanelFormFieldBuilder setAutocomplete(boolean autocomplete)
{
this.autocomplete = autocomplete;
return this;
}
private int getAD_Column_ID()
{
// not set is allowed
return AD_Column_ID;
}
/**
* @param AD_Column_ID Column for lookups.
*/
public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID)
{
this.AD_Column_ID = AD_Column_ID;
return this;
}
public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName)
{
return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID());
}
private EventListener getEditorListener()
{
// null allowed
return editorListener;
}
/**
* @param listener VetoableChangeListener that gets called if the field is changed.
*/
public VPanelFormFieldBuilder setEditorListener(EventListener listener)
{
this.editorListener = listener;
return this;
}
public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel)
{
this.bindEditorToModel = bindEditorToModel;
return this;
}
public VPanelFormFieldBuilder setReadOnly(boolean readOnly)
{
this.readOnly = readOnly;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java | 1 |
请完成以下Java代码 | public static void registerRSAggregationKeyDependencies()
{
final IAggregationKeyRegistry keyRegistry = Services.get(IAggregationKeyRegistry.class);
final String registrationKey = ReceiptScheduleHeaderAggregationKeyBuilder.REGISTRATION_KEY;
//
// Register Handlers
keyRegistry.registerAggregationKeyValueHandler(registrationKey, new ReceiptScheduleKeyValueHandler());
//
// Register ReceiptScheduleHeaderAggregationKeyBuilder
keyRegistry.registerDependsOnColumnnames(registrationKey,
I_M_ReceiptSchedule.COLUMNNAME_C_DocType_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Location_ID, | I_M_ReceiptSchedule.COLUMNNAME_C_BP_Location_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_ID,
I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_AD_User_ID,
I_M_ReceiptSchedule.COLUMNNAME_AD_User_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_AD_Org_ID,
I_M_ReceiptSchedule.COLUMNNAME_DateOrdered,
I_M_ReceiptSchedule.COLUMNNAME_C_Order_ID,
I_M_ReceiptSchedule.COLUMNNAME_POReference);
}
public void registerFactories()
{
Services.get(IAttributeSetInstanceAwareFactoryService.class)
.registerFactoryForTableName(I_M_ReceiptSchedule.Table_Name, new ReceiptScheduleASIAwareFactory());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\ReceiptScheduleValidator.java | 1 |
请完成以下Java代码 | public class RowSubscriber<T> implements Subscriber<Row> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final Class<T> clazz;
private Subscription subscription;
public List<T> consumedItems = new ArrayList<>();
public RowSubscriber(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public synchronized void onSubscribe(Subscription subscription) {
log.info("Subscriber is subscribed.");
this.subscription = subscription;
subscription.request(1);
}
@Override
public synchronized void onNext(Row row) {
String jsonString = row.asObject().toJsonString();
log.info("Row JSON: {}", jsonString);
try {
T item = OBJECT_MAPPER.readValue(jsonString, this.clazz);
log.info("Item: {}", item);
consumedItems.add(item);
} catch (JsonProcessingException e) {
log.error("Unable to parse json", e);
} | // Request the next row
subscription.request(1);
}
@Override
public synchronized void onError(Throwable t) {
log.error("Received an error", t);
}
@Override
public synchronized void onComplete() {
log.info("Query has ended.");
}
} | repos\tutorials-master\ksqldb\src\main\java\com\baeldung\ksqldb\RowSubscriber.java | 1 |
请完成以下Java代码 | public void setAD_Message_ID (int AD_Message_ID)
{
if (AD_Message_ID < 1)
set_Value (COLUMNNAME_AD_Message_ID, null);
else
set_Value (COLUMNNAME_AD_Message_ID, Integer.valueOf(AD_Message_ID));
}
/** Get Meldung.
@return System Message
*/
@Override
public int getAD_Message_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Message_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set AD_Table_AttachmentListener.
@param AD_Table_AttachmentListener_ID AD_Table_AttachmentListener */
@Override
public void setAD_Table_AttachmentListener_ID (int AD_Table_AttachmentListener_ID)
{
if (AD_Table_AttachmentListener_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_AttachmentListener_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_AttachmentListener_ID, Integer.valueOf(AD_Table_AttachmentListener_ID));
}
/** Get AD_Table_AttachmentListener.
@return AD_Table_AttachmentListener */
@Override
public int getAD_Table_AttachmentListener_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_AttachmentListener_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
@Override
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Send Notification.
@param IsSendNotification Send Notification */
@Override | public void setIsSendNotification (boolean IsSendNotification)
{
set_Value (COLUMNNAME_IsSendNotification, Boolean.valueOf(IsSendNotification));
}
/** Get Send Notification.
@return Send Notification */
@Override
public boolean isSendNotification ()
{
Object oo = get_Value(COLUMNNAME_IsSendNotification);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
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_AD_Table_AttachmentListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class GsonAutoConfiguration {
@Bean
@ConditionalOnMissingBean
GsonBuilder gsonBuilder(List<GsonBuilderCustomizer> customizers) {
GsonBuilder builder = new GsonBuilder();
customizers.forEach((c) -> c.customize(builder));
return builder;
}
@Bean
@ConditionalOnMissingBean
Gson gson(GsonBuilder gsonBuilder) {
return gsonBuilder.create();
}
@Bean
StandardGsonBuilderCustomizer standardGsonBuilderCustomizer(GsonProperties gsonProperties) {
return new StandardGsonBuilderCustomizer(gsonProperties);
}
static final class StandardGsonBuilderCustomizer implements GsonBuilderCustomizer, Ordered {
private final GsonProperties properties;
StandardGsonBuilderCustomizer(GsonProperties properties) {
this.properties = properties;
}
@Override
public int getOrder() {
return 0;
}
@Override
public void customize(GsonBuilder builder) {
GsonProperties properties = this.properties;
PropertyMapper map = PropertyMapper.get();
map.from(properties::getGenerateNonExecutableJson).whenTrue().toCall(builder::generateNonExecutableJson);
map.from(properties::getExcludeFieldsWithoutExposeAnnotation) | .whenTrue()
.toCall(builder::excludeFieldsWithoutExposeAnnotation);
map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls);
map.from(properties::getEnableComplexMapKeySerialization)
.whenTrue()
.toCall(builder::enableComplexMapKeySerialization);
map.from(properties::getDisableInnerClassSerialization)
.whenTrue()
.toCall(builder::disableInnerClassSerialization);
map.from(properties::getLongSerializationPolicy).to(builder::setLongSerializationPolicy);
map.from(properties::getFieldNamingPolicy).to(builder::setFieldNamingPolicy);
map.from(properties::getPrettyPrinting).whenTrue().toCall(builder::setPrettyPrinting);
map.from(properties::getStrictness).to(strictnessOrLeniency(builder));
map.from(properties::getDisableHtmlEscaping).whenTrue().toCall(builder::disableHtmlEscaping);
map.from(properties::getDateFormat).to(builder::setDateFormat);
}
@SuppressWarnings("deprecation")
private Consumer<GsonProperties.Strictness> strictnessOrLeniency(GsonBuilder builder) {
if (ClassUtils.isPresent("com.google.gson.Strictness", getClass().getClassLoader())) {
return (strictness) -> builder.setStrictness(Strictness.valueOf(strictness.name()));
}
return (strictness) -> {
if (strictness == GsonProperties.Strictness.LENIENT) {
builder.setLenient();
}
};
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonAutoConfiguration.java | 2 |
请完成以下Java代码 | private String getSourceTableName()
{
return InterfaceWrapperHelper.getModelTableName(getSourceModel());
}
public CountryAwareAttributeUpdater setCountryAwareFactory(final ICountryAwareFactory countryAwareFactory)
{
this.countryAwareFactory = countryAwareFactory;
return this;
}
private ICountryAwareFactory getCountryAwareFactory()
{
Check.assumeNotNull(countryAwareFactory, "countryAwareFactory not null");
return countryAwareFactory; | }
public final CountryAwareAttributeUpdater setCountryAwareAttributeService(final ICountryAwareAttributeService countryAwareAttributeService)
{
this.countryAwareAttributeService = countryAwareAttributeService;
return this;
}
private ICountryAwareAttributeService getCountryAwareAttributeService()
{
Check.assumeNotNull(countryAwareAttributeService, "countryAwareAttributeService not null");
return countryAwareAttributeService;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\CountryAwareAttributeUpdater.java | 1 |
请完成以下Java代码 | public final class AuthorizationManagerFactories {
private AuthorizationManagerFactories() {
}
/**
* Creates a {@link AdditionalRequiredFactorsBuilder} that helps build an
* {@link AuthorizationManager} to set on
* {@link DefaultAuthorizationManagerFactory#setAdditionalAuthorization(AuthorizationManager)}
* for multifactor authentication.
* <p>
* Does not affect {@code anonymous}, {@code permitAll}, or {@code denyAll}.
* @param <T> the secured object type
* @return a factory configured with the required authorities
*/
public static <T> AdditionalRequiredFactorsBuilder<T> multiFactor() {
return new AdditionalRequiredFactorsBuilder<>();
}
/**
* A builder that allows creating {@link DefaultAuthorizationManagerFactory} with
* additional requirements for {@link RequiredFactor}s.
*
* @param <T> the type for the {@link DefaultAuthorizationManagerFactory}
* @author Rob Winch
*/
public static final class AdditionalRequiredFactorsBuilder<T> {
private final AllRequiredFactorsAuthorizationManager.Builder<T> factors = AllRequiredFactorsAuthorizationManager
.builder();
/**
* Add additional authorities that will be required.
* @param additionalAuthorities the additional authorities.
* @return the {@link AdditionalRequiredFactorsBuilder} to further customize.
*/
public AdditionalRequiredFactorsBuilder<T> requireFactors(String... additionalAuthorities) {
requireFactors((factors) -> {
for (String authority : additionalAuthorities) {
factors.requireFactor((factor) -> factor.authority(authority));
}
}); | return this;
}
public AdditionalRequiredFactorsBuilder<T> requireFactors(
Consumer<AllRequiredFactorsAuthorizationManager.Builder<T>> factors) {
factors.accept(this.factors);
return this;
}
public AdditionalRequiredFactorsBuilder<T> requireFactor(Consumer<RequiredFactor.Builder> factor) {
this.factors.requireFactor(factor);
return this;
}
/**
* Builds a {@link DefaultAuthorizationManagerFactory} that has the
* {@link DefaultAuthorizationManagerFactory#setAdditionalAuthorization(AuthorizationManager)}
* set.
* @return the {@link DefaultAuthorizationManagerFactory}.
*/
public DefaultAuthorizationManagerFactory<T> build() {
DefaultAuthorizationManagerFactory<T> result = new DefaultAuthorizationManagerFactory<>();
AllRequiredFactorsAuthorizationManager<T> additionalChecks = this.factors.build();
result.setAdditionalAuthorization(additionalChecks);
return result;
}
private AdditionalRequiredFactorsBuilder() {
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationManagerFactories.java | 1 |
请完成以下Spring Boot application配置 | server.port=${port:8080}
spring.application.name = Bootstrap Spring Cloud
spring.thymeleaf.cache = false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
server.error.path=/error
se | rver.error.whitelabel.enabled=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update | repos\tutorials-master\spring-boot-modules\spring-boot-bootstrap\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AnnotationSecuredController {
final DifferentClass differentClass;
public AnnotationSecuredController(DifferentClass differentClass) {
this.differentClass = differentClass;
}
@GetMapping("/public")
public String publicHello() {
return "Hello Public";
}
@RolesAllowed("ADMIN")
@GetMapping("/admin")
public String adminHello() {
return "Hello Admin";
}
@RolesAllowed("USER")
@GetMapping("/protected")
public String jsr250Hello() {
return "Hello Jsr250";
} | @GetMapping("/indirect")
public String indirectHello() {
return jsr250Hello();
}
@GetMapping("/differentclass")
public String differentClassHello() {
return differentClass.differentJsr250Hello();
}
@PreAuthorize("hasRole('USER')")
public String preAuthorizeHello() {
return "Hello PreAuthorize";
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-security-2\src\main\java\com\baeldung\annotations\globalmethod\AnnotationSecuredController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Wsdl11Definition orderWebServiceV1()
{
return createWsdl(OrderWebServiceV1.WSDL_BEAN_NAME);
}
// e.g. http://localhost:8080/ws/Msv3BestellstatusAbfragenService.wsdl
@Bean(name = OrderStatusWebServiceV1.WSDL_BEAN_NAME)
public Wsdl11Definition orderStatusWebServiceV1()
{
return createWsdl(OrderStatusWebServiceV1.WSDL_BEAN_NAME);
}
@Bean("Msv3Service_schema1")
public XsdSchema msv3serviceSchemaXsdV1()
{
return createXsdSchema("Msv3Service_schema1.xsd");
}
@Bean("Msv3FachlicheFunktionen")
public XsdSchema msv3FachlicheFunktionenV1() | {
return createXsdSchema("Msv3FachlicheFunktionen.xsd");
}
private static Wsdl11Definition createWsdl(@NonNull final String beanName)
{
return new SimpleWsdl11Definition(createSchemaResource(beanName + ".wsdl"));
}
private static XsdSchema createXsdSchema(@NonNull final String resourceName)
{
return new SimpleXsdSchema(createSchemaResource(resourceName));
}
private static ClassPathResource createSchemaResource(@NonNull final String resourceName)
{
return new ClassPathResource(SCHEMA_RESOURCE_PREFIX + "/" + resourceName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\WebServiceConfigV1.java | 2 |
请完成以下Java代码 | public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Target URL.
@param TargetURL
URL for the Target
*/
public void setTargetURL (String TargetURL)
{
set_Value (COLUMNNAME_TargetURL, TargetURL);
}
/** Get Target URL.
@return URL for the Target
*/
public String getTargetURL ()
{
return (String)get_Value(COLUMNNAME_TargetURL);
}
/** Set User Agent.
@param UserAgent
Browser Used
*/
public void setUserAgent (String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
/** Get User Agent.
@return Browser Used
*/
public String getUserAgent ()
{
return (String)get_Value(COLUMNNAME_UserAgent);
}
public I_W_ClickCount getW_ClickCount() throws RuntimeException
{
return (I_W_ClickCount)MTable.get(getCtx(), I_W_ClickCount.Table_Name)
.getPO(getW_ClickCount_ID(), get_TrxName()); }
/** Set Click Count.
@param W_ClickCount_ID
Web Click Management
*/ | public void setW_ClickCount_ID (int W_ClickCount_ID)
{
if (W_ClickCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID));
}
/** Get Click Count.
@return Web Click Management
*/
public int getW_ClickCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Web Click.
@param W_Click_ID
Individual Web Click
*/
public void setW_Click_ID (int W_Click_ID)
{
if (W_Click_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Click_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Click_ID, Integer.valueOf(W_Click_ID));
}
/** Get Web Click.
@return Individual Web Click
*/
public int getW_Click_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Click_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_Click.java | 1 |
请完成以下Java代码 | public class POSCardReaderExternalId
{
@NonNull private final String value;
private POSCardReaderExternalId(@NonNull final String value)
{
final String valueNorm = normalizeValue(value);
if (valueNorm == null)
{
throw new AdempiereException("Invalid external ID: `" + value + "`");
}
this.value = valueNorm;
}
@Nullable
private static String normalizeValue(@Nullable final String value)
{
return StringUtils.trimBlankToNull(value);
}
@JsonCreator
public static POSCardReaderExternalId ofString(@NonNull final String value)
{ | return new POSCardReaderExternalId(value);
}
@Nullable
public static POSCardReaderExternalId ofNullableString(@Nullable final String value)
{
final String valueNorm = normalizeValue(value);
return valueNorm != null ? new POSCardReaderExternalId(valueNorm) : null;
}
@Override
@Deprecated
public String toString() {return value;}
@JsonValue
public String getAsString() {return value;}
public static boolean equals(@Nullable final POSCardReaderExternalId id1, @Nullable final POSCardReaderExternalId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\payment_gateway\POSCardReaderExternalId.java | 1 |
请完成以下Java代码 | private void updateWeightNetParameter()
{
final PlainWeightable weightable = getParametersAsWeightable();
Weightables.updateWeightNet(weightable);
weightNet = weightable.getWeightNet();
}
@VisibleForTesting
PlainWeightable getParametersAsWeightable()
{
final IWeightable huAttributes = getHUAttributesAsWeightable().get();
return PlainWeightable.builder()
.uom(huAttributes.getWeightNetUOM())
.weightGross(weightGross)
.weightNet(weightNet)
.weightTare(weightTare)
.weightTareAdjust(weightTareAdjust)
.build();
}
@ProcessParamDevicesProvider(parameterName = PARAM_WeightGross)
public DeviceDescriptorsList getWeightGrossDevices()
{
final IWeightable weightable = getHUAttributesAsWeightable().get();
final AttributeCode weightGrossAttribute = weightable.getWeightGrossAttribute(); | final WarehouseId huWarehouseId = getHUWarehouseId();
return HUEditorRowAttributesHelper.getDeviceDescriptors(weightGrossAttribute, huWarehouseId);
}
@Override
protected String doIt()
{
final HuId huId = getSelectedHUId();
final PlainWeightable targetWeight = getParametersAsWeightable();
WeightHUCommand.builder()
.huQtyService(huQtyService)
//
.huId(huId)
.targetWeight(targetWeight)
.build()
//
.execute();
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\process\WEBUI_HUsToPick_Weight.java | 1 |
请完成以下Java代码 | public int getW_Revaluation_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Revaluation_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getWithholding_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Withholding_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setWithholding_A(org.compiere.model.I_C_ValidCombination Withholding_A)
{
set_ValueFromPO(COLUMNNAME_Withholding_Acct, org.compiere.model.I_C_ValidCombination.class, Withholding_A);
}
/** Set Einbehalt.
@param Withholding_Acct
Account for Withholdings
*/
@Override
public void setWithholding_Acct (int Withholding_Acct)
{
set_Value (COLUMNNAME_Withholding_Acct, Integer.valueOf(Withholding_Acct));
}
/** Get Einbehalt.
@return Account for Withholdings
*/
@Override
public int getWithholding_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Withholding_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getWriteOff_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class); | }
@Override
public void setWriteOff_A(org.compiere.model.I_C_ValidCombination WriteOff_A)
{
set_ValueFromPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, WriteOff_A);
}
/** Set Forderungsverluste.
@param WriteOff_Acct
Konto für Forderungsverluste
*/
@Override
public void setWriteOff_Acct (int WriteOff_Acct)
{
set_Value (COLUMNNAME_WriteOff_Acct, Integer.valueOf(WriteOff_Acct));
}
/** Get Forderungsverluste.
@return Konto für Forderungsverluste
*/
@Override
public int getWriteOff_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WriteOff_Acct);
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_C_AcctSchema_Default.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DruidDBConfig {
private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
@Autowired
private DruidConfig druidOneConfig;
@Autowired
private DruidConfig druidTwoConfig;
@Autowired
private DruidConfig druidConfig;
@Bean(name = "primaryDataSource")
public DataSource dataSource() {
return initDruidDataSource(druidOneConfig);
}
@Bean(name = "secondaryDataSource")
@Primary
public DataSource secondaryDataSource() {
return initDruidDataSource(druidTwoConfig);
}
private DruidDataSource initDruidDataSource(DruidConfig config) {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(config.getUrl());
datasource.setUsername(config.getUsername());
datasource.setPassword(config.getPassword());
datasource.setDriverClassName(config.getDriverClassName()); | datasource.setInitialSize(config.getInitialSize());
datasource.setMinIdle(config.getMinIdle());
datasource.setMaxActive(config.getMaxActive());
// common config
datasource.setMaxWait(druidConfig.getMaxWait());
datasource.setTimeBetweenEvictionRunsMillis(druidConfig.getTimeBetweenEvictionRunsMillis());
datasource.setMinEvictableIdleTimeMillis(druidConfig.getMinEvictableIdleTimeMillis());
datasource.setMaxEvictableIdleTimeMillis(druidConfig.getMaxEvictableIdleTimeMillis());
datasource.setValidationQuery(druidConfig.getValidationQuery());
datasource.setTestWhileIdle(druidConfig.isTestWhileIdle());
datasource.setTestOnBorrow(druidConfig.isTestOnBorrow());
datasource.setTestOnReturn(druidConfig.isTestOnReturn());
datasource.setPoolPreparedStatements(druidConfig.isPoolPreparedStatements());
datasource.setMaxPoolPreparedStatementPerConnectionSize(druidConfig.getMaxPoolPreparedStatementPerConnectionSize());
try {
datasource.setFilters(druidConfig.getFilters());
} catch (SQLException e) {
logger.error("druid configuration initialization filter : {0}", e);
}
datasource.setConnectionProperties(druidConfig.getConnectionProperties());
return datasource;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidDBConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Class<?> getObjectType() {
return AuthorizationManager.class;
}
public void setRequestMatcherMap(Map<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> beans) {
this.beans = beans;
}
public void setObservationRegistry(ObservationRegistry observationRegistry) {
this.observationRegistry = observationRegistry;
}
}
static class DefaultWebSecurityExpressionHandlerBeanFactory
extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory {
private DefaultHttpSecurityExpressionHandler handler = new DefaultHttpSecurityExpressionHandler();
@Override
public DefaultHttpSecurityExpressionHandler getBean() {
if (this.rolePrefix != null) {
this.handler.setDefaultRolePrefix(this.rolePrefix);
}
return this.handler;
} | }
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\AuthorizationFilterParser.java | 2 |
请完成以下Java代码 | private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz = object.getClass();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(Init.class)) {
method.setAccessible(true);
method.invoke(object);
}
}
}
private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = object.getClass();
Map<String, String> jsonElementsMap = new HashMap<>();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
if (field.isAnnotationPresent(JsonElement.class)) {
jsonElementsMap.put(getKey(field), (String) field.get(object)); | }
}
String jsonString = jsonElementsMap.entrySet()
.stream()
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
.collect(Collectors.joining(","));
return "{" + jsonString + "}";
}
private String getKey(Field field) {
String value = field.getAnnotation(JsonElement.class)
.key();
return value.isEmpty() ? field.getName() : value;
}
} | repos\tutorials-master\core-java-modules\core-java-annotations\src\main\java\com\baeldung\customannotations\ObjectToJsonConverter.java | 1 |
请完成以下Java代码 | public class JsonMessagePayloadMappingProvider implements MessagePayloadMappingProvider {
private final Event bpmnEvent;
private final MessageEventDefinition messageEventDefinition;
private final ExpressionManager expressionManager;
private final VariablesCalculator variablesCalculator;
public JsonMessagePayloadMappingProvider(
Event bpmnEvent,
MessageEventDefinition messageEventDefinition,
ExpressionManager expressionManager,
VariablesCalculator variablesCalculator
) {
this.bpmnEvent = bpmnEvent;
this.messageEventDefinition = messageEventDefinition;
this.expressionManager = expressionManager;
this.variablesCalculator = variablesCalculator;
}
public Optional<Map<String, Object>> getMessagePayload(DelegateExecution execution) {
return Optional.of(variablesCalculator.calculateInputVariables(execution)).filter(payload ->
!payload.isEmpty() | );
}
public Event getBpmnEvent() {
return bpmnEvent;
}
public MessageEventDefinition getMessageEventDefinition() {
return messageEventDefinition;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public VariablesCalculator getVariablesCalculator() {
return variablesCalculator;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\JsonMessagePayloadMappingProvider.java | 1 |
请完成以下Java代码 | public class VariableListenerEventDefinition extends EventDefinition {
public static final String CHANGE_TYPE_ALL = "all";
public static final String CHANGE_TYPE_UPDATE = "update";
public static final String CHANGE_TYPE_CREATE = "create";
public static final String CHANGE_TYPE_UPDATE_CREATE = "update-create";
public static final String CHANGE_TYPE_DELETE = "delete";
public static final String CHANGE_TYPE_PROPERTY = "changeType";
protected String variableName;
protected String variableChangeType;
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public String getVariableChangeType() {
return variableChangeType;
} | public void setVariableChangeType(String variableChangeType) {
this.variableChangeType = variableChangeType;
}
@Override
public VariableListenerEventDefinition clone() {
VariableListenerEventDefinition clone = new VariableListenerEventDefinition();
clone.setValues(this);
return clone;
}
public void setValues(VariableListenerEventDefinition otherDefinition) {
super.setValues(otherDefinition);
setVariableName(otherDefinition.getVariableName());
setVariableChangeType(otherDefinition.getVariableChangeType());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\VariableListenerEventDefinition.java | 1 |
请完成以下Java代码 | public int getDlmLevel()
{
final int dlmLevel;
final String iniLevel = Ini.getProperty(INI_P_DLM_DLM_LEVEL);
if (Check.isEmpty(iniLevel))
{
dlmLevel = DLMPermanentSysConfigCustomizer.PERMANENT_SYSCONFIG_INSTANCE.getDlmLevel();
Ini.setProperty(INI_P_DLM_DLM_LEVEL, dlmLevel);
Ini.saveProperties();
}
else
{
dlmLevel = Integer.parseInt(iniLevel);
}
return dlmLevel;
}
/**
* Returns the coalesce level set in the {@link Ini} (metasfresh.properties).<br> | * <b>Side Effect:</b> if none is set there yet, then it gets the value from {@link DLMPermanentSysConfigCustomizer} and adds it to the {@link Ini}.
*/
@Override
public int getDlmCoalesceLevel()
{
final int dlmCoalesceLevel;
final String iniLevel = Ini.getProperty(INI_P_DLM_COALESCE_LEVEL);
if (Check.isEmpty(iniLevel))
{
dlmCoalesceLevel = DLMPermanentSysConfigCustomizer.PERMANENT_SYSCONFIG_INSTANCE.getDlmCoalesceLevel();
Ini.setProperty(INI_P_DLM_COALESCE_LEVEL, dlmCoalesceLevel);
Ini.saveProperties();
}
else
{
dlmCoalesceLevel = Integer.parseInt(iniLevel);
}
return dlmCoalesceLevel;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\DLMPermanentIniCustomizer.java | 1 |
请完成以下Java代码 | public static final class ADProcessName_Loader
{
private static final String PREFIX = "process_";
public static ADProcessName retrieve(final AdProcessId adProcessId)
{
final ADProcessName name = DB.retrieveFirstRowOrNull(
"SELECT " + ADProcessName_Loader.sqlSelect("p")
+ " FROM AD_Process p"
+ " WHERE p.AD_Process_ID=?",
Collections.singletonList(adProcessId),
ADProcessName_Loader::retrieve
);
return name != null
? name
: ADProcessName.missing(adProcessId);
}
@SuppressWarnings("SameParameterValue")
private static String sqlSelect(final String tableAlias)
{
return sqlSelectColumn(tableAlias, "Value", PREFIX)
+ ", " + sqlSelectColumn(tableAlias, "Classname", PREFIX);
}
private static ADProcessName retrieve(final ResultSet rs) throws SQLException
{
return ADProcessName.builder()
.value(rs.getString(PREFIX + "Value"))
.classname(rs.getString(PREFIX + "Classname"))
.build();
}
}
public static final class ADElementName_Loader
{
public static String retrieveColumnName(@NonNull final AdElementId adElementId) | {
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited,
"SELECT ColumnName FROM AD_Element WHERE AD_Element_ID=?",
adElementId);
}
}
public static final class ADMessageName_Loader
{
public static String retrieveValue(@NonNull final AdMessageId adMessageId)
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited,
"SELECT Value FROM AD_Message WHERE AD_Message_ID=?",
adMessageId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\Names.java | 1 |
请完成以下Java代码 | class PayloadSocketAcceptor implements SocketAcceptor {
private final SocketAcceptor delegate;
private final List<PayloadInterceptor> interceptors;
private @Nullable MimeType defaultDataMimeType;
private MimeType defaultMetadataMimeType = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
PayloadSocketAcceptor(SocketAcceptor delegate, List<PayloadInterceptor> interceptors) {
Assert.notNull(delegate, "delegate cannot be null");
if (interceptors == null) {
throw new IllegalArgumentException("interceptors cannot be null");
}
if (interceptors.isEmpty()) {
throw new IllegalArgumentException("interceptors cannot be empty");
}
this.delegate = delegate;
this.interceptors = interceptors;
}
@Override
public Mono<RSocket> accept(ConnectionSetupPayload setup, RSocket sendingSocket) {
MimeType dataMimeType = parseMimeType(setup.dataMimeType(), this.defaultDataMimeType);
Assert.notNull(dataMimeType, "No `dataMimeType` in ConnectionSetupPayload and no default value");
MimeType metadataMimeType = parseMimeType(setup.metadataMimeType(), this.defaultMetadataMimeType);
Assert.notNull(metadataMimeType, "No `metadataMimeType` in ConnectionSetupPayload and no default value");
// FIXME do we want to make the sendingSocket available in the PayloadExchange
return intercept(setup, dataMimeType, metadataMimeType)
.flatMap((ctx) -> this.delegate.accept(setup, sendingSocket)
.map((acceptingSocket) -> new PayloadInterceptorRSocket(acceptingSocket, this.interceptors,
metadataMimeType, dataMimeType, ctx))
.contextWrite(ctx));
} | private Mono<Context> intercept(Payload payload, MimeType dataMimeType, MimeType metadataMimeType) {
return Mono.defer(() -> {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors);
DefaultPayloadExchange exchange = new DefaultPayloadExchange(PayloadExchangeType.SETUP, payload,
metadataMimeType, dataMimeType);
return chain.next(exchange).then(Mono.fromCallable(chain::getContext)).defaultIfEmpty(Context.empty());
});
}
private @Nullable MimeType parseMimeType(String str, @Nullable MimeType defaultMimeType) {
return StringUtils.hasText(str) ? MimeTypeUtils.parseMimeType(str) : defaultMimeType;
}
void setDefaultDataMimeType(@Nullable MimeType defaultDataMimeType) {
this.defaultDataMimeType = defaultDataMimeType;
}
void setDefaultMetadataMimeType(MimeType defaultMetadataMimeType) {
Assert.notNull(defaultMetadataMimeType, "defaultMetadataMimeType cannot be null");
this.defaultMetadataMimeType = defaultMetadataMimeType;
}
} | repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\core\PayloadSocketAcceptor.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
S3Service s3Service = new S3Service(AWS_REGION);
//creating a bucket
s3Service.createBucket(AWS_BUCKET);
//check if a bucket exists
if(s3Service.doesBucketExist(AWS_BUCKET)) {
System.out.println("Bucket name is not available."
+ " Try again with a different Bucket name.");
return;
}
s3Service.putObjects(AWS_BUCKET, FileGenerator.generateFiles(1000, 1));
//list all the buckets
s3Service.listBuckets();
s3Service.listObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucketPaginated(AWS_BUCKET, 500);
s3Service.listAllObjectsInBucketPaginatedWithPrefix(AWS_BUCKET, 500, "backup/");
//deleting bucket
s3Service.deleteBucket("baeldung-bucket-test2");
//uploading object
s3Service.putObject(
AWS_BUCKET,
"Document/hello.txt",
new File("/Users/user/Document/hello.txt")
);
s3Service.updateObject(
AWS_BUCKET,
"Document/hello2.txt",
new File("/Users/user/Document/hello2.txt") | );
//listing objects
s3Service.listObjects(AWS_BUCKET);
//downloading an object
s3Service.getObject(AWS_BUCKET, "Document/hello.txt");
//copying an object
s3Service.copyObject(
"baeldung-bucket",
"picture/pic.png",
"baeldung-bucket2",
"Document/picture.png"
);
//deleting an object
s3Service.deleteObject(AWS_BUCKET, "Document/hello.txt");
//deleting multiple objects
List<String> objKeyList = List.of("Document/hello2.txt", "Document/picture.png");
s3Service.deleteObjects(AWS_BUCKET, objKeyList);
}
} | repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\S3Application.java | 1 |
请完成以下Java代码 | public String generateRandomSpecialCharacters(int length) {
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45)
.build();
return pwdGenerator.generate(length);
}
public String generateRandomNumbers(int length) {
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
.build();
return pwdGenerator.generate(length);
}
public String generateRandomCharacters(int length) {
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
.build();
return pwdGenerator.generate(length);
}
public String generateRandomAlphabet(int length, boolean lowerCase) {
int low;
int hi;
if (lowerCase) {
low = 97;
hi = 122;
} else {
low = 65;
hi = 90;
}
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi)
.build(); | return pwdGenerator.generate(length);
}
public Stream<Character> getRandomAlphabets(int count, boolean upperCase) {
IntStream characters = null;
if (upperCase) {
characters = random.ints(count, 65, 90);
} else {
characters = random.ints(count, 97, 122);
}
return characters.mapToObj(data -> (char) data);
}
public Stream<Character> getRandomNumbers(int count) {
IntStream numbers = random.ints(count, 48, 57);
return numbers.mapToObj(data -> (char) data);
}
public Stream<Character> getRandomSpecialChars(int count) {
IntStream specialChars = random.ints(count, 33, 45);
return specialChars.mapToObj(data -> (char) data);
}
} | repos\tutorials-master\core-java-modules\core-java-string-apis\src\main\java\com\baeldung\password\RandomPasswordGenerator.java | 1 |
请完成以下Java代码 | public class GetProductCategoriesCommand
{
private final ProductsServicesFacade servicesFacade;
private String adLanguage;
@Builder(buildMethodName = "_build")
private GetProductCategoriesCommand(
@NonNull final ProductsServicesFacade servicesFacade,
@NonNull final String adLanguage)
{
this.servicesFacade = servicesFacade;
this.adLanguage = adLanguage;
}
public static class GetProductCategoriesCommandBuilder
{
public JsonGetProductCategoriesResponse execute()
{
return _build().execute();
}
}
public JsonGetProductCategoriesResponse execute()
{
final ImmutableList<JsonProductCategory> productCategories = servicesFacade.streamAllProductCategories() | .map(this::toJsonProductCategory)
.collect(ImmutableList.toImmutableList());
return JsonGetProductCategoriesResponse.builder()
.productCategories(productCategories)
.build();
}
private JsonProductCategory toJsonProductCategory(final I_M_Product_Category record)
{
final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(record);
return JsonProductCategory.builder()
.id(ProductCategoryId.ofRepoId(record.getM_Product_Category_ID()))
.value(record.getValue())
.name(trls.getColumnTrl(I_M_Product_Category.COLUMNNAME_Name, record.getName()).translate(adLanguage))
.description(trls.getColumnTrl(I_M_Product_Category.COLUMNNAME_Description, record.getDescription()).translate(adLanguage))
.parentProductCategoryId(ProductCategoryId.ofRepoIdOrNull(record.getM_Product_Category_Parent_ID()))
.defaultCategory(record.isDefault())
.createdUpdatedInfo(servicesFacade.extractCreatedUpdatedInfo(record))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\product\command\GetProductCategoriesCommand.java | 1 |
请完成以下Java代码 | public int hashCode(Address x) {
return x.hashCode();
}
@Override
public Address deepCopy(Address value) {
if (Objects.isNull(value)) {
return null;
}
Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(value.getAddressLine1());
newEmpAdd.setAddressLine2(value.getAddressLine2());
newEmpAdd.setCity(value.getCity());
newEmpAdd.setCountry(value.getCountry());
newEmpAdd.setZipCode(value.getZipCode());
return newEmpAdd;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Address value) { | return (Serializable) deepCopy(value);
}
@Override
public Address assemble(Serializable cached, Object owner) {
return deepCopy((Address) cached);
}
@Override
public Address replace(Address detached, Address managed, Object owner) {
return detached;
}
@Override
public boolean isInstance(Object object) {
return CompositeUserType.super.isInstance(object);
}
@Override
public boolean isSameClass(Object object) {
return CompositeUserType.super.isSameClass(object);
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\AddressType.java | 1 |
请完成以下Java代码 | /* package */class InvoicingItem implements IInvoicingItem
{
private final I_M_Product product;
private final BigDecimal qty;
private final I_C_UOM uom;
public InvoicingItem(final I_M_Product product, final BigDecimal qty, final I_C_UOM uom)
{
super();
Check.assumeNotNull(product, "product not null");
this.product = product;
Check.assumeNotNull(qty, "qty not null");
this.qty = qty;
Check.assumeNotNull(uom, "uom not null");
this.uom = uom;
}
@Override
public String toString()
{
return "ProductionMaterial ["
+ "product=" + product.getName()
+ ", qty=" + qty
+ ", uom=" + uom.getUOMSymbol()
+ "]";
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(product)
.append(qty)
.append(uom)
.toHashcode();
};
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final InvoicingItem other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
} | return new EqualsBuilder()
.append(product, other.product)
.append(qty, other.qty)
.append(uom, other.uom)
.isEqual();
}
@Override
public I_M_Product getM_Product()
{
return product;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public I_C_UOM getC_UOM()
{
return uom;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\InvoicingItem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExternalSystemGRSSignumHouseKeepingTask implements IStartupHouseKeepingTask
{
private static final Logger logger = LogManager.getLogger(ExternalSystemGRSSignumHouseKeepingTask.class);
private static final String GRS_COMMAND = "enableRestAPI";
private final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
private final ExternalSystemConfigRepo externalSystemConfigDAO;
private final ExternalSystemRepository externalSystemRepository;
@Override
public void executeTask()
{
final AdProcessId processId = adProcessDAO.retrieveProcessIdByClassIfUnique(ExternalSystemProcesses.getExternalSystemProcessClassName(ExternalSystemType.GRSSignum));
if (processId == null)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("Nothing to do!");
return; | }
final ImmutableList<ExternalSystemParentConfig> parentConfigList = externalSystemConfigDAO.getActiveByType(ExternalSystemType.GRSSignum);
parentConfigList
.stream()
.peek(config -> Loggables.withLogger(logger, Level.DEBUG).addLog("Firing process " + processId + " for GRSSignum config " + config.getChildConfig().getId()))
.forEach((config -> ProcessInfo.builder()
.setAD_Process_ID(processId)
.setAD_User_ID(UserId.METASFRESH.getRepoId())
.addParameter(PARAM_EXTERNAL_REQUEST, GRS_COMMAND)
.addParameter(PARAM_CHILD_CONFIG_ID, config.getChildConfig().getId().getRepoId())
.buildAndPrepareExecution()
.executeSync()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\housekeeping\ExternalSystemGRSSignumHouseKeepingTask.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public RelationalManagedTypes jdbcManagedTypes() throws ClassNotFoundException {
return super.jdbcManagedTypes();
}
@Override
@Bean
@ConditionalOnMissingBean
public JdbcMappingContext jdbcMappingContext(Optional<NamingStrategy> namingStrategy,
JdbcCustomConversions customConversions, RelationalManagedTypes jdbcManagedTypes) {
return super.jdbcMappingContext(namingStrategy, customConversions, jdbcManagedTypes);
}
@Override
@Bean
@ConditionalOnMissingBean
public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext, NamedParameterJdbcOperations operations,
@Lazy RelationResolver relationResolver, JdbcCustomConversions conversions, JdbcDialect dialect) {
return super.jdbcConverter(mappingContext, operations, relationResolver, conversions, dialect);
}
@Override
@Bean
@ConditionalOnMissingBean
public JdbcCustomConversions jdbcCustomConversions() {
return super.jdbcCustomConversions();
}
@Override
@Bean | @ConditionalOnMissingBean
public JdbcAggregateTemplate jdbcAggregateTemplate(ApplicationContext applicationContext,
JdbcMappingContext mappingContext, JdbcConverter converter, DataAccessStrategy dataAccessStrategy) {
return super.jdbcAggregateTemplate(applicationContext, mappingContext, converter, dataAccessStrategy);
}
@Override
@Bean
@ConditionalOnMissingBean
public DataAccessStrategy dataAccessStrategyBean(NamedParameterJdbcOperations operations,
JdbcConverter jdbcConverter, JdbcMappingContext context, JdbcDialect dialect) {
return super.dataAccessStrategyBean(operations, jdbcConverter, context, dialect);
}
@Override
@Bean
@ConditionalOnMissingBean
public JdbcDialect jdbcDialect(NamedParameterJdbcOperations operations) {
DataJdbcDatabaseDialect dialect = this.properties.getDialect();
return (dialect != null) ? dialect.getJdbcDialect(operations.getJdbcOperations())
: super.jdbcDialect(operations);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-jdbc\src\main\java\org\springframework\boot\data\jdbc\autoconfigure\DataJdbcRepositoriesAutoConfiguration.java | 2 |
请完成以下Java代码 | public org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine()
{
return get_ValueAsPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class);
}
@Override
public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine)
{
set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine);
}
@Override
public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID)
{
if (PP_Product_BOMLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID);
}
@Override | public int getPP_Product_BOMLine_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID);
}
@Override
public void setQtyEntered (final @Nullable BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_OrderLine_Candidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DateTimeFormatters {
private @Nullable DateTimeFormatter dateFormatter;
private @Nullable String datePattern;
private @Nullable DateTimeFormatter timeFormatter;
private @Nullable DateTimeFormatter dateTimeFormatter;
/**
* Configures the date format using the given {@code pattern}.
* @param pattern the pattern for formatting dates
* @return {@code this} for chained method invocation
*/
public DateTimeFormatters dateFormat(@Nullable String pattern) {
if (isIso(pattern)) {
this.dateFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
this.datePattern = "yyyy-MM-dd";
}
else {
this.dateFormatter = formatter(pattern);
this.datePattern = pattern;
}
return this;
}
/**
* Configures the time format using the given {@code pattern}.
* @param pattern the pattern for formatting times
* @return {@code this} for chained method invocation
*/
public DateTimeFormatters timeFormat(@Nullable String pattern) {
this.timeFormatter = isIso(pattern) ? DateTimeFormatter.ISO_LOCAL_TIME
: (isIsoOffset(pattern) ? DateTimeFormatter.ISO_OFFSET_TIME : formatter(pattern));
return this;
}
/**
* Configures the date-time format using the given {@code pattern}.
* @param pattern the pattern for formatting date-times
* @return {@code this} for chained method invocation
*/
public DateTimeFormatters dateTimeFormat(@Nullable String pattern) { | this.dateTimeFormatter = isIso(pattern) ? DateTimeFormatter.ISO_LOCAL_DATE_TIME
: (isIsoOffset(pattern) ? DateTimeFormatter.ISO_OFFSET_DATE_TIME : formatter(pattern));
return this;
}
@Nullable DateTimeFormatter getDateFormatter() {
return this.dateFormatter;
}
@Nullable String getDatePattern() {
return this.datePattern;
}
@Nullable DateTimeFormatter getTimeFormatter() {
return this.timeFormatter;
}
@Nullable DateTimeFormatter getDateTimeFormatter() {
return this.dateTimeFormatter;
}
boolean isCustomized() {
return this.dateFormatter != null || this.timeFormatter != null || this.dateTimeFormatter != null;
}
private static @Nullable DateTimeFormatter formatter(@Nullable String pattern) {
return StringUtils.hasText(pattern)
? DateTimeFormatter.ofPattern(pattern).withResolverStyle(ResolverStyle.SMART) : null;
}
private static boolean isIso(@Nullable String pattern) {
return "iso".equalsIgnoreCase(pattern);
}
private static boolean isIsoOffset(@Nullable String pattern) {
return "isooffset".equalsIgnoreCase(pattern) || "iso-offset".equalsIgnoreCase(pattern);
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\format\DateTimeFormatters.java | 2 |
请完成以下Java代码 | public void setAccess (final java.lang.String Access)
{
set_Value (COLUMNNAME_Access, Access);
}
@Override
public java.lang.String getAccess()
{
return get_ValueAsString(COLUMNNAME_Access);
}
@Override
public org.compiere.model.I_AD_Role getAD_Role()
{
return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class);
}
@Override
public void setAD_Role(final org.compiere.model.I_AD_Role AD_Role)
{
set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role);
}
@Override
public void setAD_Role_ID (final int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_Value (COLUMNNAME_AD_Role_ID, null);
else
set_Value (COLUMNNAME_AD_Role_ID, AD_Role_ID);
}
@Override
public int getAD_Role_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Role_ID);
} | @Override
public void setAD_Role_TableOrg_Access_ID (final int AD_Role_TableOrg_Access_ID)
{
if (AD_Role_TableOrg_Access_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Role_TableOrg_Access_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_TableOrg_Access_ID, AD_Role_TableOrg_Access_ID);
}
@Override
public int getAD_Role_TableOrg_Access_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Role_TableOrg_Access_ID);
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_TableOrg_Access.java | 1 |
请完成以下Java代码 | public class User {
private String name;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public User() {
}
public User(String name) {
this.name = name;
} | public static boolean isRealUser(User user) {
return true;
}
public String getOrThrow() {
String value = null;
Optional<String> valueOpt = Optional.ofNullable(value);
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
return result;
}
public boolean isLegalName(String name) {
return name.length() > 3 && name.length() < 16;
}
} | repos\tutorials-master\core-java-modules\core-java-8\src\main\java\com\baeldung\java_8_features\User.java | 1 |
请完成以下Java代码 | public class ExecutionTree implements Iterable<ExecutionTreeNode> {
protected ExecutionTreeNode root;
public ExecutionTree() {}
public ExecutionTreeNode getRoot() {
return root;
}
public void setRoot(ExecutionTreeNode root) {
this.root = root;
}
/**
* Looks up the {@link ExecutionEntity} for a given id.
*/
public ExecutionTreeNode getTreeNode(String executionId) {
return getTreeNode(executionId, root);
}
protected ExecutionTreeNode getTreeNode(String executionId, ExecutionTreeNode currentNode) {
if (currentNode.getExecutionEntity().getId().equals(executionId)) {
return currentNode;
}
List<ExecutionTreeNode> children = currentNode.getChildren();
if (currentNode.getChildren() != null && children.size() > 0) {
int index = 0;
while (index < children.size()) {
ExecutionTreeNode result = getTreeNode(executionId, children.get(index));
if (result != null) {
return result;
}
index++;
}
} | return null;
}
@Override
public Iterator<ExecutionTreeNode> iterator() {
return new ExecutionTreeBfsIterator(this.getRoot());
}
public ExecutionTreeBfsIterator bfsIterator() {
return new ExecutionTreeBfsIterator(this.getRoot());
}
/**
* Uses an {@link ExecutionTreeBfsIterator}, but returns the leafs first (so flipped order of BFS)
*/
public ExecutionTreeBfsIterator leafsFirstIterator() {
return new ExecutionTreeBfsIterator(this.getRoot(), true);
}
@Override
public String toString() {
return root != null ? root.toString() : "";
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\debug\ExecutionTree.java | 1 |
请完成以下Java代码 | public Sbom getApplication() {
return this.application;
}
public Map<String, Sbom> getAdditional() {
return this.additional;
}
public void setAdditional(Map<String, Sbom> additional) {
this.additional = additional;
}
public static class Sbom {
/**
* Location to the SBOM. If null, the location will be auto-detected.
*/
private @Nullable String location;
/**
* Media type of the SBOM. If null, the media type will be auto-detected.
*/
private @Nullable MimeType mediaType;
public @Nullable String getLocation() { | return this.location;
}
public void setLocation(@Nullable String location) {
this.location = location;
}
public @Nullable MimeType getMediaType() {
return this.mediaType;
}
public void setMediaType(@Nullable MimeType mediaType) {
this.mediaType = mediaType;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\sbom\SbomProperties.java | 1 |
请完成以下Java代码 | public class UpdateProcessInstancesSuspendStateBatchCmd extends AbstractUpdateProcessInstancesSuspendStateCmd<Batch> {
public UpdateProcessInstancesSuspendStateBatchCmd(CommandExecutor commandExecutor,
UpdateProcessInstancesSuspensionStateBuilderImpl builder,
boolean suspending) {
super(commandExecutor, builder, suspending);
}
@Override
public Batch execute(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = collectProcessInstanceIds(commandContext);
EnsureUtil.ensureNotEmpty(BadUserRequestException.class,
"No process instance ids given", "process Instance Ids", elementConfiguration.getIds());
EnsureUtil.ensureNotContainsNull(BadUserRequestException.class,
"Cannot be null.", "Process Instance ids", elementConfiguration.getIds()); | return new BatchBuilder(commandContext)
.type(Batch.TYPE_PROCESS_INSTANCE_UPDATE_SUSPENSION_STATE)
.config(getConfiguration(elementConfiguration))
.permission(BatchPermissions.CREATE_BATCH_UPDATE_PROCESS_INSTANCES_SUSPEND)
.operationLogHandler(this::writeUserOperationLogAsync)
.build();
}
public BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) {
return new UpdateProcessInstancesSuspendStateBatchConfiguration(elementConfiguration.getIds(),
elementConfiguration.getMappings(), suspending);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateProcessInstancesSuspendStateBatchCmd.java | 1 |
请完成以下Java代码 | public I_C_BPartner_Report_Text getC_BPartner_Report_Text()
{
return get_ValueAsPO(COLUMNNAME_C_BPartner_Report_Text_ID, I_C_BPartner_Report_Text.class);
}
@Override
public void setC_BPartner_Report_Text(final I_C_BPartner_Report_Text C_BPartner_Report_Text)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_Report_Text_ID, I_C_BPartner_Report_Text.class, C_BPartner_Report_Text);
}
@Override
public void setC_BPartner_Report_Text_ID (final int C_BPartner_Report_Text_ID)
{
if (C_BPartner_Report_Text_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Report_Text_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Report_Text_ID, C_BPartner_Report_Text_ID);
}
@Override
public int getC_BPartner_Report_Text_ID()
{ | return get_ValueAsInt(COLUMNNAME_C_BPartner_Report_Text_ID);
}
@Override
public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\partnerreporttext\model\X_C_BPartner_DocType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DDOrderMoveScheduleId implements RepoIdAware
{
int repoId;
@JsonCreator
public static DDOrderMoveScheduleId ofRepoId(final int repoId)
{
return new DDOrderMoveScheduleId(repoId);
}
@Nullable
public static DDOrderMoveScheduleId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new DDOrderMoveScheduleId(repoId) : null;
}
public static DDOrderMoveScheduleId ofJson(@NonNull final String string)
{
try
{ | return ofRepoId(Integer.parseInt(string));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid id: " + string);
}
}
private DDOrderMoveScheduleId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "DD_Order_MoveSchedule_ID");
}
@JsonValue
public int toJson() {return getRepoId();}
public static boolean equals(@Nullable final DDOrderMoveScheduleId id1, @Nullable final DDOrderMoveScheduleId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleId.java | 2 |
请完成以下Java代码 | public int getJasperProcess_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_JasperProcess_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Betreff.
@param Subject
Mail Betreff
*/
@Override
public void setSubject (java.lang.String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Betreff.
@return Mail Betreff
*/ | @Override
public java.lang.String getSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_Subject);
}
/** Set Text.
@param TextSnippet Text */
@Override
public void setTextSnippet (java.lang.String TextSnippet)
{
set_Value (COLUMNNAME_TextSnippet, TextSnippet);
}
/** Get Text.
@return Text */
@Override
public java.lang.String getTextSnippet ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextSnippet);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void closing(CommandContext commandContext) {
}
@Override
public void afterSessionsFlush(CommandContext commandContext) {
}
@Override
public void closed(CommandContext context) {
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_EXECUTION_SUCCESS, job),
jobServiceConfiguration.getEngineName());
}
}
@Override
public void closeFailure(CommandContext commandContext) {
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityExceptionEvent(FlowableEngineEventType.JOB_EXECUTION_FAILURE,
job, commandContext.getException()), jobServiceConfiguration.getEngineName());
} | CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew();
FailedJobCommandFactory failedJobCommandFactory = jobServiceConfiguration.getFailedJobCommandFactory();
Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), commandContext.getException());
LOGGER.trace("Using FailedJobCommandFactory '{}' and command of type '{}'", failedJobCommandFactory.getClass(), cmd.getClass());
commandExecutor.execute(commandConfig, cmd);
}
@Override
public Integer order() {
return 20;
}
@Override
public boolean multipleAllowed() {
return true;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\FailedJobListener.java | 2 |
请完成以下Java代码 | public static String usingPattern(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Optional<String> result = Pattern.compile(".{1," + length + "}")
.matcher(text)
.results()
.map(MatchResult::group)
.findFirst();
return result.isPresent() ? result.get() : EMPTY;
}
public static String usingCodePointsMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
return text.codePoints()
.limit(length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
} | public static String usingLeftMethod(String text, int length) {
return StringUtils.left(text, length);
}
public static String usingTruncateMethod(String text, int length) {
return StringUtils.truncate(text, length);
}
public static String usingSplitter(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Iterable<String> parts = Splitter.fixedLength(length)
.split(text);
return parts.iterator()
.next();
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-11\src\main\java\com\baeldung\truncate\TruncateString.java | 1 |
请完成以下Java代码 | 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 JwsHeader.Builder JWS headers} allowing the ability to add,
* replace, or remove.
* @return the {@link JwsHeader.Builder}
*/
public JwsHeader.Builder getJwsHeader() {
return get(JwsHeader.Builder.class);
}
/**
* Returns the {@link JwtClaimsSet.Builder claims} allowing the ability to add,
* replace, or remove.
* @return the {@link JwtClaimsSet.Builder}
*/
public JwtClaimsSet.Builder getClaims() {
return get(JwtClaimsSet.Builder.class);
}
/**
* Constructs a new {@link Builder} with the provided JWS headers and claims.
* @param jwsHeaderBuilder the JWS headers to initialize the builder
* @param claimsBuilder the claims to initialize the builder
* @return the {@link Builder} | */
public static Builder with(JwsHeader.Builder jwsHeaderBuilder, JwtClaimsSet.Builder claimsBuilder) {
return new Builder(jwsHeaderBuilder, claimsBuilder);
}
/**
* A builder for {@link JwtEncodingContext}.
*/
public static final class Builder extends AbstractBuilder<JwtEncodingContext, Builder> {
private Builder(JwsHeader.Builder jwsHeaderBuilder, JwtClaimsSet.Builder claimsBuilder) {
Assert.notNull(jwsHeaderBuilder, "jwsHeaderBuilder cannot be null");
Assert.notNull(claimsBuilder, "claimsBuilder cannot be null");
put(JwsHeader.Builder.class, jwsHeaderBuilder);
put(JwtClaimsSet.Builder.class, claimsBuilder);
}
/**
* Builds a new {@link JwtEncodingContext}.
* @return the {@link JwtEncodingContext}
*/
@Override
public JwtEncodingContext build() {
return new JwtEncodingContext(getContext());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\JwtEncodingContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean supports(Class<?> aClass) {
return true;
}
/**
* 初始化 所有资源 对应的角色
*/
public void loadResourceDefine() {
map = new HashMap<>(16);
//权限资源 和 角色对应的表 也就是 角色权限 中间表
List<RolePermisson> rolePermissons = permissionMapper.getRolePermissions();
//某个资源 可以被哪些角色访问
for (RolePermisson rolePermisson : rolePermissons) { | String url = rolePermisson.getUrl();
String roleName = rolePermisson.getRoleName();
ConfigAttribute role = new SecurityConfig(roleName);
if(map.containsKey(url)){
map.get(url).add(role);
}else{
List<ConfigAttribute> list = new ArrayList<>();
list.add( role );
map.put( url , list );
}
}
}
} | repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\MyInvocationSecurityMetadataSourceService.java | 2 |
请完成以下Java代码 | public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* OrderPickingType AD_Reference_ID=542022
* Reference name: OrderPickingType List
*/
public static final int ORDERPICKINGTYPE_AD_Reference_ID=542022;
/** Single = SG */
public static final String ORDERPICKINGTYPE_Single = "SG";
/** Multiple = MP */
public static final String ORDERPICKINGTYPE_Multiple = "MP";
@Override
public void setOrderPickingType (final @Nullable java.lang.String OrderPickingType)
{
set_Value (COLUMNNAME_OrderPickingType, OrderPickingType);
}
@Override
public java.lang.String getOrderPickingType()
{
return get_ValueAsString(COLUMNNAME_OrderPickingType);
}
@Override
public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID)
{ | if (PickFrom_Locator_ID < 1)
set_Value (COLUMNNAME_PickFrom_Locator_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID);
}
@Override
public int getPickFrom_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID);
}
/**
* PriorityRule AD_Reference_ID=154
* Reference name: _PriorityRule
*/
public static final int PRIORITYRULE_AD_Reference_ID=154;
/** High = 3 */
public static final String PRIORITYRULE_High = "3";
/** Medium = 5 */
public static final String PRIORITYRULE_Medium = "5";
/** Low = 7 */
public static final String PRIORITYRULE_Low = "7";
/** Urgent = 1 */
public static final String PRIORITYRULE_Urgent = "1";
/** Minor = 9 */
public static final String PRIORITYRULE_Minor = "9";
@Override
public void setPriorityRule (final @Nullable java.lang.String PriorityRule)
{
set_Value (COLUMNNAME_PriorityRule, PriorityRule);
}
@Override
public java.lang.String getPriorityRule()
{
return get_ValueAsString(COLUMNNAME_PriorityRule);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace.java | 1 |
请完成以下Java代码 | private PaymentToReconcileRow toPaymentToReconcileRow(
@NonNull final I_C_Payment record,
@NonNull final ImmutableSetMultimap<PaymentId, String> invoiceDocumentNosByPaymentId)
{
final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID());
final CurrencyCode currencyCode = currencyRepository.getCurrencyCodeById(currencyId);
final Amount payAmt = Amount.of(record.getPayAmt(), currencyCode);
final PaymentId paymentId = PaymentId.ofRepoId(record.getC_Payment_ID());
String invoiceDocumentNos = joinInvoiceDocumentNos(invoiceDocumentNosByPaymentId.get(paymentId));
return PaymentToReconcileRow.builder()
.paymentId(paymentId)
.inboundPayment(record.isReceipt())
.documentNo(record.getDocumentNo())
.dateTrx(TimeUtil.asLocalDate(record.getDateTrx()))
.bpartner(bpartnerLookup.findById(record.getC_BPartner_ID()))
.invoiceDocumentNos(invoiceDocumentNos)
.payAmt(payAmt) | .reconciled(record.isReconciled())
.build();
}
private static String joinInvoiceDocumentNos(final Collection<String> documentNos)
{
if (documentNos == null || documentNos.isEmpty())
{
return "";
}
return documentNos.stream()
.map(StringUtils::trimBlankToNull)
.filter(Objects::nonNull)
.collect(Collectors.joining(", "));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementLineAndPaymentsToReconcileRepository.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.