instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public void savePermissionDataRule(SysPermissionDataRule sysPermissionDataRule) {
this.save(sysPermissionDataRule);
SysPermission permission = sysPermissionMapper.selectById(sysPermissionDataRule.getPermissionId());
boolean flag = permission != null && (permission.getRuleFlag() == null || permission.getRuleFlag().equals(CommonConstant.RULE_FLAG_0));
if(flag) {
permission.setRuleFlag(CommonConstant.RULE_FLAG_1);
sysPermissionMapper.updateById(permission);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deletePermissionDataRule(String dataRuleId) {
SysPermissionDataRule dataRule = this.baseMapper.selectById(dataRuleId);
if(dataRule!=null) { | this.removeById(dataRuleId);
Long count = this.baseMapper.selectCount(new LambdaQueryWrapper<SysPermissionDataRule>().eq(SysPermissionDataRule::getPermissionId, dataRule.getPermissionId()));
//注:同一个事务中删除后再查询是会认为数据已被删除的 若事务回滚上述删除无效
if(count==null || count==0) {
SysPermission permission = sysPermissionMapper.selectById(dataRule.getPermissionId());
if(permission!=null && permission.getRuleFlag().equals(CommonConstant.RULE_FLAG_1)) {
permission.setRuleFlag(CommonConstant.RULE_FLAG_0);
sysPermissionMapper.updateById(permission);
}
}
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysPermissionDataRuleImpl.java | 2 |
请完成以下Java代码 | protected CTableModelRowSorter createModelRowSorter()
{
return new CTableModelRowSorter(this)
{
@Override
protected void sort (final int modelColumnIndex)
{
final int rows = getRowCount();
if (rows <= 0)
return;
//
final TableModel model = getModel();
if (!(model instanceof GridTable))
{
super.sort(modelColumnIndex);
return;
}
final GridTable gridTable = (GridTable)model;
sorting = true;
try
{
// other sort columns
final boolean sortAscending = addToSortColumnsAndRemoveOtherColumns(modelColumnIndex);
gridTable.sort(modelColumnIndex, sortAscending);
}
finally
{
sorting = false;
}
// table model fires "Sorted" DataStatus event which causes MTab to position to row 0
} // sort
};
}
/**
* Transfer focus explicitly to editor due to editors with multiple components
*
* @param row row
* @param column column
* @param e event
* @return true if cell is editing | */
@Override
public boolean editCellAt (int row, int column, java.util.EventObject e)
{
if (!super.editCellAt(row, column, e))
return false;
// log.debug( "VTable.editCellAt", "r=" + row + ", c=" + column);
Object ed = getCellEditor();
if (ed instanceof VEditor)
((Component)ed).requestFocus();
else if (ed instanceof VCellEditor)
{
ed = ((VCellEditor)ed).getEditor();
((Component)ed).requestFocus();
}
return true;
} // editCellAt
/**
* toString
* @return String representation
*/
@Override
public String toString()
{
return new StringBuilder("VTable[")
.append(getModel()).append("]").toString();
} // toString
} // VTable | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\VTable.java | 1 |
请完成以下Java代码 | public String getPipelineDelegateExpression() {
return pipelineDelegateExpression;
}
public void setPipelineDelegateExpression(String pipelineDelegateExpression) {
this.pipelineDelegateExpression = pipelineDelegateExpression;
}
public ChannelEventKeyDetection getChannelEventKeyDetection() {
return channelEventKeyDetection;
}
public void setChannelEventKeyDetection(ChannelEventKeyDetection channelEventKeyDetection) {
this.channelEventKeyDetection = channelEventKeyDetection;
}
public ChannelEventTenantIdDetection getChannelEventTenantIdDetection() {
return channelEventTenantIdDetection;
}
public void setChannelEventTenantIdDetection(ChannelEventTenantIdDetection channelEventTenantIdDetection) {
this.channelEventTenantIdDetection = channelEventTenantIdDetection;
} | public Object getInboundEventProcessingPipeline() {
return inboundEventProcessingPipeline;
}
public void setInboundEventProcessingPipeline(Object inboundEventProcessingPipeline) {
this.inboundEventProcessingPipeline = inboundEventProcessingPipeline;
}
public Object getInboundEventChannelAdapter() {
return inboundEventChannelAdapter;
}
public void setInboundEventChannelAdapter(Object inboundEventChannelAdapter) {
this.inboundEventChannelAdapter = inboundEventChannelAdapter;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\InboundChannelModel.java | 1 |
请完成以下Java代码 | public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcCreate (final @Nullable java.lang.String ProcCreate)
{
set_Value (COLUMNNAME_ProcCreate, ProcCreate);
}
@Override
public java.lang.String getProcCreate()
{
return get_ValueAsString(COLUMNNAME_ProcCreate);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
} | @Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList_Version.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setAcceptingPartyGLN(String value) {
this.acceptingPartyGLN = value;
}
/**
* Gets the value of the contractNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContractNumber() {
return contractNumber;
}
/**
* Sets the value of the contractNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContractNumber(String value) {
this.contractNumber = value;
}
/**
* Gets the value of the thm property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTHM() {
return thm;
}
/**
* Sets the value of the thm property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTHM(Boolean value) {
this.thm = value;
}
/**
* Gets the value of the nonReturnableContainer property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isNonReturnableContainer() {
return nonReturnableContainer;
} | /**
* Sets the value of the nonReturnableContainer property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNonReturnableContainer(Boolean value) {
this.nonReturnableContainer = value;
}
/**
* Gets the value of the specialConditionCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpecialConditionCode() {
return specialConditionCode;
}
/**
* Sets the value of the specialConditionCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpecialConditionCode(String value) {
this.specialConditionCode = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICListLineItemExtensionType.java | 2 |
请完成以下Java代码 | protected final CustomPostgRESTParameters beforePostgRESTCall()
{
final I_EDI_Document_Extension record = loadRecordOutOfTrx();
record.setEDI_ExportStatus(I_EDI_Document.EDI_EXPORTSTATUS_SendingStarted);
saveRecord(record);
final boolean calledViaAPI = isCalledViaAPI();
return CustomPostgRESTParameters.builder()
.storeJsonFile(!calledViaAPI)
.expectSingleResult(true) // because we export exactly one record, we don't want the JSON to be an array
.build();
}
@Override
protected final String afterPostgRESTCall()
{
final ReportResultData reportData = Check.assumeNotNull(getResult().getReportData(), "reportData shall not be null after successful invocation");
final I_EDI_Document_Extension record = loadRecordOutOfTrx();
// note that if it was called via API, then the result will also be in API_Response_Audit, but there it will be removed after some time
final TableRecordReference recordReference = TableRecordReference.of(record);
addLog("Attaching result with filename {} to the {}-record with ID {}",
reportData.getReportFilename(),
recordReference.getTableName(),
recordReference.getRecord_ID()
);
attachmentEntryService.createNewAttachment(
record,
reportData.getReportFilename(),
reportData.getReportDataByteArray());
// note that a possible C_Doc_Outbound_Log's status is updated via modelinterceptor | record.setEDI_ExportStatus(I_EDI_Document.EDI_EXPORTSTATUS_Sent);
saveRecord(record);
return MSG_OK;
}
@Override
protected Exception handleException(@NonNull final Exception e)
{
final I_EDI_Document_Extension record = loadRecordOutOfTrx();
record.setEDI_ExportStatus(I_EDI_Document.EDI_EXPORTSTATUS_Error);
record.setEDIErrorMsg(e.getLocalizedMessage());
saveRecord(record);
return AdempiereException.wrapIfNeeded(e);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\json\EDI_Export_JSON.java | 1 |
请完成以下Java代码 | public String getCmmnElementRef() {
return cmmnElementRef;
}
public void setCmmnElementRef(String cmmnElementRef) {
this.cmmnElementRef = cmmnElementRef;
}
public String getTargetCmmnElementRef() {
return targetCmmnElementRef;
}
public void setTargetCmmnElementRef(String targetCmmnElementRef) {
this.targetCmmnElementRef = targetCmmnElementRef;
}
public GraphicInfo getSourceDockerInfo() {
return sourceDockerInfo;
}
public void setSourceDockerInfo(GraphicInfo sourceDockerInfo) {
this.sourceDockerInfo = sourceDockerInfo;
}
public GraphicInfo getTargetDockerInfo() {
return targetDockerInfo;
}
public void setTargetDockerInfo(GraphicInfo targetDockerInfo) {
this.targetDockerInfo = targetDockerInfo;
}
public void addWaypoint(GraphicInfo graphicInfo) { | this.waypoints.add(graphicInfo);
}
public List<GraphicInfo> getWaypoints() {
return waypoints;
}
public void setWaypoints(List<GraphicInfo> waypoints) {
this.waypoints = waypoints;
}
public GraphicInfo getLabelGraphicInfo() {
return labelGraphicInfo;
}
public void setLabelGraphicInfo(GraphicInfo labelGraphicInfo) {
this.labelGraphicInfo = labelGraphicInfo;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CmmnDiEdge.java | 1 |
请完成以下Java代码 | public ConfigurationPropertyName map(String propertySourceName) {
// Use a local copy in case another thread changes things
LastMapping<String, ConfigurationPropertyName> last = this.lastMappedPropertyName;
if (last != null && last.isFrom(propertySourceName)) {
return last.getMapping();
}
ConfigurationPropertyName mapping = tryMap(propertySourceName);
this.lastMappedPropertyName = new LastMapping<>(propertySourceName, mapping);
return mapping;
}
private ConfigurationPropertyName tryMap(String propertySourceName) {
try {
ConfigurationPropertyName convertedName = ConfigurationPropertyName.adapt(propertySourceName, '.');
if (!convertedName.isEmpty()) {
return convertedName;
}
}
catch (Exception ex) {
// Ignore
}
return ConfigurationPropertyName.EMPTY;
}
private static class LastMapping<T, M> {
private final T from;
private final M mapping;
LastMapping(T from, M mapping) { | this.from = from;
this.mapping = mapping;
}
boolean isFrom(T from) {
return ObjectUtils.nullSafeEquals(from, this.from);
}
M getMapping() {
return this.mapping;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\DefaultPropertyMapper.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public String[] getIds() {
return ids;
}
public String getFirstName() {
return firstName;
}
public String getFirstNameLike() {
return firstNameLike;
}
public String getLastName() {
return lastName;
}
public String getLastNameLike() { | return lastNameLike;
}
public String getEmail() {
return email;
}
public String getEmailLike() {
return emailLike;
}
public String getGroupId() {
return groupId;
}
public String getTenantId() {
return tenantId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserQueryImpl.java | 1 |
请完成以下Java代码 | public void registerCallout()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_M_ProductPrice.COLUMNNAME_C_UOM_ID, I_M_ProductPrice.COLUMNNAME_M_Product_ID })
@CalloutMethod(columnNames = { I_M_ProductPrice.COLUMNNAME_C_UOM_ID, I_M_ProductPrice.COLUMNNAME_M_Product_ID })
public void validateUOM(final I_M_ProductPrice productPrice)
{
if (productPrice.getM_Product_ID() <= 0)
{
return; // nothing to do yet
}
final UomId uomId = UomId.ofRepoId(productPrice.getC_UOM_ID());
if (uomDAO.isUOMForTUs(uomId))
{
validateTuUom(productPrice);
productPrice.setIsHUPrice(true);
}
else
{
productPrice.setIsHUPrice(false);
validatePriceUOM(productPrice);
}
}
private void validateTuUom(@NonNull final I_M_ProductPrice productPrice)
{
final HUPIItemProductId packingMaterialPriceId = HUPIItemProductId.ofRepoIdOrNull(productPrice.getM_HU_PI_Item_Product_ID());
if (packingMaterialPriceId == null)
{
final I_C_UOM priceUom = uomDAO.getById(productPrice.getC_UOM_ID());
throw new AdempiereException(MSG_ERR_M_PRODUCT_PRICE_MISSING_PACKING_ITEM, priceUom.getName())
.markAsUserValidationError();
}
final I_M_HU_PI_Item_Product packingMaterial = huPIItemProductBL.getRecordById(packingMaterialPriceId);
if (huCapacityBL.isInfiniteCapacity(packingMaterial)) | {
final Object errorParameter = CoalesceUtil.coalesceNotNull(packingMaterial.getName(), packingMaterial.getM_HU_PI_Item_Product_ID());
throw new AdempiereException(MSG_ERR_M_PRODUCT_PRICE_PACKING_ITEM_INFINITE_CAPACITY, errorParameter)
.markAsUserValidationError();
}
}
private void validatePriceUOM(@NonNull final I_M_ProductPrice productPrice)
{
final UomId productPriceUOMId = UomId.ofRepoId(productPrice.getC_UOM_ID());
final UOMConversionsMap uomConversionsMap = uomConversionDAO.getProductConversions(ProductId.ofRepoId(productPrice.getM_Product_ID()));
final UomId productUomId = productBL.getStockUOMId(productPrice.getM_Product_ID());
uomConversionsMap.getRateIfExists(productUomId, productPriceUOMId)
.orElseThrow(() -> new AdempiereException(MSG_ERR_M_PRODUCT_PRICE_NO_UOM_CONVERSION)
.markAsUserValidationError());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_ProductPrice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DynamicSecurityFilter extends AbstractSecurityInterceptor implements Filter {
@Autowired
private DynamicSecurityMetadataSource dynamicSecurityMetadataSource;
@Autowired
private IgnoreUrlsConfig ignoreUrlsConfig;
@Autowired
public void setMyAccessDecisionManager(DynamicAccessDecisionManager dynamicAccessDecisionManager) {
super.setAccessDecisionManager(dynamicAccessDecisionManager);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
//OPTIONS请求直接放行
if(request.getMethod().equals(HttpMethod.OPTIONS.toString())){
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
return;
}
//白名单请求直接放行
PathMatcher pathMatcher = new AntPathMatcher();
for (String path : ignoreUrlsConfig.getUrls()) {
if(pathMatcher.match(path,request.getRequestURI())){
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
return;
}
}
//此处会调用AccessDecisionManager中的decide方法进行鉴权操作
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null); | }
}
@Override
public void destroy() {
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return dynamicSecurityMetadataSource;
}
} | repos\mall-master\mall-security\src\main\java\com\macro\mall\security\component\DynamicSecurityFilter.java | 2 |
请完成以下Java代码 | public ByteArrayRef getByteArrayRef() {
return byteArrayRef;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricVariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", revision=").append(revision);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue);
} | if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java | 1 |
请完成以下Java代码 | private void createEndOfPause(
final I_C_Flatrate_Term term,
final Timestamp pauseUntil,
final int seqNoOfPauseRecord)
{
final I_C_SubscriptionProgress pauseEnd = newInstance(I_C_SubscriptionProgress.class);
pauseEnd.setEventType(X_C_SubscriptionProgress.EVENTTYPE_EndOfPause);
pauseEnd.setC_Flatrate_Term(term);
pauseEnd.setStatus(X_C_SubscriptionProgress.STATUS_Planned);
pauseEnd.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_Running);
pauseEnd.setEventDate(pauseUntil);
pauseEnd.setSeqNo(seqNoOfPauseRecord);
save(pauseEnd);
} | private ImmutableList<I_C_SubscriptionProgress> collectSpsAfterEndOfPause(final List<I_C_SubscriptionProgress> sps, final Timestamp pauseUntil)
{
final ImmutableList<I_C_SubscriptionProgress> spsAfterPause = sps.stream()
.filter(sp -> sp.getEventDate().after(pauseUntil))
.collect(ImmutableList.toImmutableList());
return spsAfterPause;
}
private void increaseSeqNosByTwo(@NonNull final List<I_C_SubscriptionProgress> sps)
{
final int seqNoOffSet = 2;
for (final I_C_SubscriptionProgress currentSP : sps)
{
currentSP.setSeqNo(currentSP.getSeqNo() + seqNoOffSet);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\InsertPause.java | 1 |
请完成以下Java代码 | private void printLabel(
final DeliveryOrder deliveryOrder,
final PackageLabel packageLabel,
@NonNull final DeliveryOrderService deliveryOrderRepo,
@Nullable final AsyncBatchId asyncBatchId)
{
final IArchiveStorageFactory archiveStorageFactory = Services.get(IArchiveStorageFactory.class);
final String fileExtWithDot = MimeType.getExtensionByType(packageLabel.getContentType());
final String fileName = CoalesceUtil.firstNotEmptyTrimmed(packageLabel.getFileName(), packageLabel.getType().toString()) + fileExtWithDot;
final byte[] labelData = packageLabel.getLabelData();
final Properties ctx = Env.getCtx();
final IArchiveStorage archiveStorage = archiveStorageFactory.getArchiveStorage(ctx);
final I_AD_Archive archive = InterfaceWrapperHelper.create(archiveStorage.newArchive(ctx, ITrx.TRXNAME_ThreadInherited), I_AD_Archive.class);
final ITableRecordReference deliveryOrderRef = deliveryOrderRepo.toTableRecordReference(deliveryOrder); | archive.setAD_Table_ID(deliveryOrderRef.getAD_Table_ID());
archive.setRecord_ID(deliveryOrderRef.getRecord_ID());
archive.setC_BPartner_ID(deliveryOrder.getDeliveryAddress().getBpartnerId());
// archive.setAD_Org_ID(); // TODO: do we need to orgId too?
archive.setName(fileName);
archiveStorage.setBinaryData(archive, labelData);
archive.setIsReport(false);
archive.setIsDirectEnqueue(true);
archive.setIsDirectProcessQueueItem(true);
archive.setC_Async_Batch_ID(AsyncBatchId.toRepoId(asyncBatchId));
InterfaceWrapperHelper.save(archive);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\async\DeliveryOrderWorkpackageProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<?> produceEvents()
{
final WorkflowLaunchersList newResult = computeNewResult();
final WorkflowLaunchersList previousResult = lastResultHolder.setValueAndReturnPrevious(newResult);
if (previousResult != null && previousResult.equalsIgnoringTimestamp(newResult))
{
// nothing changed, don't flood the frontend with same information
return ImmutableList.of();
}
else
{
return toJson(newResult);
}
}
@NonNull
private ImmutableList<JsonWorkflowLaunchersList> toJson(final WorkflowLaunchersList launchers)
{
final JsonOpts jsonOpts = newJsonOpts();
return ImmutableList.of(JsonWorkflowLaunchersList.of(launchers, false, jsonOpts));
}
private JsonOpts newJsonOpts()
{
return JsonOpts.builder()
.adLanguage(userBL.getUserLanguage(userId).getAD_Language()) | .build();
}
private WorkflowLaunchersList computeNewResult()
{
final WorkflowLaunchersQuery query = queryTemplate.withMaxStaleAccepted(getMaxStaleAccepted());
return workflowRestAPIService.getLaunchers(query);
}
private Duration getMaxStaleAccepted()
{
final int durationSec = sysConfigBL.getIntValue(SYSCONFIG_MaxStaleAcceptedInSeconds, (int)DEFAULT_MaxStaleAccepted.getSeconds());
return Duration.ofSeconds(durationSec);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\ws\WorkflowLaunchersWebSocketProducer.java | 2 |
请完成以下Java代码 | public double getV1() {
return getV(0);
}
@JsonIgnore
public double getV2() {
return getV(1);
}
@JsonIgnore
public double getV3() {
return getV(2);
}
@JsonIgnore
public double getV4() {
return getV(3);
}
@JsonIgnore
public double getV5() { | return getV(4);
}
private double getV(int idx) {
if (values.length < idx + 1) {
throw new IllegalArgumentException("Can't get value at index " + idx + ". There are " + values.length + " values present.");
} else {
return values[idx];
}
}
@Override
public long memorySize() {
return OBJ_SIZE + values.length * 8L;
}
} | repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\tbel\TbelCfTsMultiDoubleVal.java | 1 |
请完成以下Java代码 | public int read() throws IOException {
int nextCharacter = wrappedReader.read();
if (nextCharacter != -1) {
if (pos < buffer.length) {
buffer[pos] = (char) nextCharacter;
pos++;
} else if (rewindable && pos >= buffer.length) {
rewindable = false;
}
}
return nextCharacter;
}
public void close() throws IOException {
wrappedReader.close();
}
public synchronized void mark(int readlimit) throws IOException {
wrappedReader.mark(readlimit);
}
public boolean markSupported() {
return wrappedReader.markSupported();
}
public synchronized void reset() throws IOException {
wrappedReader.reset();
}
public long skip(long n) throws IOException {
return wrappedReader.skip(n);
}
/**
* Rewinds the reader such that the initial characters are returned when invoking read().
*
* Throws an exception if more than the buffering limit has already been read.
* @throws IOException
*/
public void rewind() throws IOException {
if (!rewindable) { | throw LOG.unableToRewindReader();
}
wrappedReader.unread(buffer, 0, pos);
pos = 0;
}
public int getRewindBufferSize() {
return buffer.length;
}
/**
*
* @return the number of characters that can still be read and rewound.
*/
public int getCurrentRewindableCapacity() {
return buffer.length - pos;
}
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\util\RewindableReader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderService {
private List<Order> orders = Arrays.asList(
new Order(1, 1, "A101", "2020/02/14"),
new Order(2, 1, "A101", "2020/02/14"),
new Order(3, 2, "A150", "2020/02/17"));
@GetMapping
public List<Order> getAllOrders() {
return orders;
}
@GetMapping("/{id}")
public List<Order> getOrdersByCustomer(@PathVariable int id) {
return orders.stream() | .filter(order -> order.getCustomerId() == id).collect(Collectors.toList());
}
@PostMapping("/create")
public OrderResponse createOrder(@RequestBody OrderDTO request) {
int lastIndex = orders.size();
Order order = new Order();
order.setId(lastIndex + 1);
order.setCustomerId(request.getCustomerId());
order.setItemId(request.getItemId());
String date = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
order.setDate(date);
return new OrderResponse(order.getId(), order.getItemId(), "CREATED");
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\order-service\order-server\src\main\java\com\baeldung\orderservice\OrderService.java | 2 |
请完成以下Java代码 | protected void postProcessJob(RestartProcessInstancesBatchConfiguration configuration, JobEntity job, RestartProcessInstancesBatchConfiguration jobConfiguration) {
if (job.getDeploymentId() == null) {
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntity processDefinitionEntity = commandContext.getProcessEngineConfiguration().getDeploymentCache()
.findDeployedProcessDefinitionById(configuration.getProcessDefinitionId());
job.setDeploymentId(processDefinitionEntity.getDeploymentId());
}
}
@Override
public void executeHandler(RestartProcessInstancesBatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
String processDefinitionId = batchConfiguration.getProcessDefinitionId();
RestartProcessInstanceBuilderImpl builder =
new RestartProcessInstanceBuilderImpl(processDefinitionId);
builder.processInstanceIds(batchConfiguration.getIds());
builder.setInstructions(batchConfiguration.getInstructions());
if (batchConfiguration.isInitialVariables()) {
builder.initialSetOfVariables();
}
if (batchConfiguration.isSkipCustomListeners()) {
builder.skipCustomListeners();
}
if (batchConfiguration.isWithoutBusinessKey()) {
builder.withoutBusinessKey();
}
if (batchConfiguration.isSkipIoMappings()) {
builder.skipIoMappings();
}
CommandExecutor commandExecutor = commandContext.getProcessEngineConfiguration()
.getCommandExecutorTxRequired();
commandContext.executeWithOperationLogPrevented(
new RestartProcessInstancesCmd(commandExecutor, builder)); | }
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
@Override
protected RestartProcessInstancesBatchConfiguration createJobConfiguration(RestartProcessInstancesBatchConfiguration configuration,
List<String> processIdsForJob) {
return new RestartProcessInstancesBatchConfiguration(processIdsForJob, configuration.getInstructions(), configuration.getProcessDefinitionId(),
configuration.isInitialVariables(), configuration.isSkipCustomListeners(), configuration.isSkipIoMappings(), configuration.isWithoutBusinessKey());
}
@Override
protected RestartProcessInstancesBatchConfigurationJsonConverter getJsonConverterInstance() {
return RestartProcessInstancesBatchConfigurationJsonConverter.INSTANCE;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstancesJobHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeleteProcessDefinitionsBuilderImpl implements DeleteProcessDefinitionsBuilder,
DeleteProcessDefinitionsSelectBuilder, DeleteProcessDefinitionsTenantBuilder {
private final CommandExecutor commandExecutor;
private String processDefinitionKey;
private List<String> processDefinitionIds;
private boolean cascade;
private String tenantId;
private boolean isTenantIdSet;
private boolean skipCustomListeners;
protected boolean skipIoMappings;
public DeleteProcessDefinitionsBuilderImpl(CommandExecutor commandExecutor) {
this.commandExecutor = commandExecutor;
}
@Override
public DeleteProcessDefinitionsBuilderImpl byIds(String... processDefinitionId) {
if (processDefinitionId != null) {
this.processDefinitionIds = new ArrayList<String>();
this.processDefinitionIds.addAll(Arrays.asList(processDefinitionId));
}
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl byKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl withoutTenantId() {
isTenantIdSet = true;
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl withTenantId(String tenantId) {
ensureNotNull("tenantId", tenantId);
isTenantIdSet = true;
this.tenantId = tenantId; | return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl cascade() {
this.cascade = true;
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl skipCustomListeners() {
this.skipCustomListeners = true;
return this;
}
@Override
public DeleteProcessDefinitionsBuilderImpl skipIoMappings() {
this.skipIoMappings = true;
return this;
}
@Override
public void delete() {
ensureOnlyOneNotNull(NullValueException.class, "'processDefinitionKey' or 'processDefinitionIds' cannot be null", processDefinitionKey, processDefinitionIds);
Command<Void> command;
if (processDefinitionKey != null) {
command = new DeleteProcessDefinitionsByKeyCmd(processDefinitionKey, cascade, skipCustomListeners, skipIoMappings, tenantId, isTenantIdSet);
} else if (processDefinitionIds != null && !processDefinitionIds.isEmpty()) {
command = new DeleteProcessDefinitionsByIdsCmd(processDefinitionIds, cascade, skipCustomListeners, skipIoMappings);
} else {
return;
}
commandExecutor.execute(command);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeleteProcessDefinitionsBuilderImpl.java | 2 |
请完成以下Java代码 | private void registerProxy(RuntimeHints hints, Class<?> clazz) {
Class<?> proxied = this.proxyFactory.proxy(clazz);
if (proxied == null) {
return;
}
if (Proxy.isProxyClass(proxied)) {
hints.proxies().registerJdkProxy(proxied.getInterfaces());
return;
}
if (SpringProxy.class.isAssignableFrom(proxied)) {
hints.reflection()
.registerType(clazz, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS)
.registerType(proxied, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.ACCESS_DECLARED_FIELDS);
}
} | private void traverseType(List<Class<?>> toProxy, Class<?> clazz) {
if (clazz == Object.class || this.visitedClasses.contains(clazz)) {
return;
}
this.visitedClasses.add(clazz);
for (Method m : clazz.getDeclaredMethods()) {
AuthorizeReturnObject object = this.scanner.scan(m, clazz);
if (object == null) {
continue;
}
Class<?> returnType = m.getReturnType();
toProxy.add(returnType);
traverseType(toProxy, returnType);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\aot\hint\AuthorizeReturnObjectHintsRegistrar.java | 1 |
请完成以下Java代码 | public class DeserializationException extends KafkaException {
@Nullable
private transient Headers headers;
private final byte[] data;
private final boolean isKey;
/**
* Construct an instance with the provided properties.
* @param message the message.
* @param data the data (value or key).
* @param isKey true if the exception occurred while deserializing the key.
* @param cause the cause.
*/
public DeserializationException(String message, byte[] data, boolean isKey, Throwable cause) { // NOSONAR array reference
super(message, cause);
this.data = data; // NOSONAR array reference
this.isKey = isKey;
}
/**
* Get the headers.
* @return the headers.
*/
@Nullable
public Headers getHeaders() {
return this.headers;
}
/**
* Set the headers. | * @param headers the headers.
*/
public void setHeaders(@Nullable Headers headers) {
this.headers = headers;
}
/**
* Get the data that failed deserialization (value or key).
* @return the data.
*/
public byte[] getData() {
return this.data; // NOSONAR array reference
}
/**
* True if deserialization of the key failed, otherwise deserialization of the value
* failed.
* @return true for the key.
*/
public boolean isKey() {
return this.isKey;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DeserializationException.java | 1 |
请完成以下Java代码 | public void setService_Fee_Invoice_ID (final int Service_Fee_Invoice_ID)
{
if (Service_Fee_Invoice_ID < 1)
set_Value (COLUMNNAME_Service_Fee_Invoice_ID, null);
else
set_Value (COLUMNNAME_Service_Fee_Invoice_ID, Service_Fee_Invoice_ID);
}
@Override
public int getService_Fee_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Fee_Invoice_ID);
}
@Override
public void setServiceFeeVatRate (final @Nullable BigDecimal ServiceFeeVatRate)
{
set_Value (COLUMNNAME_ServiceFeeVatRate, ServiceFeeVatRate);
}
@Override
public BigDecimal getServiceFeeVatRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeVatRate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setService_Product_ID (final int Service_Product_ID) | {
if (Service_Product_ID < 1)
set_Value (COLUMNNAME_Service_Product_ID, null);
else
set_Value (COLUMNNAME_Service_Product_ID, Service_Product_ID);
}
@Override
public int getService_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Product_ID);
}
@Override
public void setService_Tax_ID (final int Service_Tax_ID)
{
if (Service_Tax_ID < 1)
set_Value (COLUMNNAME_Service_Tax_ID, null);
else
set_Value (COLUMNNAME_Service_Tax_ID, Service_Tax_ID);
}
@Override
public int getService_Tax_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Tax_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice_Line.java | 1 |
请完成以下Java代码 | private static ObjectNode pruneNode(ObjectNode node, Set<String> keys, String prefix, ObjectMapper mapper) {
ObjectNode pruned = mapper.createObjectNode();
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
String key = entry.getKey();
JsonNode value = entry.getValue();
String fullKey = prefix.isEmpty() ? key : prefix + "." + key;
if (keys.contains(fullKey)) {
if (value.isObject()) {
ObjectNode child = pruneNode((ObjectNode) value, keys, fullKey, mapper);
pruned.set(key, child);
} else {
pruned.set(key, value);
}
}
}
return pruned;
}
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Usage: `java TranslationPruner <source folder> <dest folder>`, where dest folder must contain the locale.constant-en_US.json for reference structure.");
System.exit(1);
}
try { | File sourceFolder = new File(args[0]);
File destFolder = new File(args[1]);
File referenceFile = new File(destFolder, "locale.constant-en_US.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode usRoot = mapper.readTree(referenceFile);
Set<String> validKeys = new HashSet<>();
collectKeys(usRoot, "", validKeys);
for (File sourceFile : sourceFolder.listFiles()) {
File destFile = new File(destFolder, sourceFile.getName());
JsonNode sourceRoot = mapper.readTree(sourceFile);
if (!sourceRoot.isObject()) {
throw new IllegalArgumentException("Source JSON must be an object at root");
}
ObjectNode pruned = pruneNode((ObjectNode) sourceRoot, validKeys, "", mapper);
Separators seps = Separators.createDefaultInstance()
.withObjectFieldValueSpacing(Spacing.AFTER);
mapper.writer(new DefaultPrettyPrinter().withSeparators(seps)).writeValue(destFile, pruned);
System.out.println("Pruned translation written to " + destFile.getPath());
}
} catch (IOException e) {
e.printStackTrace();
System.exit(2);
}
}
} | repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\i18n\TranslationPruner.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws Exception{
File file = ResourceUtils.getFile("classpath:static/shpTest[Point]/dp_tl.shp");
// 从shp文件里面读取属性信息
readShpByPath(file.getAbsolutePath(),10);
System.out.println("=================下面开始往shp文件里面写几何对象===================");
// 先创建文件夹test
String filePath = "C:/test/test.shp";
String pointWkt="POINT (120.76164848270959 31.22001141278534)";
Point point = gCreator.createPointByWKT(pointWkt);
// Polygon【面】
String polygonWkt="POLYGON ((103.859188 34.695908, 103.85661 34.693788, 103.862027 34.69259, 103.863709 34.695078, 103.859188 34.695908))";
Polygon polygon = gCreator.createPolygonByWKT(polygonWkt);
// LineString【线】 | String linestringWkt="LINESTRING(113.511315990174 41.7274734296674,113.51492087909 41.7284983348307,113.516079593384 41.727649586406,113.515907932007 41.7262243043929,113.514019656861 41.7247989907606,113.512131381714 41.7250872589898,113.51138036319 41.7256637915682,113.511315990174 41.7274734296674)";
LineString lineString = gCreator.createLineByWKT(linestringWkt);
// MultiPolygon【多面】
String multiPolyWkt = "MULTIPOLYGON(((101.870371 25.19228,101.873633 25.188183,101.880564 25.184416,101.886808 25.186028,101.892043 25.189969,101.896592 25.190163,101.903716 25.190785,101.905454 25.193464,101.899897 25.196202,101.894146 25.197911,101.891657 25.19826,101.886078 25.197658,101.884211145538 25.2007060137013,101.88172564506 25.1949712942389,101.87874 25.199619,101.874641 25.200998,101.868547 25.202415,101.863741 25.202415,101.85887 25.202842,101.854557 25.202182,101.852604 25.199736,101.852282 25.19628,101.854492 25.194183,101.855608 25.192668,101.863698 25.192105,101.870371 25.19228)))";
MultiPolygon multiPolygon = gCreator.createMulPolygonByWKT(multiPolyWkt);
// 几何对象的范围【矩形边界】
Envelope envelope = polygon.getEnvelopeInternal();
System.out.println(envelope);
// 往shp文件里面写几何对象
writeShpByGeom(filePath,point);
}
} | repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\geotools\ShpTools.java | 1 |
请完成以下Java代码 | public IWorkPackageBuilder end()
{
return _parentBuilder;
}
/* package */void setC_Queue_WorkPackage(final I_C_Queue_WorkPackage workpackage)
{
assertNotBuilt();
_workpackage = workpackage;
}
private I_C_Queue_WorkPackage getC_Queue_WorkPackage()
{
Check.assumeNotNull(_workpackage, "workpackage not null");
return _workpackage;
}
@Override
public IWorkPackageParamsBuilder setParameter(final String parameterName, final Object parameterValue)
{
assertNotBuilt();
Check.assumeNotEmpty(parameterName, "parameterName not empty");
parameterName2valueMap.put(parameterName, parameterValue);
return this;
}
@Override
public IWorkPackageParamsBuilder setParameters(final Map<String, ?> parameters)
{
assertNotBuilt();
if (parameters == null || parameters.isEmpty())
{
return this;
}
for (final Map.Entry<String, ?> param : parameters.entrySet())
{
final String parameterName = param.getKey();
Check.assumeNotEmpty(parameterName, "parameterName not empty");
final Object parameterValue = param.getValue();
parameterName2valueMap.put(parameterName, parameterValue);
}
return this;
}
@Override
public IWorkPackageParamsBuilder setParameters(@Nullable final IParams parameters) | {
assertNotBuilt();
if (parameters == null)
{
return this;
}
final Collection<String> parameterNames = parameters.getParameterNames();
if(parameterNames.isEmpty())
{
return this;
}
for (final String parameterName : parameterNames)
{
Check.assumeNotEmpty(parameterName, "parameterName not empty");
final Object parameterValue = parameters.getParameterAsObject(parameterName);
parameterName2valueMap.put(parameterName, parameterValue);
}
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageParamsBuilder.java | 1 |
请完成以下Java代码 | public Duration getDurationReal(@NonNull final PPOrderRoutingActivity activity, @NonNull final CostCollectorType costCollectorType)
{
return computeDuration(activity, costCollectorType, I_PP_Cost_Collector.COLUMNNAME_DurationReal);
}
private Duration computeDuration(final PPOrderRoutingActivity activity, final CostCollectorType costCollectorType, final String durationColumnName)
{
BigDecimal duration = queryBL.createQueryBuilder(I_PP_Cost_Collector.class)
.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID, activity.getOrderId())
.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_Node_ID, activity.getId())
.addInArrayFilter(I_PP_Cost_Collector.COLUMNNAME_DocStatus, X_PP_Cost_Collector.DOCSTATUS_Completed, X_PP_Cost_Collector.DOCSTATUS_Closed)
.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_CostCollectorType, costCollectorType.getCode())
.create()
.aggregate(durationColumnName, Aggregate.SUM, BigDecimal.class);
if (duration == null) | {
duration = BigDecimal.ZERO;
}
final int durationInt = duration.setScale(0, RoundingMode.UP).intValueExact();
return Duration.of(durationInt, activity.getDurationUnit().getTemporalUnit());
}
@Override
public void save(@NonNull final I_PP_Cost_Collector cc)
{
saveRecord(cc);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\impl\PPCostCollectorDAO.java | 1 |
请完成以下Java代码 | private LULoaderItemInstance addLUItemIfPossible(final I_M_HU_Item luItem)
{
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
//
// Check if it's a handling unit item
if (!Objects.equals(handlingUnitsBL.getItemType(luItem), X_M_HU_Item.ITEMTYPE_HandlingUnit))
{
// Note: we aren't even interested in items with type "HUAggregate" / "HA", because this here is about adding TUs that already exist to an LU.
// In the other hand, "HUAggregate" items are all about *not* having to add an actual TU, but sortof cover it in a "bag", together with others.
return null;
}
final LULoaderItemInstance luItemInstance = new LULoaderItemInstance(huContext, luItem);
if (!luItemInstances.add(luItemInstance))
{
throw new AdempiereException("InternalError: Item " + luItemInstance + " was not added to instances list");
}
return luItemInstance;
}
/**
* Checks if given TU is compatible with our LU (same BParter, BP Location etc).
*
* @param tuHU
* @return true if it's compatible
*/
private boolean acceptTU(final I_M_HU tuHU)
{
//
// Check same BPartner
if (!BPartnerId.equals(IHandlingUnitsBL.extractBPartnerIdOrNull(tuHU), this.bpartnerId))
{
return false;
}
//
// Check same BPartner Location
if (!BPartnerLocationId.equals(IHandlingUnitsBL.extractBPartnerLocationIdOrNull(tuHU), this.bpartnerLocationId))
{
return false;
} | //
// Check same Locator
if (!LocatorId.equalsByRepoId(tuHU.getM_Locator_ID(), LocatorId.toRepoId(locatorId)))
{
return false;
}
//
// Check same HUStatus
final String huStatus = tuHU.getHUStatus();
if (!Objects.equals(huStatus, this.huStatus))
{
return false;
}
//
// Default: accept
return true;
}
void close()
{
final IAttributeStorage luAttributes = huContext.getHUAttributeStorageFactory().getAttributeStorage(luHU);
luAttributes.setSaveOnChange(true);
collectedAttributes.updateAggregatedValuesTo(luAttributes);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\LULoaderInstance.java | 1 |
请完成以下Java代码 | public void requestCarrierAdvises(@NonNull final ShipmentScheduleQuery query)
{
shipmentScheduleService.getBy(query)
.forEach(schedule -> requestCarrierAdvise(schedule, false));
}
private void requestCarrierAdvise(@NonNull final ShipmentSchedule shipmentSchedule, final boolean isIncludeCarrierAdviseManual)
{
trxManager.runInThreadInheritedTrx(() -> {
if (shipmentScheduleService.isNotEligibleForManualCarrierAdvise(shipmentSchedule, isIncludeCarrierAdviseManual))
{
return;
}
shipmentSchedule.setCarrierAdvisingStatus(CarrierAdviseStatus.Requested);
shipmentSchedule.setCarrierProductId(null);
shipmentScheduleService.save(shipmentSchedule);
});
} | public void updateEligibleShipmentSchedules(@NonNull final CarrierAdviseUpdateRequest request)
{
shipmentScheduleService.updateByQuery(request.getQuery(), schedule -> updateEligibleShipmentSchedule(schedule, request));
}
private void updateEligibleShipmentSchedule(@NonNull final ShipmentSchedule schedule, @NonNull final CarrierAdviseUpdateRequest request)
{
if (shipmentScheduleService.isNotEligibleForManualCarrierAdvise(schedule, request.isIncludeCarrierAdviseManual()))
{
return;
}
schedule.setCarrierAdvisingStatus(CarrierAdviseStatus.Manual);
schedule.setCarrierProductId(request.getCarrierProductId());
schedule.setCarrierGoodsTypeId(request.getCarrierGoodsTypeId());
schedule.setCarrierServices(request.getCarrierServiceIds());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\process\CarrierAdviseProcessService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class PropertiesRabbitConnectionDetails implements RabbitConnectionDetails {
private final RabbitProperties properties;
private final @Nullable SslBundles sslBundles;
PropertiesRabbitConnectionDetails(RabbitProperties properties, @Nullable SslBundles sslBundles) {
this.properties = properties;
this.sslBundles = sslBundles;
}
@Override
public String getUsername() {
return this.properties.determineUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.determinePassword();
}
@Override
public @Nullable String getVirtualHost() {
return this.properties.determineVirtualHost();
}
@Override
public List<Address> getAddresses() {
List<Address> addresses = new ArrayList<>();
for (String address : this.properties.determineAddresses()) {
int portSeparatorIndex = address.lastIndexOf(':');
String host = address.substring(0, portSeparatorIndex);
String port = address.substring(portSeparatorIndex + 1);
addresses.add(new Address(host, Integer.parseInt(port)));
}
return addresses; | }
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getSsl();
if (!ssl.determineEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
return this.sslBundles.getBundle(ssl.getBundle());
}
return null;
}
} | repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\PropertiesRabbitConnectionDetails.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public SignatureVerificationResultType getSignatureVerificationResult() {
return signatureVerificationResult;
}
/**
* Sets the value of the signatureVerificationResult property.
*
* @param value
* allowed object is
* {@link SignatureVerificationResultType }
*
*/
public void setSignatureVerificationResult(SignatureVerificationResultType value) {
this.signatureVerificationResult = value;
}
/**
* Gets the value of the signatureVerificationOmittedErrorCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSignatureVerificationOmittedErrorCode() {
return signatureVerificationOmittedErrorCode;
}
/**
* Sets the value of the signatureVerificationOmittedErrorCode property.
*
* @param value
* allowed object is | * {@link String }
*
*/
public void setSignatureVerificationOmittedErrorCode(String value) {
this.signatureVerificationOmittedErrorCode = value;
}
/**
* Gets the value of the signatureVerified property.
*
*/
public boolean isSignatureVerified() {
return signatureVerified;
}
/**
* Sets the value of the signatureVerified property.
*
*/
public void setSignatureVerified(boolean value) {
this.signatureVerified = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SignatureVerificationType.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescritpion() {
return descritpion;
}
public void setDescritpion(String descritpion) {
this.descritpion = descritpion;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url; | }
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
} | repos\springBoot-master\springboot-springSecurity3\src\main\java\com\us\example\domain\Permission.java | 1 |
请完成以下Java代码 | public class DuplicatesCounter {
public static <T> Map<T, Long> countByClassicalLoop(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
for (T element : inputList) {
if (resultMap.containsKey(element)) {
resultMap.put(element, resultMap.get(element) + 1L);
} else {
resultMap.put(element, 1L);
}
}
return resultMap;
}
public static <T> Map<T, Long> countByForEachLoopWithGetOrDefault(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L));
return resultMap;
} | public static <T> Map<T, Long> countByForEachLoopWithMapCompute(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L));
return resultMap;
}
public static <T> Map<T, Long> countByForEachLoopWithMapMerge(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum));
return resultMap;
}
public static <T> Map<T, Long> countByStreamToMap(List<T> inputList) {
return inputList.stream().collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));
}
public static <T> Map<T, Long> countByStreamGroupBy(List<T> inputList) {
return inputList.stream().collect(Collectors.groupingBy(k -> k, Collectors.counting()));
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\list\duplicatescounter\DuplicatesCounter.java | 1 |
请完成以下Java代码 | public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
/** Set Nutzer 1.
@param User1_ID
User defined list element #1
*/
@Override
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get Nutzer 1.
@return User defined list element #1
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
} | /** Set Nutzer 2.
@param User2_ID
User defined list element #2
*/
@Override
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get Nutzer 2.
@return User defined list element #2
*/
@Override
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Movement.java | 1 |
请完成以下Java代码 | public class QueryTypesExamples {
EntityManagerFactory emf;
public QueryTypesExamples() {
Map properties = new HashMap();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
emf = Persistence.createEntityManagerFactory("jpa-query-types", properties);
}
private EntityManager getEntityManager() {
return emf.createEntityManager();
}
public UserEntity getUserByIdWithPlainQuery(Long id) {
Query jpqlQuery = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id");
jpqlQuery.setParameter("id", id);
return (UserEntity) jpqlQuery.getSingleResult();
}
public UserEntity getUserByIdWithTypedQuery(Long id) {
TypedQuery<UserEntity> typedQuery = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id", UserEntity.class);
typedQuery.setParameter("id", id);
return typedQuery.getSingleResult();
}
public UserEntity getUserByIdWithNamedQuery(Long id) {
Query namedQuery = getEntityManager().createNamedQuery("UserEntity.findByUserId"); | namedQuery.setParameter("userId", id);
return (UserEntity) namedQuery.getSingleResult();
}
public UserEntity getUserByIdWithNativeQuery(Long id) {
Query nativeQuery = getEntityManager().createNativeQuery("SELECT * FROM users WHERE id=:userId", UserEntity.class);
nativeQuery.setParameter("userId", id);
return (UserEntity) nativeQuery.getSingleResult();
}
public UserEntity getUserByIdWithCriteriaQuery(Long id) {
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<UserEntity> criteriaQuery = criteriaBuilder.createQuery(UserEntity.class);
Root<UserEntity> userRoot = criteriaQuery.from(UserEntity.class);
UserEntity queryResult = getEntityManager().createQuery(criteriaQuery.select(userRoot)
.where(criteriaBuilder.equal(userRoot.get("id"), id)))
.getSingleResult();
return queryResult;
}
} | repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\querytypes\QueryTypesExamples.java | 1 |
请完成以下Java代码 | public boolean isSameProduct(final I_I_Product importRecord)
{
final I_I_Product currentImportRecord = getCurrentImportRecord();
return currentImportRecord != null
&& Objects.equals(importRecord.getValue(), currentImportRecord.getValue());
}
public boolean isCurrentProductIdSet()
{
return getCurrentProductIdOrNull() != null;
}
public Product getCurrentProduct()
{
final ProductId productId = getCurrentProductIdOrNull();
return getProductsCache().getProductById(productId); | }
public ProductId getCurrentProductIdOrNull()
{
final I_I_Product currentImportRecord = getCurrentImportRecord();
return currentImportRecord != null
? ProductId.ofRepoIdOrNull(currentImportRecord.getM_Product_ID())
: null;
}
public void setCurrentProductId(@NonNull final ProductId productId)
{
final I_I_Product currentImportRecord = getCurrentImportRecord();
Check.assumeNotNull(currentImportRecord, "Parameter currentImportRecord is not null");
currentImportRecord.setM_Product_ID(productId.getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impexp\ProductImportContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ContentNegotiatingViewResolver viewResolver(ContentNegotiationManager cnManager) {
ContentNegotiatingViewResolver cnvResolver = new ContentNegotiatingViewResolver();
cnvResolver.setContentNegotiationManager(cnManager);
List<ViewResolver> resolvers = new ArrayList<>();
InternalResourceViewResolver bean = new InternalResourceViewResolver("/WEB-INF/views/",".jsp");
ArticleRssFeedViewResolver articleRssFeedViewResolver = new ArticleRssFeedViewResolver();
resolvers.add(bean);
resolvers.add(articleRssFeedViewResolver);
cnvResolver.setViewResolvers(resolvers);
return cnvResolver;
}
@Bean
public MultipartResolver multipartResolver() { | StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
return multipartResolver;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new StringHttpMessageConverter());
converters.add(new RssChannelHttpMessageConverter());
converters.add(new JsonChannelHttpMessageConverter());
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToEnumConverter());
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\configuration\ApplicationConfiguration.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Author getAuthor() {
return author;
} | public void setAuthor(Author author) {
this.author = author;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Book)) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaFullJoins\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public PasswordSalt getPasswordSalt() {
return passwordSalt;
}
public IdmEngineConfiguration setPasswordSalt(PasswordSalt passwordSalt) {
this.passwordSalt = passwordSalt;
return this;
}
@Override
public IdmEngineConfiguration setSessionFactories(Map<Class<?>, SessionFactory> sessionFactories) {
this.sessionFactories = sessionFactories;
return this;
}
@Override
public IdmEngineConfiguration setDatabaseSchemaUpdate(String databaseSchemaUpdate) {
this.databaseSchemaUpdate = databaseSchemaUpdate;
return this;
}
@Override
public IdmEngineConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) {
this.enableEventDispatcher = enableEventDispatcher;
return this;
}
@Override
public IdmEngineConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
return this;
}
@Override
public IdmEngineConfiguration setEventListeners(List<FlowableEventListener> eventListeners) { | this.eventListeners = eventListeners;
return this;
}
@Override
public IdmEngineConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) {
this.typedEventListeners = typedEventListeners;
return this;
}
@Override
public IdmEngineConfiguration setClock(Clock clock) {
this.clock = clock;
return this;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\IdmEngineConfiguration.java | 1 |
请完成以下Java代码 | default String getGroupId() {
throw new UnsupportedOperationException("This container does not support retrieving the group id");
}
/**
* The 'id' attribute of a {@code @KafkaListener} or the bean name for spring-managed
* containers.
* @return the id or bean name.
* @since 2.2.5
*/
default String getListenerId() {
throw new UnsupportedOperationException("This container does not support retrieving the listener id");
}
/**
* The 'id' attribute of the main {@code @KafkaListener} container, if this container
* is for a retry topic; null otherwise.
* @return the id.
* @since 3.0
*/
@Nullable
default String getMainListenerId() {
throw new UnsupportedOperationException("This container does not support retrieving the main listener id");
}
/**
* Get arbitrary static information that will be added to the
* {@link KafkaHeaders#LISTENER_INFO} header of all records.
* @return the info.
* @since 2.8.6
*/
@Nullable
default byte[] getListenerInfo() {
throw new UnsupportedOperationException("This container does not support retrieving the listener info");
}
/**
* If this container has child containers, return true if at least one child is running. If there are not
* child containers, returns {@link #isRunning()}.
* @return true if a child is running.
* @since 2.7.3
*/
default boolean isChildRunning() {
return isRunning();
}
/**
* Return true if the container is running, has never been started, or has been
* stopped.
* @return true if the state is as expected.
* @since 2.8
* @see #stopAbnormally(Runnable) | */
default boolean isInExpectedState() {
return true;
}
/**
* Stop the container after some exception so that {@link #isInExpectedState()} will
* return false.
* @param callback the callback.
* @since 2.8
* @see #isInExpectedState()
*/
default void stopAbnormally(Runnable callback) {
stop(callback);
}
/**
* If this container has child containers, return the child container that is assigned
* the topic/partition. Return this when there are no child containers.
* @param topic the topic.
* @param partition the partition.
* @return the container.
*/
default MessageListenerContainer getContainerFor(String topic, int partition) {
return this;
}
/**
* Notify a parent container that a child container has stopped.
* @param child the container.
* @param reason the reason.
* @since 2.9.7
*/
default void childStopped(MessageListenerContainer child, ConsumerStoppedEvent.Reason reason) {
}
/**
* Notify a parent container that a child container has started.
* @param child the container.
* @since 3.3
*/
default void childStarted(MessageListenerContainer child) {
}
@Override
default void destroy() {
stop();
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\MessageListenerContainer.java | 1 |
请完成以下Java代码 | public abstract class AbstractListeningExecutor implements ListeningExecutor {
private ListeningExecutorService service;
@PostConstruct
public void init() {
this.service = MoreExecutors.listeningDecorator(ThingsBoardExecutors.newWorkStealingPool(getThreadPollSize(), getClass()));
}
@PreDestroy
public void destroy() {
if (this.service != null) {
this.service.shutdown();
}
}
@Override
public <T> ListenableFuture<T> executeAsync(Callable<T> task) {
return service.submit(task);
} | public ListenableFuture<?> executeAsync(Runnable task) {
return service.submit(task);
}
@Override
public void execute(Runnable command) {
service.execute(command);
}
public ListeningExecutorService executor() {
return service;
}
protected abstract int getThreadPollSize();
} | repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\AbstractListeningExecutor.java | 1 |
请完成以下Java代码 | public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public void delete(Path path) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public void move(Path source, Path target, CopyOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public boolean isSameFile(Path path, Path path2) throws IOException {
return path.equals(path2);
}
@Override
public boolean isHidden(Path path) throws IOException {
return false;
}
@Override
public FileStore getFileStore(Path path) throws IOException {
NestedPath nestedPath = NestedPath.cast(path);
nestedPath.assertExists();
return new NestedFileStore(nestedPath.getFileSystem());
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
Path jarPath = getJarPath(path);
jarPath.getFileSystem().provider().checkAccess(jarPath, modes);
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { | Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().getFileAttributeView(jarPath, type, options);
}
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, type, options);
}
@Override
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, attributes, options);
}
protected Path getJarPath(Path path) {
return NestedPath.cast(path).getJarPath();
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystemProvider.java | 1 |
请完成以下Java代码 | private static void checkScope(OAuth2Authorization.Token<OAuth2AccessToken> authorizedAccessToken,
Set<String> requiredScope) {
Collection<String> authorizedScope = Collections.emptySet();
if (authorizedAccessToken.getClaims().containsKey(OAuth2ParameterNames.SCOPE)) {
authorizedScope = (Collection<String>) authorizedAccessToken.getClaims().get(OAuth2ParameterNames.SCOPE);
}
if (!authorizedScope.containsAll(requiredScope)) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
}
else if (authorizedScope.size() != requiredScope.size()) {
// Restrict the access token to only contain the required scope
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN);
}
}
private static boolean isValidRedirectUris(List<String> redirectUris) {
if (CollectionUtils.isEmpty(redirectUris)) {
return true;
}
for (String redirectUri : redirectUris) {
try {
URI validRedirectUri = new URI(redirectUri); | if (validRedirectUri.getFragment() != null) {
return false;
}
}
catch (URISyntaxException ex) {
return false;
}
}
return true;
}
private static void throwInvalidClientRegistration(String errorCode, String fieldName) {
OAuth2Error error = new OAuth2Error(errorCode, "Invalid Client Registration: " + fieldName, ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2ClientRegistrationAuthenticationProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ShipmentOrderLogRepository
{
private final ObjectMapper objectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
public void save(@NonNull final ShipmentOrderLogCreateRequest logRequest)
{
final I_Carrier_ShipmentOrder_Log log = InterfaceWrapperHelper.newInstance(I_Carrier_ShipmentOrder_Log.class);
final JsonDeliveryRequest request = logRequest.getRequest();
final JsonDeliveryResponse response = logRequest.getResponse();
log.setCarrier_ShipmentOrder_ID(request.getDeliveryOrderId());
log.setRequestMessage(toJson(request));
log.setResponseMessage(toJson(response.withoutPDFContents()));//Don't save the PDF contents
log.setDurationMillis((int)logRequest.getDurationMillis());
log.setIsError(response.isError());
log.setRequestID(request.getId());
InterfaceWrapperHelper.saveRecord(log);
} | @NonNull
private String toJson(@NonNull final Object object)
{
if (object instanceof String)
{
return (String)object;
}
try
{
return objectMapper.writeValueAsString(object);
}
catch (final JsonProcessingException e)
{
return object.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\ShipmentOrderLogRepository.java | 2 |
请完成以下Spring Boot application配置 | spring:
application:
name: listener-demo
server:
port: ${random.int[10000,19999]} # 随机端口,方便启动多个消费者
# rocketmq 配置项,对应 RocketMQProperties | 配置类
rocketmq:
name-server: 127.0.0.1:9876 # RocketMQ Namesrv | repos\SpringBoot-Labs-master\labx-20\labx-20-sca-bus-rocketmq-demo-listener\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public UserInfo grant(TokenParameter tokenParameter) {
HttpServletRequest request = WebUtil.getRequest();
String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);
// 开放平台来源
String sourceParameter = request.getParameter("source");
// 匹配是否有别名定义
String source = socialProperties.getAlias().getOrDefault(sourceParameter, sourceParameter);
// 开放平台授权码
String code = request.getParameter("code");
// 开放平台状态吗
String state = request.getParameter("state");
// 获取开放平台授权数据
AuthRequest authRequest = SocialUtil.getAuthRequest(source, socialProperties);
AuthCallback authCallback = new AuthCallback();
authCallback.setCode(code);
authCallback.setState(state);
AuthResponse authResponse = authRequest.login(authCallback);
AuthUser authUser;
if (authResponse.getCode() == AUTH_SUCCESS_CODE) { | authUser = (AuthUser) authResponse.getData();
} else {
throw new ServiceException("social grant failure, auth response is not success");
}
// 组装数据
UserOauth userOauth = Objects.requireNonNull(BeanUtil.copyProperties(authUser, UserOauth.class));
userOauth.setSource(authUser.getSource());
userOauth.setTenantId(tenantId);
userOauth.setUuid(authUser.getUuid());
// 远程调用,获取认证信息
R<UserInfo> result = userClient.userAuthInfo(userOauth);
return result.getData();
}
} | repos\SpringBlade-master\blade-auth\src\main\java\org\springblade\auth\granter\SocialTokenGranter.java | 1 |
请完成以下Java代码 | public void addInputMethodListener (InputMethodListener l)
{
m_textArea.addInputMethodListener(l);
}
/**
* Get text Input Method Requests
* @return requests
*/
@Override
public InputMethodRequests getInputMethodRequests()
{
return m_textArea.getInputMethodRequests();
}
/**
* Set Text Input Verifier | * @param l
*/
@Override
public void setInputVerifier (InputVerifier l)
{
m_textArea.setInputVerifier(l);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // CTextArea | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java | 1 |
请完成以下Java代码 | public void keyPressed(KeyEvent e)
{
} // keyPressed
/**
* key Released
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
* @param e
*/
@Override
public void keyReleased(KeyEvent e)
{
} // keyReleased
/**
* key Typed
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
* @param e
*/
@Override
public void keyTyped(KeyEvent e)
{
} // keyTyped | @Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
@Override
public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)
{
// NOTE: overridden just to make it public
return super.processKeyBinding(ks, e, condition, pressed);
}
} // CTextField | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextField.java | 1 |
请完成以下Java代码 | public static PlainPackingMaterialDocumentLineSource of(final I_M_HU_PackingMaterial packingMaterial, final int qty)
{
return of(packingMaterial, qty, null, 0);
}
public static PlainPackingMaterialDocumentLineSource of(final I_M_HU_PackingMaterial packingMaterial,
final int qty,
final ProductId lUProductID,
final int luQty)
{
return new PlainPackingMaterialDocumentLineSource(packingMaterial, qty, lUProductID, luQty);
}
List<I_M_HU_PackingMaterial> M_HU_PackingMaterials;
BigDecimal qty;
@Nullable ProductId lUProductId; | BigDecimal qtyLU;
private PlainPackingMaterialDocumentLineSource(final I_M_HU_PackingMaterial packingMaterial,
final int qty,
@Nullable final ProductId lUProductId,
final int qtyLU)
{
super();
Check.assumeNotNull(packingMaterial, "packingMaterial not null");
M_HU_PackingMaterials = Collections.singletonList(packingMaterial);
this.qty = BigDecimal.valueOf(qty);
this.lUProductId = lUProductId;
this.qtyLU = BigDecimal.valueOf(qtyLU);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\PlainPackingMaterialDocumentLineSource.java | 1 |
请完成以下Java代码 | private static RuleServiceProvider instantiateJessInstance() throws ClassNotFoundException, ConfigurationException {
// Load the rule service provider of the reference implementation.
// Loading this class will automatically register this provider with the provider manager.
Class.forName(RULE_SERVICE_PROVIDER + ".RuleServiceProviderImpl");
// Get the rule service provider from the provider manager.
return RuleServiceProviderManager.getRuleServiceProvider(RULE_SERVICE_PROVIDER);
}
private static void runRules(String rulesURI, RuleServiceProvider ruleServiceProvider)
throws ConfigurationException, RuleSessionTypeUnsupportedException, RuleSessionCreateException, RuleExecutionSetNotFoundException, RemoteException, InvalidRuleSessionException {
// Get a RuleRuntime and invoke the rule engine.
RuleRuntime ruleRuntime = ruleServiceProvider.getRuleRuntime();
//Create a statelessRuleSession.
StatelessRuleSession statelessRuleSession = (StatelessRuleSession) ruleRuntime.createRuleSession(rulesURI, new HashMap(), RuleRuntime.STATELESS_SESSION_TYPE);
calculateResults(statelessRuleSession);
statelessRuleSession.release();
}
private static void calculateResults(StatelessRuleSession statelessRuleSession) throws InvalidRuleSessionException, RemoteException {
List data = prepareData();
// execute the rules
List results = statelessRuleSession.executeRules(data);
checkResults(results);
}
private static List prepareData() {
List data = new ArrayList();
data.add(new Question("Can I have a bonus?", -5));
return data;
}
private static void checkResults(List results) {
Iterator itr = results.iterator(); | while (itr.hasNext()) {
Object obj = itr.next();
if (obj instanceof Answer) {
log.info(obj.toString());
}
}
}
private static void registerRules(String rulesFile, String rulesURI, RuleServiceProvider serviceProvider) throws ConfigurationException, RuleExecutionSetCreateException, IOException, RuleExecutionSetRegisterException {
// Get the rule administrator.
RuleAdministrator ruleAdministrator = serviceProvider.getRuleAdministrator();
// load the rules
InputStream ruleInput = JessWithJsr94.class.getResourceAsStream(rulesFile);
HashMap vendorProperties = new HashMap();
// Create the RuleExecutionSet
RuleExecutionSet ruleExecutionSet = ruleAdministrator
.getLocalRuleExecutionSetProvider(vendorProperties)
.createRuleExecutionSet(ruleInput, vendorProperties);
// Register the rule execution set.
ruleAdministrator.registerRuleExecutionSet(rulesURI, ruleExecutionSet, vendorProperties);
}
} | repos\tutorials-master\rule-engines-modules\jess\src\main\java\com\baeldung\rules\jess\JessWithJsr94.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getMerchantNo() {
return merchantNo;
}
public void setMerchantNo(String merchantNo) {
this.merchantNo = merchantNo;
}
public String getMerchantOrderNo() {
return merchantOrderNo;
}
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo;
}
public String getPayKey() {
return payKey;
}
public void setPayKey(String payKey) {
this.payKey = payKey;
}
public TradeStatusEnum getTradeStatus() {
return tradeStatus;
} | public void setTradeStatus(TradeStatusEnum tradeStatus) {
this.tradeStatus = tradeStatus;
}
public boolean isAuth() {
return isAuth;
}
public void setAuth(boolean auth) {
isAuth = auth;
}
public Map<String, PayTypeEnum> getPayTypeEnumMap() {
return payTypeEnumMap;
}
public void setPayTypeEnumMap(Map<String, PayTypeEnum> payTypeEnumMap) {
this.payTypeEnumMap = payTypeEnumMap;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthInitResultVo.java | 2 |
请完成以下Java代码 | class UseZonedDateTime {
ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) {
return ZonedDateTime.of(localDateTime, zoneId);
}
ZonedDateTime getZonedDateTimeUsingParseMethod(String parsableString) {
return ZonedDateTime.parse(parsableString);
}
ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) {
ZonedDateTime startOfDay = localDate.atStartOfDay()
.atZone(zone);
return startOfDay;
}
ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) {
ZonedDateTime startOfDay = localDate.atStartOfDay(zone);
return startOfDay;
} | ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) {
ZonedDateTime startOfDay = zonedDateTime.toLocalDateTime()
.toLocalDate()
.atStartOfDay(zonedDateTime.getZone());
return startOfDay;
}
ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) {
ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0);
return startOfDay;
}
ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) {
ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0);
return startOfDay;
}
} | repos\tutorials-master\core-java-modules\core-java-8-datetime\src\main\java\com\baeldung\datetime\UseZonedDateTime.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPayKey() {
return payKey;
}
public void setPayKey(String payKey) {
this.payKey = payKey;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public BigDecimal getOrderPrice() {
return orderPrice;
}
public void setOrderPrice(BigDecimal orderPrice) {
this.orderPrice = orderPrice;
}
public String getOrderIp() {
return orderIp;
}
public void setOrderIp(String orderIp) {
this.orderIp = orderIp;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
} | public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getPayType() {
return payType;
}
public void setPayType(String payType) {
this.payType = payType;
}
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
@Override
public String toString() {
return "F2FPayRequestBo{" +
"payKey='" + payKey + '\'' +
", authCode='" + authCode + '\'' +
", productName='" + productName + '\'' +
", orderNo='" + orderNo + '\'' +
", orderPrice=" + orderPrice +
", orderIp='" + orderIp + '\'' +
", orderDate='" + orderDate + '\'' +
", orderTime='" + orderTime + '\'' +
", sign='" + sign + '\'' +
", remark='" + remark + '\'' +
", payType='" + payType + '\'' +
'}';
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\F2FPayRequestBo.java | 2 |
请完成以下Java代码 | public class DynamicDataSourceModel {
public DynamicDataSourceModel() {
}
public DynamicDataSourceModel(Object dbSource) {
if (dbSource != null) {
BeanUtils.copyProperties(dbSource, this);
}
}
/**
* id
*/
private java.lang.String id;
/**
* 数据源编码
*/
private java.lang.String code;
/**
* 数据库类型
*/
private java.lang.String dbType;
/**
* 驱动类
*/
private java.lang.String dbDriver;
/**
* 数据源地址
*/
private java.lang.String dbUrl; | // /**
// * 数据库名称
// */
// private java.lang.String dbName;
/**
* 用户名
*/
private java.lang.String dbUsername;
/**
* 密码
*/
private java.lang.String dbPassword;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\DynamicDataSourceModel.java | 1 |
请完成以下Java代码 | protected void convertCommonTaskAttributes(XMLStreamReader xtr, Task task) {
task.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME));
String isBlockingString = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_IS_BLOCKING);
if (StringUtils.isNotEmpty(isBlockingString)) {
task.setBlocking(Boolean.valueOf(isBlockingString));
}
String isBlockingExpressionString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE,
CmmnXmlConstants.ATTRIBUTE_IS_BLOCKING_EXPRESSION);
if (StringUtils.isNotEmpty(isBlockingExpressionString)) {
task.setBlockingExpression(isBlockingExpressionString);
}
String isAsyncString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE,
CmmnXmlConstants.ATTRIBUTE_IS_ASYNCHRONOUS);
if (StringUtils.isNotEmpty(isAsyncString)) {
task.setAsync(Boolean.valueOf(isAsyncString.toLowerCase()));
} | String isExclusiveString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE,
CmmnXmlConstants.ATTRIBUTE_IS_EXCLUSIVE);
if (StringUtils.isNotEmpty(isExclusiveString)) {
task.setExclusive(Boolean.valueOf(isExclusiveString));
}
String isAsyncLeaveString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE,
CmmnXmlConstants.ATTRIBUTE_IS_ASYNCHRONOUS_LEAVE);
if (StringUtils.isNotEmpty(isAsyncLeaveString)) {
task.setAsyncLeave(Boolean.valueOf(isAsyncLeaveString.toLowerCase()));
}
String isAsyncLeaveExclusiveString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE,
CmmnXmlConstants.ATTRIBUTE_IS_ASYNCHRONOUS_LEAVE_EXCLUSIVE);
if (StringUtils.isNotEmpty(isAsyncLeaveExclusiveString)) {
task.setAsyncLeaveExclusive(Boolean.valueOf(isAsyncLeaveExclusiveString));
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\TaskXmlConverter.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_Container_URL[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Last Checked.
@param Checked
Info when we did the last check
*/
public void setChecked (Timestamp Checked)
{
set_Value (COLUMNNAME_Checked, Checked);
}
/** Get Last Checked.
@return Info when we did the last check
*/
public Timestamp getChecked ()
{
return (Timestamp)get_Value(COLUMNNAME_Checked);
}
public I_CM_Container getCM_Container() throws RuntimeException
{
return (I_CM_Container)MTable.get(getCtx(), I_CM_Container.Table_Name)
.getPO(getCM_Container_ID(), get_TrxName()); }
/** Set Web Container.
@param CM_Container_ID
Web Container contains content like images, text etc.
*/
public void setCM_Container_ID (int CM_Container_ID)
{
if (CM_Container_ID < 1)
set_Value (COLUMNNAME_CM_Container_ID, null);
else
set_Value (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID));
}
/** Get Web Container.
@return Web Container contains content like images, text etc.
*/
public int getCM_Container_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Container URL.
@param CM_Container_URL_ID
Contains info on used URLs
*/
public void setCM_Container_URL_ID (int CM_Container_URL_ID)
{
if (CM_Container_URL_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, Integer.valueOf(CM_Container_URL_ID));
}
/** Get Container URL.
@return Contains info on used URLs
*/
public int getCM_Container_URL_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_URL_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Last Result.
@param Last_Result
Contains data on the last check result
*/
public void setLast_Result (String Last_Result)
{
set_Value (COLUMNNAME_Last_Result, Last_Result);
}
/** Get Last Result.
@return Contains data on the last check result
*/
public String getLast_Result ()
{
return (String)get_Value(COLUMNNAME_Last_Result);
}
/** Set Status.
@param Status
Status of the currently running check
*/
public void setStatus (String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
public String getStatus ()
{
return (String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container_URL.java | 1 |
请完成以下Java代码 | private void checkExpression(@NonNull final ContextPath path, @NonNull final ContextVariablesExpression expression)
{
if (expression.isConstant()) {return;}
try
{
for (final String contextVariable : expression.getRequiredContextVariables())
{
if (checkContextVariableResolved(path, contextVariable))
{
continue;
}
String message = "No context variable `" + contextVariable + "` found in " + path + ".";
final ContextVariables contextVariables = getCurrentContextVariables();
final Set<String> suggestedParameterNames = contextVariables.findSimilar(contextVariable);
if (!suggestedParameterNames.isEmpty())
{
message += " You might want to use one of " + suggestedParameterNames + " instead.";
}
errorsCollector.collectError(
newException(message).setParameter("expression", expression)
);
}
}
catch (Exception ex)
{
errorsCollector.collectError(ex);
}
}
private boolean checkContextVariableResolved(@NonNull final ContextPath path, @NonNull final String contextVariable)
{
final ContextVariables contextVariables = getCurrentContextVariables();
final boolean isFound = contextVariables.contains(contextVariable); | missingContextVariables.recordContextVariableUsed(path, contextVariable, isFound);
return isFound || missingContextVariables.isKnownAsMissing(path, contextVariable);
}
private AdempiereException newException(final String message)
{
final AdempiereException exception = new AdempiereException(message);
fillContextInfo(exception);
return exception;
}
private AdempiereException wrapException(final Exception exception)
{
final AdempiereException wrappedException = AdempiereException.wrapIfNeeded(exception);
fillContextInfo(wrappedException);
return wrappedException;
}
private void fillContextInfo(final AdempiereException exception)
{
exception.setParameter("contextPath", getCurrentPath());
final ContextVariables contextVariables = getCurrentContextVariables();
if (contextVariables != null)
{
exception.setParameter("contextVariables", contextVariables.toSummaryString());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariablesCheckCommand.java | 1 |
请完成以下Java代码 | public abstract class KafkaEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
private static final String UNCHECKED = "unchecked";
private transient final Object container;
public KafkaEvent(Object source, Object container) {
super(source);
this.container = container;
}
/**
* Get the container for which the event was published, which will be the parent
* container if the source that emitted the event is a child container, or the source
* itself otherwise. The type is required here to avoid a dependency tangle between
* the event and listener packages.
* @param type the container type (e.g. {@code MessageListenerContainer.class}).
* @param <T> the type.
* @return the container.
* @since 2.2.1
* @see #getSource(Class)
*/
@SuppressWarnings(UNCHECKED)
public <T> T getContainer(Class<T> type) {
Assert.isInstanceOf(type, this.container); | return (T) this.container;
}
/**
* Get the container (source) that published the event. This is provided as an
* alternative to {@link #getSource()} to avoid the need to cast in user code. The
* type is required here to avoid a dependency tangle between the event and listener
* packages.
* @param type the container type (e.g. {@code MessageListenerContainer.class}).
* @param <T> the type.
* @return the container.
* @since 2.2.1
* @see #getContainer(Class)
* @see #getSource()
*/
@SuppressWarnings(UNCHECKED)
public <T> T getSource(Class<T> type) {
Assert.isInstanceOf(type, getSource());
return (T) getSource();
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\KafkaEvent.java | 1 |
请完成以下Java代码 | public Filter saveFilter(Filter filter) {
return commandExecutor.execute(new SaveFilterCmd(filter));
}
public Filter getFilter(String filterId) {
return commandExecutor.execute(new GetFilterCmd(filterId));
}
public void deleteFilter(String filterId) {
commandExecutor.execute(new DeleteFilterCmd(filterId));
}
@SuppressWarnings("unchecked")
public <T> List<T> list(String filterId) {
return (List<T>) commandExecutor.execute(new ExecuteFilterListCmd(filterId));
}
@SuppressWarnings("unchecked")
public <T, Q extends Query<?, T>> List<T> list(String filterId, Q extendingQuery) {
return (List<T>) commandExecutor.execute(new ExecuteFilterListCmd(filterId, extendingQuery));
}
@SuppressWarnings("unchecked")
public <T> List<T> listPage(String filterId, int firstResult, int maxResults) {
return (List<T>) commandExecutor.execute(new ExecuteFilterListPageCmd(filterId, firstResult, maxResults));
}
@SuppressWarnings("unchecked")
public <T, Q extends Query<?, T>> List<T> listPage(String filterId, Q extendingQuery, int firstResult, int maxResults) {
return (List<T>) commandExecutor.execute(new ExecuteFilterListPageCmd(filterId, extendingQuery, firstResult, maxResults)); | }
@SuppressWarnings("unchecked")
public <T> T singleResult(String filterId) {
return (T) commandExecutor.execute(new ExecuteFilterSingleResultCmd(filterId));
}
@SuppressWarnings("unchecked")
public <T, Q extends Query<?, T>> T singleResult(String filterId, Q extendingQuery) {
return (T) commandExecutor.execute(new ExecuteFilterSingleResultCmd(filterId, extendingQuery));
}
public Long count(String filterId) {
return commandExecutor.execute(new ExecuteFilterCountCmd(filterId));
}
public Long count(String filterId, Query<?, ?> extendingQuery) {
return commandExecutor.execute(new ExecuteFilterCountCmd(filterId, extendingQuery));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\FilterServiceImpl.java | 1 |
请完成以下Java代码 | public static void doDBFunctionCall(
@NonNull final DBFunction function,
@Nullable final DataImportConfigId dataImportConfigId,
final int recordId)
{
final String sql = new StringBuilder()
.append("SELECT ")
.append(function.getSchema())
.append(".")
.append(function.getName())
.append("(?,?)")
.toString();
final Object[] sqlParams = new Object[] {
DataImportConfigId.toRepoId(dataImportConfigId),
recordId };
DB.executeFunctionCallEx(ITrx.TRXNAME_ThreadInherited, sql, sqlParams);
logger.debug("\nExecuted {} with params: {}", function, sqlParams);
} | /**
* Used to call import DB functions using c_dataimport_run_id
*/
public static void doDBFunctionCall(
@NonNull final DBFunction function,
@Nullable final DataImportRunId dataImportRunId)
{
final String sql = new StringBuilder()
.append("SELECT ")
.append(function.getSchema())
.append(".")
.append(function.getName())
.append("(?)")
.toString();
final Object[] sqlParams = new Object[] {
DataImportRunId.toRepoId(dataImportRunId) };
DB.executeFunctionCallEx(ITrx.TRXNAME_ThreadInherited, sql, sqlParams);
logger.debug("\nExecuted {} with params: {}", function, sqlParams);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\DBFunctionHelper.java | 1 |
请完成以下Java代码 | public abstract class DeviceAwareSessionContext implements SessionContext {
@Getter
protected final UUID sessionId;
@Getter
private volatile DeviceId deviceId;
@Getter
private volatile TenantId tenantId;
@Getter
protected volatile TransportDeviceInfo deviceInfo;
@Getter
@Setter
protected volatile DeviceProfile deviceProfile;
@Getter
@Setter
protected volatile TransportProtos.SessionInfoProto sessionInfo;
@Setter
private volatile boolean connected;
public DeviceId getDeviceId() {
return deviceId;
}
public void setDeviceInfo(TransportDeviceInfo deviceInfo) {
this.deviceInfo = deviceInfo;
this.deviceId = deviceInfo.getDeviceId();
this.tenantId = deviceInfo.getTenantId();
}
@Override
public void onDeviceProfileUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceProfile deviceProfile) {
this.sessionInfo = sessionInfo;
this.deviceProfile = deviceProfile;
this.deviceInfo.setDeviceType(deviceProfile.getName());
} | @Override
public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional<DeviceProfile> deviceProfileOpt) {
this.sessionInfo = sessionInfo;
this.deviceInfo.setDeviceProfileId(device.getDeviceProfileId());
this.deviceInfo.setDeviceType(device.getType());
deviceProfileOpt.ifPresent(profile -> this.deviceProfile = profile);
}
public boolean isConnected() {
return connected;
}
public void setDisconnected() {
this.connected = false;
}
public boolean isSparkplug() {
DeviceProfileTransportConfiguration transportConfiguration = this.deviceProfile.getProfileData().getTransportConfiguration();
if (transportConfiguration instanceof MqttDeviceProfileTransportConfiguration) {
return ((MqttDeviceProfileTransportConfiguration) transportConfiguration).isSparkplug();
} else {
return false;
}
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\session\DeviceAwareSessionContext.java | 1 |
请完成以下Java代码 | public static String jsonObject() throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(new LinkedHashMap<String, Object>() {{
put("name", "John Doe");
put("age", 30);
}});
}
public static String jsonComposer() throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.composeString()
.startObject()
.startArrayField("objectArray")
.startObject()
.put("name", "name1")
.put("age", 11)
.end()
.startObject()
.put("name", "name2")
.put("age", 12)
.end()
.end()
.startArrayField("array")
.add(1)
.add(2)
.add(3)
.end()
.startObjectField("object")
.put("name", "name3")
.put("age", 13)
.end()
.put("last", true)
.end()
.finish();
}
public static String objectSerialization(Person person) throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(person);
}
public static String objectAnnotationSerialization(Person person) throws IOException {
return JSON.builder()
.register(JacksonAnnotationExtension.std)
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(person);
}
public static String customObjectSerialization(Person person) throws IOException {
return JSON.builder()
.register(new JacksonJrExtension() {
@Override | protected void register(ExtensionContext extensionContext) {
extensionContext.insertProvider(new MyHandlerProvider());
}
})
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(person);
}
public static Person objectDeserialization(String json) throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.beanFrom(Person.class, json);
}
public static Person customObjectDeserialization(String json) throws IOException {
return JSON.builder()
.register(new JacksonJrExtension() {
@Override
protected void register(ExtensionContext extensionContext) {
extensionContext.insertProvider(new MyHandlerProvider());
}
})
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.beanFrom(Person.class, json);
}
} | repos\tutorials-master\jackson-modules\jackson-jr\src\main\java\com\baeldung\jacksonjr\JacksonJrFeatures.java | 1 |
请完成以下Java代码 | public String getUserId() {
return userId;
}
/**
* @return the id of the resource if there
* is only one {@link MissingAuthorization}, {@code null} otherwise
*
* @deprecated Use {@link #getMissingAuthorizations()} to get the id of the resource
* of the {@link MissingAuthorization}(s). This method may be removed in future versions.
*/
@Deprecated
public String getResourceId() {
if (missingAuthorizations.size() == 1) {
return missingAuthorizations.get(0).getResourceId();
}
return null;
}
/**
* @return Disjunctive list of {@link MissingAuthorization} from
* which a user needs to have at least one for the authorization to pass
*/
public List<MissingAuthorization> getMissingAuthorizations() {
return Collections.unmodifiableList(missingAuthorizations);
}
/**
* Generate exception message from the missing authorizations.
*
* @param userId to use
* @param missingAuthorizations to use
* @return The prepared exception message
*/
private static String generateExceptionMessage(String userId, List<MissingAuthorization> missingAuthorizations) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("The user with id '");
sBuilder.append(userId);
sBuilder.append("' does not have one of the following permissions: ");
sBuilder.append(generateMissingAuthorizationsList(missingAuthorizations));
return sBuilder.toString();
}
/**
* Generate a String containing a list of missing authorizations.
*
* @param missingAuthorizations
*/
public static String generateMissingAuthorizationsList(List<MissingAuthorization> missingAuthorizations) {
StringBuilder sBuilder = new StringBuilder();
boolean first = true;
for(MissingAuthorization missingAuthorization: missingAuthorizations) {
if (!first) {
sBuilder.append(" or ");
} else { | first = false;
}
sBuilder.append(generateMissingAuthorizationMessage(missingAuthorization));
}
return sBuilder.toString();
}
/**
* Generated exception message for the missing authorization.
*
* @param exceptionInfo to use
*/
private static String generateMissingAuthorizationMessage(MissingAuthorization exceptionInfo) {
StringBuilder builder = new StringBuilder();
String permissionName = exceptionInfo.getViolatedPermissionName();
String resourceType = exceptionInfo.getResourceType();
String resourceId = exceptionInfo.getResourceId();
builder.append("'");
builder.append(permissionName);
builder.append("' permission on resource '");
builder.append((resourceId != null ? (resourceId+"' of type '") : "" ));
builder.append(resourceType);
builder.append("'");
return builder.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\AuthorizationException.java | 1 |
请完成以下Java代码 | public class MissingResourceException extends AdempiereException
{
private static final long serialVersionUID = -3485523266695546853L;
/**
*
* @param resourceName name of the resource in terms of the respective endpoint. Example: {@code "billPartner"}.
* @param resourceIdentifier identifier with which the lookup was attempted. Example: {@code "ext-product123"}. Can be {@code null} if the missing resource had not to be explicitly specified, such as a default location.
* @param detail optional detail message. If not {@code null}, it is incorporated into the exception message.
*/
@Builder
private MissingResourceException(
@NonNull final String resourceName,
@Nullable final String resourceIdentifier,
@Nullable final Object parentResource,
@Nullable final ITranslatableString detail,
@Nullable final AdempiereException cause)
{
super(buildMessage(resourceName, resourceIdentifier, detail), cause);
appendParametersToMessage();
if (parentResource != null)
{
setParameter("parentResource", parentResource);
}
} | private static ITranslatableString buildMessage(
@NonNull final String resourceName,
@Nullable final String resourceIdentifier,
@Nullable final ITranslatableString detail)
{
final TranslatableStringBuilder result = TranslatableStrings.builder();
result.append(TranslatableStrings.constant("The resource with resourceName="
+ assumeNotEmpty(resourceName, "Parameter 'resourceName' may not be empty")));
if (!isEmpty(resourceIdentifier, true))
{
result.append(" - which is identified by resourceIdentifier=" + resourceIdentifier + " - ");
}
else
{
result.append(" - which has no resourceIdentifier - ");
}
result.append(" could not be found.");
if (detail != null)
{
result.append(" ");
result.append(detail);
}
return result.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\exception\MissingResourceException.java | 1 |
请完成以下Java代码 | public void setLetterSubject (java.lang.String LetterSubject)
{
set_Value (COLUMNNAME_LetterSubject, LetterSubject);
}
/** Get Subject.
@return Subject */
@Override
public java.lang.String getLetterSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterSubject);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0) | set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_C_Letter.java | 1 |
请完成以下Java代码 | public class WEBUI_ProcessHelper
{
private static final String SYSCONFIG_ALLOW_INFINIT_CAPACITY_TUS = "de.metas.ui.web.handlingunits.process.WEBUI_M_HU_Transform.AllowNewTUsWithInfiniteCapacity";
/**
* This method can be used by process methods that are annotated with {@link de.metas.ui.web.process.descriptor.ProcessParamLookupValuesProvide}.
* It returns the eligible PIIPs for the given product and partner.
*
* @param ctx
* @param productId
* @param bPartner optional, may be {@code null}
* @param includeVirtualItem if {@code true}, then the resulting list also contains the "virtual" PiiP.
* @return
*/
public LookupValuesList retrieveHUPIItemProducts(
@NonNull final Properties ctx,
@NonNull final ProductId productId,
@Nullable final BPartnerId bpartnerId,
final boolean includeVirtualItem)
{
final List<I_M_HU_PI_Item_Product> list = retrieveHUPIItemProductRecords(ctx, productId, bpartnerId, includeVirtualItem);
return list.stream()
.sorted(Comparator.comparing(I_M_HU_PI_Item_Product::getName))
.map(huPIItemProduct -> IntegerLookupValue.of(huPIItemProduct.getM_HU_PI_Item_Product_ID(), huPIItemProduct.getName()))
.collect(LookupValuesList.collect());
}
public List<I_M_HU_PI_Item_Product> retrieveHUPIItemProductRecords(
@NonNull final Properties ctx,
@NonNull final ProductId productId,
@Nullable final BPartnerId bpartnerId,
final boolean includeVirtualItem)
{
final IHUPIItemProductDAO hupiItemProductDAO = Services.get(IHUPIItemProductDAO.class);
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final boolean allowInfiniteCapacity = sysConfigBL.getBooleanValue(SYSCONFIG_ALLOW_INFINIT_CAPACITY_TUS, true,
Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx));
final List<I_M_HU_PI_Item_Product> list = hupiItemProductDAO
.retrieveTUs(ctx, productId, bpartnerId, allowInfiniteCapacity);
if (includeVirtualItem)
{
list.add(hupiItemProductDAO.retrieveVirtualPIMaterialItemProduct(ctx));
}
return list;
} | /**
* Creates a string of the form "PI-Version-Name (Qty x Included-PI)", e.g. "Palette (20 x IFCO)".
*
* @param huPIItem may not be {@code null}
* @return
*/
public String buildHUPIItemString(@NonNull final I_M_HU_PI_Item huPIItem)
{
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
final I_M_HU_PI includedPI = handlingUnitsDAO.getIncludedPI(huPIItem);
final String result = StringUtils.formatMessage("{} ({} x {})",
huPIItem.getM_HU_PI_Version().getName(),
huPIItem.getQty().setScale(0, RoundingMode.HALF_UP), // it's always integer quantities
includedPI.getName());
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\WEBUI_ProcessHelper.java | 1 |
请完成以下Java代码 | public PostingException setAcctSchema(final AcctSchema acctSchema)
{
_acctSchema = acctSchema;
resetMessageBuilt();
return this;
}
public ITranslatableString getDetailMessage()
{
return _detailMessage;
}
/**
* Sets the detail message.
* <p>
* NOTE: any other detail message which was appended by {@link #addDetailMessage(String)} will be lost.
*
* @see #addDetailMessage(String)
*/
public PostingException setDetailMessage(@Nullable final ITranslatableString detailMessage)
{
_detailMessage = TranslatableStrings.nullToEmpty(detailMessage);
resetMessageBuilt();
return this;
}
public PostingException setDetailMessage(final String detailMessage)
{
return setDetailMessage(TranslatableStrings.anyLanguage(detailMessage));
}
/**
* Appends given message to current detail message.
*
* @see #setDetailMessage(String)
*/
public PostingException addDetailMessage(final String detailMessageToAppend)
{
// If there is nothing to append, do nothing
if (Check.isBlank(detailMessageToAppend))
{
return this;
}
//
// Set append the detail message
if (TranslatableStrings.isEmpty(_detailMessage))
{
_detailMessage = TranslatableStrings.anyLanguage(detailMessageToAppend);
}
else
{
_detailMessage = TranslatableStrings.join("\n", _detailMessage, detailMessageToAppend);
}
resetMessageBuilt();
return this;
}
public PostingException setFact(final Fact fact)
{
_fact = fact;
resetMessageBuilt();
return this;
}
public Fact getFact()
{
return _fact;
}
private FactLine getFactLine()
{
return _factLine;
}
public PostingException setFactLine(final FactLine factLine)
{
this._factLine = factLine;
resetMessageBuilt();
return this;
}
/**
* @return <code>true</code> if the document's "Posted" status shall not been changed.
*/
public boolean isPreserveDocumentPostedStatus()
{
return _preserveDocumentPostedStatus;
}
/**
* If set, the document's "Posted" status shall not been changed. | */
public PostingException setPreserveDocumentPostedStatus()
{
_preserveDocumentPostedStatus = true;
resetMessageBuilt();
return this;
}
public PostingException setDocLine(final DocLine<?> docLine)
{
_docLine = docLine;
resetMessageBuilt();
return this;
}
public DocLine<?> getDocLine()
{
return _docLine;
}
@SuppressWarnings("unused")
public PostingException setLogLevel(@NonNull final Level logLevel)
{
this._logLevel = logLevel;
return this;
}
/**
* @return recommended log level to be used when reporting this issue
*/
public Level getLogLevel()
{
return _logLevel;
}
@Override
public PostingException setParameter(
final @NonNull String parameterName,
final @Nullable Object parameterValue)
{
super.setParameter(parameterName, parameterValue);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\PostingException.java | 1 |
请完成以下Java代码 | public class SysTenantPackUser implements Serializable {
private static final long serialVersionUID = 1L;
/**id*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private java.lang.String id;
/**租户产品包ID*/
@Excel(name = "租户产品包ID", width = 15)
@Schema(description = "租户产品包ID")
private java.lang.String packId;
/**用户ID*/
@Excel(name = "用户ID", width = 15)
@Schema(description = "用户ID")
private java.lang.String userId;
/**租户ID*/
@Excel(name = "租户ID", width = 15)
@Schema(description = "租户ID")
private java.lang.Integer tenantId;
/**创建人*/
@Schema(description = "创建人")
private java.lang.String createBy;
/**创建时间*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
@DateTimeFormat(pattern="yyyy-MM-dd")
@Schema(description = "创建时间")
private java.util.Date createTime;
/**更新人*/
@Schema(description = "更新人")
private java.lang.String updateBy;
/**更新时间*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
@DateTimeFormat(pattern="yyyy-MM-dd")
@Schema(description = "更新时间")
private java.util.Date updateTime; | private transient String realname;
private transient String packName;
private transient String packCode;
/**
* 状态(申请状态0 正常状态1)
*/
private Integer status;
public SysTenantPackUser(){
}
public SysTenantPackUser(Integer tenantId, String packId, String userId) {
this.packId = packId;
this.userId = userId;
this.tenantId = tenantId;
this.status = 1;
}
public SysTenantPackUser(SysTenantPackUser param, String userId, String realname) {
this.userId = userId;
this.realname = realname;
this.packId = param.getPackId();
this.tenantId = param.getTenantId();
this.packName = param.getPackName();
this.status = 1;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysTenantPackUser.java | 1 |
请完成以下Java代码 | public SpringApplicationRunListener getRunListener(SpringApplication application) {
return new SpringApplicationRunListener() {
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
throw new AbandonedRunException(context);
}
};
}
private <T> GenericApplicationContext run(ThrowingSupplier<T> action) {
try {
SpringApplication.withHook(this, action);
} | catch (AbandonedRunException ex) {
ApplicationContext context = ex.getApplicationContext();
Assert.state(context instanceof GenericApplicationContext,
() -> "AOT processing requires a GenericApplicationContext but got a "
+ ((context != null) ? context.getClass().getName() : "null"));
return (GenericApplicationContext) context;
}
throw new IllegalStateException(
"No application context available after calling main method of '%s'. Does it run a SpringApplication?"
.formatted(this.application.getName()));
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationAotProcessor.java | 1 |
请完成以下Java代码 | public int hashCode() {
return Objects.hash(getFirstName(), getLastName(), getSeatNumber());
}
@Override
public String toString() {
final StringBuilder toStringBuilder = new StringBuilder(getClass().getSimpleName());
toStringBuilder.append("{ id=").append(id);
toStringBuilder.append(", firstName='").append(firstName).append('\'');
toStringBuilder.append(", lastName='").append(lastName).append('\'');
toStringBuilder.append(", seatNumber=").append(seatNumber);
toStringBuilder.append('}');
return toStringBuilder.toString();
} | Long getId() {
return id;
}
String getFirstName() {
return firstName;
}
String getLastName() {
return lastName;
}
Integer getSeatNumber() {
return seatNumber;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\boot\passenger\Passenger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void create(DictDetail resources) {
dictDetailRepository.save(resources);
// 清理缓存
delCaches(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(DictDetail resources) {
DictDetail dictDetail = dictDetailRepository.findById(resources.getId()).orElseGet(DictDetail::new);
ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId());
resources.setId(dictDetail.getId());
dictDetailRepository.save(resources);
// 清理缓存
delCaches(resources);
}
@Override
public List<DictDetailDto> getDictByName(String name) {
String key = CacheKey.DICT_NAME + name;
List<DictDetail> dictDetails = redisUtils.getList(key, DictDetail.class);
if(CollUtil.isEmpty(dictDetails)){
dictDetails = dictDetailRepository.findByDictName(name);
redisUtils.set(key, dictDetails, 1 , TimeUnit.DAYS);
}
return dictDetailMapper.toDto(dictDetails);
} | @Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new);
// 清理缓存
delCaches(dictDetail);
dictDetailRepository.deleteById(id);
}
public void delCaches(DictDetail dictDetail){
Dict dict = dictRepository.findById(dictDetail.getDict().getId()).orElseGet(Dict::new);
redisUtils.del(CacheKey.DICT_NAME + dict.getName());
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DictDetailServiceImpl.java | 2 |
请完成以下Java代码 | public List<I_AD_JavaClass> retrieveJavaClasses(
@CacheCtx final Properties ctx,
final String javaClassTypeInternalName)
{
if (javaClassTypeInternalName == null)
{
return Collections.emptyList();
}
final IQueryBL queryBL = Services.get(IQueryBL.class);
return queryBL.createQueryBuilder(I_AD_JavaClass_Type.class, ctx, ITrx.TRXNAME_None)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_JavaClass_Type.COLUMNNAME_InternalName, javaClassTypeInternalName)
.andCollectChildren(I_AD_JavaClass.COLUMN_AD_JavaClass_Type_ID, I_AD_JavaClass.class)
.addOnlyActiveRecordsFilter()
.create()
.list();
} | @Override
@Cached(cacheName = I_AD_JavaClass_Type.Table_Name + "#by#" + I_AD_JavaClass_Type.COLUMNNAME_InternalName)
public I_AD_JavaClass_Type retrieveJavaClassTypeOrNull(
@CacheCtx final Properties ctx,
final String internalName)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
return queryBL.createQueryBuilder(I_AD_JavaClass_Type.class, ctx, ITrx.TRXNAME_None)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_JavaClass_Type.COLUMNNAME_InternalName, internalName)
.create()
.firstOnly(I_AD_JavaClass_Type.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\javaclasses\impl\JavaClassDAO.java | 1 |
请完成以下Java代码 | public static void putIfAbsent() {
HashMap<String, Product> productsByName = new HashMap<>();
Product chocolate = new Product("chocolate", "something sweet");
productsByName.putIfAbsent("E-Bike", chocolate);
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.put("E-Bike", chocolate);
}
}
public static void merge() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
eBike2.getTags().add("sport");
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProduct);
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
} | }
public static void compute() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
productsByName.compute("E-Bike", (k,v) -> {
if(v != null) {
return v.addTagsOfOtherProduct(eBike2);
} else {
return eBike2;
}
});
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\hashmapguide\Product.java | 1 |
请完成以下Java代码 | public void waitIsNotEmpty() throws InterruptedException {
synchronized (IS_NOT_EMPTY) {
IS_NOT_EMPTY.wait();
}
}
public void add(Message message) {
queue.add(message);
notifyIsNotEmpty();
}
public Message poll() {
Message mess = queue.poll();
notifyIsNotFull();
return mess;
} | public Integer getSize() {
return queue.size();
}
private void notifyIsNotFull() {
synchronized (IS_NOT_FULL) {
IS_NOT_FULL.notify();
}
}
private void notifyIsNotEmpty() {
synchronized (IS_NOT_EMPTY) {
IS_NOT_EMPTY.notify();
}
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\producerconsumer\DataQueue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DocumentPostingUserNotificationService
{
private static final Topic NOTIFICATIONS_TOPIC = Topic.distributed("de.metas.acct.UserNotifications");
@NonNull private final INotificationBL userNotifications = Services.get(INotificationBL.class);
public void notifyPostingError(
@NonNull final UserId recipientUserId,
@NonNull final TableRecordReference documentRef,
@NonNull final Exception exception)
{
notifyPostingError(recipientUserId, documentRef, AdempiereException.extractMessage(exception));
}
public void notifyPostingError(@NonNull final String message, final DocumentPostMultiRequest postRequests)
{
final List<UserNotificationRequest> notifications = postRequests.stream()
.map(postRequest -> toUserNotificationRequestOrNull(postRequest, message))
.filter(Objects::nonNull)
.collect(Collectors.toList());
userNotifications.sendAfterCommit(notifications);
}
public void notifyPostingError(
@NonNull final UserId recipientUserId,
@NonNull final TableRecordReference documentRef,
@NonNull final String message)
{
userNotifications.sendAfterCommit(toUserNotificationRequest(recipientUserId, documentRef, message));
} | private static UserNotificationRequest toUserNotificationRequestOrNull(
@NonNull final DocumentPostRequest postRequest,
@NonNull final String message)
{
final UserId recipientUserId = postRequest.getOnErrorNotifyUserId();
if (recipientUserId == null) {return null;}
return UserNotificationRequest.builder()
.topic(NOTIFICATIONS_TOPIC)
.recipientUserId(recipientUserId)
.contentPlain(message)
.targetAction(UserNotificationRequest.TargetRecordAction.of(postRequest.getRecord()))
.build();
}
private static UserNotificationRequest toUserNotificationRequest(
@NonNull final UserId recipientUserId,
@NonNull final TableRecordReference documentRef,
@NonNull final String message)
{
return UserNotificationRequest.builder()
.topic(NOTIFICATIONS_TOPIC)
.recipientUserId(recipientUserId)
.contentPlain(message)
.targetAction(UserNotificationRequest.TargetRecordAction.of(documentRef))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\DocumentPostingUserNotificationService.java | 2 |
请完成以下Java代码 | public void process(TransportProtos.SessionInfoProto sessionInfo, DeviceId gatewayId, List<GatewayMetadata> data, long serverReceiveTs) {
states.computeIfAbsent(gatewayId, k -> new GatewayMetricsState(sessionInfo)).update(data, serverReceiveTs);
}
public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceId gatewayId) {
var state = states.get(gatewayId);
if (state != null) {
state.updateSessionInfo(sessionInfo);
}
}
public void onDeviceDelete(DeviceId deviceId) {
states.remove(deviceId);
}
public void reportMetrics() {
if (states.isEmpty()) {
return;
}
Map<DeviceId, GatewayMetricsState> statesToReport = states;
states = new ConcurrentHashMap<>();
long ts = System.currentTimeMillis();
statesToReport.forEach((gatewayId, state) -> {
reportMetrics(state, ts);
});
}
private void reportMetrics(GatewayMetricsState state, long ts) { | if (state.isEmpty()) {
return;
}
var result = state.getStateResult();
var kvProto = TransportProtos.KeyValueProto.newBuilder()
.setKey(GATEWAY_METRICS)
.setType(TransportProtos.KeyValueType.JSON_V)
.setJsonV(JacksonUtil.toString(result))
.build();
TransportProtos.TsKvListProto tsKvList = TransportProtos.TsKvListProto.newBuilder()
.setTs(ts)
.addKv(kvProto)
.build();
TransportProtos.PostTelemetryMsg telemetryMsg = TransportProtos.PostTelemetryMsg.newBuilder()
.addTsKvList(tsKvList)
.build();
transportService.process(state.getSessionInfo(), telemetryMsg, TransportServiceCallback.EMPTY);
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\gateway\GatewayMetricsService.java | 1 |
请完成以下Java代码 | public class ProductItem {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
int id;
String name;
String description;
String status;
double price;
public ProductItem() {
}
public ProductItem(String name, String description, String status, double price) {
this.name = name;
this.description = description;
this.status = status;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
} | public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
} | repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\query\ProductItem.java | 1 |
请完成以下Java代码 | LocalDate computeEasterDateWithGaussAlgorithm(int year) {
int a = year % 19;
int b = year % 4;
int c = year % 7;
int k = year / 100;
int p = (13 + 8*k) / 25;
int q = k / 4;
int M = (15 - p + k - q) % 30;
int N = (4 + k - q) % 7;
int d = (19*a + M) % 30;
int e = (2*b + 4*c + 6*d + N) % 7;
if (d==29 && e == 6) {
return LocalDate.of(year, 4, 19);
} else if (d==28 && e==6 && ((11*M + 11)%30 < 10)) {
return LocalDate.of(year, 4, 18);
}
int H = 22 + d + e;
if (H <= 31) {
return LocalDate.of(year, 3, H);
}
return LocalDate.of(year, 4, H-31);
}
LocalDate computeEasterDateWithButcherMeeusAlgorithm(int year) {
int a = year % 19;
int b = year / 100;
int c = year % 100;
int d = b / 4;
int e = b % 4;
int f = (b + 8) / 25;
int g = (b - f + 1) / 3;
int h = (19*a + b - d - g + 15) % 30;
int i = c / 4;
int k = c % 4;
int l = (2*e + 2*i - h - k + 32) % 7;
int m = (a + 11*h + 22*l) / 451;
int t = h + l - 7*m + 114; | int n = t / 31;
int o = t % 31;
return LocalDate.of(year, n, o+1);
}
LocalDate computeEasterDateWithConwayAlgorithm(int year) {
int s = year / 100;
int t = year % 100;
int a = t / 4;
int p = s % 4;
int x = (9 - 2*p) % 7;
int y = (x + t + a) % 7;
int g = year % 19;
int G = g + 1;
int b = s / 4;
int r = 8 * (s + 11) / 25;
int C = -s + b + r;
int d = (11*G + C) % 30;
d = (d + 30) % 30;
int h = (551 - 19*d + G) / 544;
int e = (50 - d - h) % 7;
int f = (e + y) % 7;
int R = 57 - d - f - h;
if (R <= 31) {
return LocalDate.of(year, 3, R);
}
return LocalDate.of(year, 4, R-31);
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\eastersunday\EasterDateCalculator.java | 1 |
请完成以下Java代码 | public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
} | protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsPrefrenceAreaProductRelationExample.java | 1 |
请完成以下Java代码 | public boolean isOnlyAllowedTrxNamePrefixes()
{
return false;
}
@Override
public ITrxConstraints addAllowedTrxNamePrefix(String trxNamePrefix)
{
return this;
}
@Override
public ITrxConstraints removeAllowedTrxNamePrefix(String trxNamePrefix)
{
return this;
}
@Override
public Set<String> getAllowedTrxNamePrefixes()
{
return Collections.emptySet();
}
@Override
public ITrxConstraints setTrxTimeoutSecs(int secs, boolean logOnly)
{
return this;
}
@Override
public int getTrxTimeoutSecs()
{
return 0;
}
@Override
public boolean isTrxTimeoutLogOnly()
{
return false;
}
@Override
public ITrxConstraints setMaxTrx(int max)
{
return this;
}
@Override
public ITrxConstraints incMaxTrx(int num)
{
return this;
}
@Override
public int getMaxTrx()
{
return 0;
}
@Override
public int getMaxSavepoints()
{ | return 0;
}
@Override
public ITrxConstraints setMaxSavepoints(int maxSavePoints)
{
return this;
}
@Override
public boolean isAllowTrxAfterThreadEnd()
{
return false;
}
@Override
public ITrxConstraints setAllowTrxAfterThreadEnd(boolean allow)
{
return this;
}
@Override
public void reset()
{
}
@Override
public String toString()
{
return "TrxConstraints have been globally disabled. Add or change AD_SysConfig " + TrxConstraintsBL.SYSCONFIG_TRX_CONSTRAINTS_DISABLED + " to enable them";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraintsDisabled.java | 1 |
请完成以下Java代码 | public void append(final JdbcExportDataSource source)
{
final StringBuilder sqlInsert = new StringBuilder();
final StringBuilder sqlSelect = new StringBuilder();
final List<Object> sqlSelectParams = new ArrayList<Object>();
for (final Column field : fields.values())
{
final String columnName = field.getColumnName();
//
// INSERT part
if (sqlInsert.length() > 0)
{
sqlInsert.append(", ");
}
sqlInsert.append(columnName);
if (sqlSelect.length() > 0)
{
sqlSelect.append("\n, ");
}
//
// SELECT part
final String sourceColumnName = field.getSourceColumnName();
if (!Check.isEmpty(sourceColumnName))
{
sqlSelect.append(sourceColumnName).append(" AS ").append(columnName);
}
// Constant
else
{
sqlSelect.append("? AS ").append(columnName);
sqlSelectParams.add(field.getConstantValue());
}
}
final String sql = new StringBuilder()
.append("INSERT INTO ").append(tableName).append(" (").append(sqlInsert).append(")")
.append("\nSELECT ").append(sqlSelect) | .append("\nFROM (").append(source.getSqlSelect()).append(") t")
.toString();
final List<Object> sqlParams = new ArrayList<Object>();
sqlParams.addAll(sqlSelectParams);
sqlParams.addAll(source.getSqlParams());
final String trxName = Trx.TRXNAME_None;
final int count = DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams.toArray(), trxName);
logger.info("Inserted {} records into {} from {}", new Object[] { count, tableName, source });
}
public void addField(final String fieldName, final String sourceFieldName)
{
final Column field = new Column(fieldName, sourceFieldName, null);
fields.put(fieldName, field);
}
public void addConstant(final String fieldName, final Object value)
{
final Column field = new Column(fieldName, null, value);
fields.put(fieldName, field);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcTableExportDataDestination.java | 1 |
请完成以下Java代码 | public Optional<QtyAvailableStatus> getQtyAvailableStatus()
{
Optional<QtyAvailableStatus> qtyAvailableStatus = this._qtyAvailableStatus;
//noinspection OptionalAssignedToNull
if (qtyAvailableStatus == null)
{
qtyAvailableStatus = this._qtyAvailableStatus = computeQtyAvailableStatus();
}
return qtyAvailableStatus;
}
private Optional<QtyAvailableStatus> computeQtyAvailableStatus()
{
return QtyAvailableStatus.computeOfLines(byProductId.values(), product -> product.getQtyAvailableStatus().orElse(null));
}
public PickingJobCandidateProducts updatingEachProduct(@NonNull UnaryOperator<PickingJobCandidateProduct> updater)
{
if (byProductId.isEmpty())
{
return this;
}
final ImmutableMap<ProductId, PickingJobCandidateProduct> byProductIdNew = byProductId.values()
.stream()
.map(updater)
.collect(ImmutableMap.toImmutableMap(PickingJobCandidateProduct::getProductId, product -> product));
return Objects.equals(this.byProductId, byProductIdNew)
? this
: new PickingJobCandidateProducts(byProductIdNew);
}
@Nullable
public ProductId getSingleProductIdOrNull() | {
return singleProduct != null ? singleProduct.getProductId() : null;
}
@Nullable
public Quantity getSingleQtyToDeliverOrNull()
{
return singleProduct != null ? singleProduct.getQtyToDeliver() : null;
}
@Nullable
public Quantity getSingleQtyAvailableToPickOrNull()
{
return singleProduct != null ? singleProduct.getQtyAvailableToPick() : null;
}
@Nullable
public ITranslatableString getSingleProductNameOrNull()
{
return singleProduct != null ? singleProduct.getProductName() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobCandidateProducts.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ChatbotConfiguration {
@Bean
@Primary
ChatClient primaryChatClient(OpenAiChatModel chatModel) {
return ChatClient.create(chatModel);
}
@Bean
ChatClient secondaryChatClient(AnthropicChatModel chatModel) {
return ChatClient.create(chatModel);
}
@Bean
ChatModel tertiaryChatModel(
AnthropicApi anthropicApi,
AnthropicChatModel anthropicChatModel,
@Value("${spring.ai.anthropic.chat.options.tertiary-model}") String tertiaryModelName | ) {
AnthropicChatOptions chatOptions = anthropicChatModel.getDefaultOptions().copy();
chatOptions.setModel(tertiaryModelName);
return AnthropicChatModel.builder()
.anthropicApi(anthropicApi)
.defaultOptions(chatOptions)
.build();
}
@Bean
ChatClient tertiaryChatClient(@Qualifier("tertiaryChatModel") ChatModel tertiaryChatModel) {
return ChatClient.create(tertiaryChatModel);
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-multiple-llms\src\main\java\com\baeldung\multillm\ChatbotConfiguration.java | 2 |
请完成以下Java代码 | 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 int getSO_DocTypeTarget_ID()
{
return get_ValueAsInt(COLUMNNAME_SO_DocTypeTarget_ID);
}
@Override
public void setSO_TargetDocTypeReason (final @Nullable java.lang.String SO_TargetDocTypeReason)
{
set_Value (COLUMNNAME_SO_TargetDocTypeReason, SO_TargetDocTypeReason);
}
@Override
public java.lang.String getSO_TargetDocTypeReason()
{
return get_ValueAsString(COLUMNNAME_SO_TargetDocTypeReason);
}
@Override
public void setTaxID (final @Nullable java.lang.String TaxID)
{
set_Value (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
}
@Override
public void setTitleShort (final @Nullable java.lang.String TitleShort)
{
throw new IllegalArgumentException ("TitleShort is virtual column"); }
@Override
public java.lang.String getTitleShort()
{
return get_ValueAsString(COLUMNNAME_TitleShort);
}
@Override
public void setURL (final @Nullable java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
@Override
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
@Override
public void setURL2 (final @Nullable java.lang.String URL2)
{
set_Value (COLUMNNAME_URL2, URL2);
}
@Override
public java.lang.String getURL2()
{
return get_ValueAsString(COLUMNNAME_URL2);
}
@Override
public void setURL3 (final @Nullable java.lang.String URL3)
{
set_Value (COLUMNNAME_URL3, URL3); | }
@Override
public java.lang.String getURL3()
{
return get_ValueAsString(COLUMNNAME_URL3);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner.java | 1 |
请完成以下Java代码 | public class ClassPathFileSystemWatcher implements InitializingBean, DisposableBean, ApplicationContextAware {
private final FileSystemWatcher fileSystemWatcher;
private final @Nullable ClassPathRestartStrategy restartStrategy;
@SuppressWarnings("NullAway.Init")
private ApplicationContext applicationContext;
private boolean stopWatcherOnRestart;
/**
* Create a new {@link ClassPathFileSystemWatcher} instance.
* @param fileSystemWatcherFactory a factory to create the underlying
* {@link FileSystemWatcher} used to monitor the local file system
* @param restartStrategy the classpath restart strategy
* @param urls the URLs to watch
*/
public ClassPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory,
@Nullable ClassPathRestartStrategy restartStrategy, URL[] urls) {
Assert.notNull(fileSystemWatcherFactory, "'fileSystemWatcherFactory' must not be null");
Assert.notNull(urls, "'urls' must not be null");
this.fileSystemWatcher = fileSystemWatcherFactory.getFileSystemWatcher();
this.restartStrategy = restartStrategy;
this.fileSystemWatcher.addSourceDirectories(new ClassPathDirectories(urls));
}
/**
* Set if the {@link FileSystemWatcher} should be stopped when a full restart occurs.
* @param stopWatcherOnRestart if the watcher should be stopped when a restart occurs
*/
public void setStopWatcherOnRestart(boolean stopWatcherOnRestart) {
this.stopWatcherOnRestart = stopWatcherOnRestart;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override | public void afterPropertiesSet() throws Exception {
if (this.restartStrategy != null) {
FileSystemWatcher watcherToStop = null;
if (this.stopWatcherOnRestart) {
watcherToStop = this.fileSystemWatcher;
}
this.fileSystemWatcher.addListener(
new ClassPathFileChangeListener(this.applicationContext, this.restartStrategy, watcherToStop));
}
this.fileSystemWatcher.start();
}
@Override
public void destroy() throws Exception {
this.fileSystemWatcher.stop();
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\classpath\ClassPathFileSystemWatcher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseResult write(@RequestBody ShpInfo shpInfo) throws Exception{
return shpService.writeShp(shpInfo);
}
/**
* 查询一个shp文件
* @param shpFilePath 文件绝对路径
* @param limit 指定显示多少条shp特征【features】
* @return
* @throws Exception
*/
@GetMapping("/query")
public ResponseResult query(@RequestParam(value = "path",required = true) String shpFilePath,
@RequestParam(value = "limit",required = false,defaultValue = "10") Integer limit ) throws Exception{
return shpService.getShpDatas(shpFilePath,limit);
}
/**
* 将shp文件转换成png图片,图片或写入文件或通过response输出到界面【比如,客户端浏览器】
* @param path shp文件路径
* @param imagePath 如果imagePath不等于空,则shp文件转成图片文件存储进行存
* @param color 渲染颜色 | */
@GetMapping("/show")
public void show(@RequestParam(value = "path",required = true) String path,
@RequestParam(value = "imagePath",required = false) String imagePath,
@RequestParam(value = "color",required = false) String color,
HttpServletResponse response) throws Exception{
// 设置响应消息的类型
response.setContentType("image/png");
// 设置页面不缓存
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
shpService.showShp(path, imagePath,color ,response);
}
} | repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\controller\ShpController.java | 2 |
请完成以下Java代码 | public class OrderCheckupPrintingQueueHandler extends PrintingQueueHandlerAdapter
{
public static final transient OrderCheckupPrintingQueueHandler instance = new OrderCheckupPrintingQueueHandler();
private static final transient Logger logger = LogManager.getLogger(OrderCheckupPrintingQueueHandler.class);
private final transient IOrderCheckupBL orderCheckupBL = Services.get(IOrderCheckupBL.class);
/**
* Set the number of copies to the configured value.
* Note that this handler is invoked after the "standard" handler, because the main validator of de.metas.fresh
* has a higher SeqNo and is inititalized later.
*
* @task http://dewiki908/mediawiki/index.php/09467_Bestellkontrolle_2x_ausdrucken_%28103975976435%29
*/
@Override
public void afterEnqueueBeforeSave(final I_C_Printing_Queue queueItem, final I_AD_Archive printOut)
{
final int copies = orderCheckupBL.getNumberOfCopies(queueItem, printOut);
queueItem.setCopies(copies);
}
@Override
public void afterEnqueueAfterSave(final I_C_Printing_Queue queueItem, final I_AD_Archive printOut)
{
//
// Get the underlying report if applies
final I_C_Order_MFGWarehouse_Report report = orderCheckupBL.getReportOrNull(printOut);
if (report == null)
{
return;
}
setUserToPrint(queueItem, report);
}
/**
* Returns <code>true</code> if the given archive's <code>AD_Table_ID</code> is the ID of the <code>C_Order_MFGWarehouse_Report</code> table. | */
@Override
public boolean isApplyHandler(final I_C_Printing_Queue queueItem_IGNOED, final I_AD_Archive printOut)
{
return Services.get(IADTableDAO.class).isTableId(I_C_Order_MFGWarehouse_Report.Table_Name, printOut.getAD_Table_ID());
}
private final void setUserToPrint(final I_C_Printing_Queue queueItem, final I_C_Order_MFGWarehouse_Report report)
{
//
// Get the user that shall be used for printing.
// If there is no printing user, don't print it.
final int userToPrintId = report.getAD_User_Responsible_ID();
if (userToPrintId <= 0)
{
logger.info("Cancel from printing because there was no user to print: {}", report);
queueItem.setIsActive(false);
return;
}
//
// Set the new recipient
Services.get(IPrintingQueueBL.class).setPrintoutForOtherUsers(queueItem, ImmutableSet.of(userToPrintId));
}
private OrderCheckupPrintingQueueHandler()
{
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\printing\spi\impl\OrderCheckupPrintingQueueHandler.java | 1 |
请完成以下Java代码 | public void setDscntApldAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.dscntApldAmt = value;
}
/**
* Gets the value of the cdtNoteAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getCdtNoteAmt() {
return cdtNoteAmt;
}
/**
* Sets the value of the cdtNoteAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setCdtNoteAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.cdtNoteAmt = value;
}
/**
* Gets the value of the taxAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getTaxAmt() {
return taxAmt;
}
/**
* Sets the value of the taxAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTaxAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.taxAmt = value;
}
/**
* Gets the value of the adjstmntAmtAndRsn property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the adjstmntAmtAndRsn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdjstmntAmtAndRsn().add(newItem);
* </pre> | *
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DocumentAdjustment1 }
*
*
*/
public List<DocumentAdjustment1> getAdjstmntAmtAndRsn() {
if (adjstmntAmtAndRsn == null) {
adjstmntAmtAndRsn = new ArrayList<DocumentAdjustment1>();
}
return this.adjstmntAmtAndRsn;
}
/**
* Gets the value of the rmtdAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() {
return rmtdAmt;
}
/**
* Sets the value of the rmtdAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.rmtdAmt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\RemittanceAmount1.java | 1 |
请完成以下Java代码 | public void setAuditFileFolder (final java.lang.String AuditFileFolder)
{
set_Value (COLUMNNAME_AuditFileFolder, AuditFileFolder);
}
@Override
public java.lang.String getAuditFileFolder()
{
return get_ValueAsString(COLUMNNAME_AuditFileFolder);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class);
}
@Override
public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else | set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setWriteAudit (final boolean WriteAudit)
{
set_Value (COLUMNNAME_WriteAudit, WriteAudit);
}
@Override
public boolean isWriteAudit()
{
return get_ValueAsBoolean(COLUMNNAME_WriteAudit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config.java | 1 |
请完成以下Java代码 | public BlockingQueue<Runnable> getThreadPoolQueue() {
return threadPoolQueue;
}
public void setThreadPoolQueue(BlockingQueue<Runnable> threadPoolQueue) {
this.threadPoolQueue = threadPoolQueue;
}
public String getThreadPoolNamingPattern() {
return getConfiguration().getThreadPoolNamingPattern();
}
public void setThreadPoolNamingPattern(String threadPoolNamingPattern) {
getConfiguration().setThreadPoolNamingPattern(threadPoolNamingPattern);
}
public ThreadFactory getThreadFactory() {
return threadFactory;
}
public void setThreadFactory(ThreadFactory threadFactory) { | this.threadFactory = threadFactory;
}
public RejectedExecutionHandler getRejectedExecutionHandler() {
return rejectedExecutionHandler;
}
public void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler) {
this.rejectedExecutionHandler = rejectedExecutionHandler;
}
@Override
public int getRemainingCapacity() {
return threadPoolQueue.remainingCapacity();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\async\DefaultAsyncTaskExecutor.java | 1 |
请完成以下Java代码 | public abstract class AbstractEntity
{
@Id
@GeneratedValue
private Long id;
private boolean deleted = false;
@NotNull
private String uuid = UUID.randomUUID().toString();
//
// Versioning and created/updated timestamps
protected static final int VERSION_INITIAL = 0;
@Version
private final int version = VERSION_INITIAL;
@Setter(AccessLevel.NONE) | @Temporal(TemporalType.TIMESTAMP)
private Date dateCreated;
@Setter(AccessLevel.NONE)
@Temporal(TemporalType.TIMESTAMP)
private Date dateUpdated;
@PreUpdate
@PrePersist
public void updateCreatedUpdated()
{
final Date now = new Date();
this.dateUpdated = now;
if (dateCreated == null)
{
dateCreated = now;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\jpa\AbstractEntity.java | 1 |
请完成以下Java代码 | public boolean supportsContext(Observation.Context context) {
return context instanceof AuthorizationObservationContext<?>;
}
private String getAuthenticationType(AuthorizationObservationContext<?> context) {
if (context.getAuthentication() == null) {
return "n/a";
}
return context.getAuthentication().getClass().getSimpleName();
}
private String getObjectType(AuthorizationObservationContext<?> context) {
if (context.getObject() == null) {
return "unknown";
}
if (context.getObject() instanceof MethodInvocation) {
return "method";
}
String className = context.getObject().getClass().getSimpleName();
if (className.contains("Method")) {
return "method";
}
if (className.contains("Request")) {
return "request";
}
if (className.contains("Message")) {
return "message";
}
if (className.contains("Exchange")) {
return "exchange";
}
return className;
}
private String getAuthorizationDecision(AuthorizationObservationContext<?> context) {
if (context.getAuthorizationResult() == null) {
return "unknown"; | }
return String.valueOf(context.getAuthorizationResult().isGranted());
}
private String getAuthorities(AuthorizationObservationContext<?> context) {
if (context.getAuthentication() == null) {
return "n/a";
}
return String.valueOf(context.getAuthentication().getAuthorities());
}
private String getDecisionDetails(AuthorizationObservationContext<?> context) {
if (context.getAuthorizationResult() == null) {
return "unknown";
}
AuthorizationResult decision = context.getAuthorizationResult();
return String.valueOf(decision);
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationObservationConvention.java | 1 |
请完成以下Java代码 | public class X_S_TimeType extends PO implements I_S_TimeType, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_S_TimeType (Properties ctx, int S_TimeType_ID, String trxName)
{
super (ctx, S_TimeType_ID, trxName);
/** if (S_TimeType_ID == 0)
{
setName (null);
setS_TimeType_ID (0);
} */
}
/** Load Constructor */
public X_S_TimeType (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_S_TimeType[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help | Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Time Type.
@param S_TimeType_ID
Type of time recorded
*/
public void setS_TimeType_ID (int S_TimeType_ID)
{
if (S_TimeType_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeType_ID, Integer.valueOf(S_TimeType_ID));
}
/** Get Time Type.
@return Type of time recorded
*/
public int getS_TimeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_TimeType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void setFirstCacheConfig(LayeringCacheManager layeringCacheManager) {
// 设置默认的一级缓存配置
String specification = this.cacheProperties.getCaffeine().getSpec();
if (StringUtils.hasText(specification)) {
layeringCacheManager.setCaffeineSpec(CaffeineSpec.parse(specification));
}
// 设置每个一级缓存的过期时间和自动刷新时间
Map<String, FirstCacheSetting> firstCacheSettings = new HashMap<>();
firstCacheSettings.put("people", new FirstCacheSetting("initialCapacity=5,maximumSize=500,expireAfterWrite=10s"));
firstCacheSettings.put("people1", new FirstCacheSetting("initialCapacity=5,maximumSize=50,expireAfterWrite=30s"));
layeringCacheManager.setFirstCacheSettings(firstCacheSettings);
}
private void setSecondaryCacheConfig(LayeringCacheManager layeringCacheManager) {
// 设置使用缓存名称(value属性)作为redis缓存前缀
layeringCacheManager.setUsePrefix(true);
//这里可以设置一个默认的过期时间 单位是秒
layeringCacheManager.setSecondaryCacheDefaultExpiration(redisDefaultExpiration); | // 设置每个二级缓存的过期时间和自动刷新时间
Map<String, SecondaryCacheSetting> secondaryCacheSettings = new HashMap<>();
secondaryCacheSettings.put("people", new SecondaryCacheSetting(selectCacheTimeout, selectCacheRefresh));
secondaryCacheSettings.put("people1", new SecondaryCacheSetting(5, 0, false,true));
secondaryCacheSettings.put("people2", new SecondaryCacheSetting(false, selectCacheTimeout, selectCacheRefresh));
secondaryCacheSettings.put("people3", new SecondaryCacheSetting(selectCacheTimeout, selectCacheRefresh, false, true));
layeringCacheManager.setSecondaryCacheSettings(secondaryCacheSettings);
}
/**
* 显示声明缓存key生成器
*
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\config\CacheConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected final RabbitProperties getRabbitProperties() {
return this.rabbitProperties;
}
/**
* Configure the specified rabbit listener container factory. The factory can be
* further tuned and default settings can be overridden.
* @param factory the {@link AbstractRabbitListenerContainerFactory} instance to
* configure
* @param connectionFactory the {@link ConnectionFactory} to use
*/
public abstract void configure(T factory, ConnectionFactory connectionFactory);
protected void configure(T factory, ConnectionFactory connectionFactory,
RabbitProperties.AmqpContainer configuration) {
Assert.notNull(factory, "'factory' must not be null");
Assert.notNull(connectionFactory, "'connectionFactory' must not be null");
Assert.notNull(configuration, "'configuration' must not be null");
factory.setConnectionFactory(connectionFactory);
if (this.messageConverter != null) {
factory.setMessageConverter(this.messageConverter);
}
factory.setAutoStartup(configuration.isAutoStartup());
if (configuration.getAcknowledgeMode() != null) {
factory.setAcknowledgeMode(configuration.getAcknowledgeMode());
}
if (configuration.getPrefetch() != null) {
factory.setPrefetchCount(configuration.getPrefetch());
}
if (configuration.getDefaultRequeueRejected() != null) {
factory.setDefaultRequeueRejected(configuration.getDefaultRequeueRejected());
}
if (configuration.getIdleEventInterval() != null) {
factory.setIdleEventInterval(configuration.getIdleEventInterval().toMillis());
}
factory.setMissingQueuesFatal(configuration.isMissingQueuesFatal());
factory.setDeBatchingEnabled(configuration.isDeBatchingEnabled());
factory.setForceStop(configuration.isForceStop());
if (this.taskExecutor != null) {
factory.setTaskExecutor(this.taskExecutor); | }
factory.setObservationEnabled(configuration.isObservationEnabled());
ListenerRetry retryConfig = configuration.getRetry();
if (retryConfig.isEnabled()) {
RetryInterceptorBuilder<?, ?> builder = (retryConfig.isStateless()) ? RetryInterceptorBuilder.stateless()
: RetryInterceptorBuilder.stateful();
builder.retryPolicy(createRetryPolicy(retryConfig));
MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer
: new RejectAndDontRequeueRecoverer();
builder.recoverer(recoverer);
factory.setAdviceChain(builder.build());
}
}
private RetryPolicy createRetryPolicy(Retry retryProperties) {
RetryPolicySettings retrySettings = retryProperties.initializeRetryPolicySettings();
if (this.retrySettingsCustomizers != null) {
for (RabbitListenerRetrySettingsCustomizer customizer : this.retrySettingsCustomizers) {
customizer.customize(retrySettings);
}
}
return retrySettings.createRetryPolicy();
}
} | repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\AbstractRabbitListenerContainerFactoryConfigurer.java | 2 |
请完成以下Java代码 | public int getC_Order_Cost_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Order_Cost_ID);
}
@Override
public I_C_OrderLine getC_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_C_OrderLine_ID, I_C_OrderLine.class);
}
@Override
public void setC_OrderLine(final I_C_OrderLine C_OrderLine)
{
set_ValueFromPO(COLUMNNAME_C_OrderLine_ID, I_C_OrderLine.class, C_OrderLine);
}
@Override
public void setC_OrderLine_ID (final int C_OrderLine_ID)
{
if (C_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID);
}
@Override
public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
@Override
public void setCostAmount (final BigDecimal CostAmount)
{
set_Value (COLUMNNAME_CostAmount, CostAmount);
}
@Override
public BigDecimal getCostAmount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setCostAmountReceived (final BigDecimal CostAmountReceived)
{
set_Value (COLUMNNAME_CostAmountReceived, CostAmountReceived);
}
@Override
public BigDecimal getCostAmountReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmountReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setLineNetAmt (final BigDecimal LineNetAmt)
{
set_Value (COLUMNNAME_LineNetAmt, LineNetAmt); | }
@Override
public BigDecimal getLineNetAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_LineNetAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReceived (final BigDecimal QtyReceived)
{
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
@Override
public BigDecimal getQtyReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost_Detail.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() { | return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public Set<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(Set<OrderItem> orderItems) {
this.orderItems = orderItems;
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-Multiple-DataStructure\src\main\java\spring\mvc\orders\entities\Order.java | 1 |
请完成以下Java代码 | default CookieSameSiteSupplier when(Predicate<Cookie> predicate) {
Assert.notNull(predicate, "'predicate' must not be null");
return (cookie) -> predicate.test(cookie) ? getSameSite(cookie) : null;
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns
* {@link SameSite#NONE}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofNone() {
return of(SameSite.NONE);
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns
* {@link SameSite#LAX}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofLax() {
return of(SameSite.LAX);
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns | * {@link SameSite#STRICT}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofStrict() {
return of(SameSite.STRICT);
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns the given
* {@link SameSite} value.
* @param sameSite the value to return
* @return the supplier instance
*/
static CookieSameSiteSupplier of(SameSite sameSite) {
Assert.notNull(sameSite, "'sameSite' must not be null");
return (cookie) -> sameSite;
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\CookieSameSiteSupplier.java | 1 |
请完成以下Java代码 | public class TableColumnPath implements ITableColumnPath
{
private String valueTableName;
private String valueColumnName;
private int valueDisplayType;
private String keyTableName;
private String keyColumnName;
private int recordId;
final private List<ITableColumnPathElement> elements = new ArrayList<ITableColumnPathElement>();
public TableColumnPath(String keyTableName, String keyColumnName, int recordId)
{
this.keyTableName = keyTableName;
this.keyColumnName = keyColumnName;
this.recordId = recordId;
}
public void setValueColumnName(String valueTableName, String valueColumnName, int valueDisplayType)
{
this.valueTableName = valueTableName;
this.valueColumnName = valueColumnName;
this.valueDisplayType = valueDisplayType;
}
public void addElement(TableColumnPathElement e)
{
elements.add(e);
}
@Override
public List<ITableColumnPathElement> getElements()
{
return Collections.unmodifiableList(this.elements);
}
@Override
public String getValueTableName()
{
return valueTableName;
}
@Override
public String getValueColumnName()
{
return valueColumnName;
}
@Override
public int getValueDisplayType()
{
return valueDisplayType; | }
@Override
public String getKeyTableName()
{
return keyTableName;
}
@Override
public String getKeyColumnName()
{
return keyColumnName;
}
@Override
public int getRecordId()
{
return recordId;
}
@Override
public String toString()
{
return "TableColumnPath [valueTableName=" + valueTableName + ", valueColumnName=" + valueColumnName + ", keyTableName=" + keyTableName + ", keyColumnName=" + keyColumnName + ", recordId="
+ recordId + ", elements=" + elements + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\model\TableColumnPath.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.