instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public UserEMailConfig getEmailConfigById(@NonNull final UserId userId)
{
final I_AD_User userRecord = userDAO.getById(userId);
return toUserEMailConfig(userRecord);
}
@Override
public ExplainedOptional<EMailAddress> getEMailAddressById(@NonNull final UserId userId)
{
final I_AD_User adUser = getById(userId);
final String email = StringUtils.trimBlankToNull(adUser.getEMail());
if (email == null)
{
return ExplainedOptional.emptyBecause("User " + adUser.getName() + " does not have email");
}
return ExplainedOptional.of(EMailAddress.ofString(email));
}
public static UserEMailConfig toUserEMailConfig(@NonNull final I_AD_User userRecord)
{
return UserEMailConfig.builder()
.userId(UserId.ofRepoId(userRecord.getAD_User_ID()))
.email(EMailAddress.ofNullableString(userRecord.getEMail()))
.username(userRecord.getEMailUser())
.password(userRecord.getEMailUserPW())
.build();
}
@Override
public void deleteUserDependency(@NonNull final I_AD_User userRecord)
{
UserId userId = UserId.ofRepoId(userRecord.getAD_User_ID());
|
valuePreferenceDAO.deleteUserPreferenceByUserId(userId);
getUserAuthTokenRepository().deleteUserAuthTokenByUserId(userId);
userRolePermissionsDAO.deleteUserOrgAccessByUserId(userId);
userRolePermissionsDAO.deleteUserOrgAssignmentByUserId(userId);
roleDAO.deleteUserRolesByUserId(userId);
getUserSubstituteRepository().deleteUserSubstituteByUserId(userId);
getUserMailRepository().deleteUserMailByUserId(userId);
getUserQueryRepository().deleteUserQueryByUserId(userId);
}
@Override
public String getUserFullNameById(@NonNull final UserId userId) {return userDAO.retrieveUserFullName(userId);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserBL.java
| 1
|
请完成以下Java代码
|
public int getM_PriceList_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_Version_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setProductPriceInStockUOM (final BigDecimal ProductPriceInStockUOM)
{
set_ValueNoCheck (COLUMNNAME_ProductPriceInStockUOM, ProductPriceInStockUOM);
}
@Override
public BigDecimal getProductPriceInStockUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ProductPriceInStockUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
|
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_ValueNoCheck (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_purchase_prices_in_stock_uom_plv_v.java
| 1
|
请完成以下Java代码
|
public void initHUStorages(final I_M_HU hu)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(hu);
delegate.initHUStorages(hu);
}
@Override
public void initHUItemStorages(final I_M_HU_Item item)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(item);
delegate.initHUItemStorages(item);
}
@Override
public I_M_HU_Storage retrieveStorage(final I_M_HU hu, final ProductId productId)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(hu);
return delegate.retrieveStorage(hu, productId);
}
@Override
public void save(final I_M_HU_Storage storage)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(storage);
delegate.save(storage);
}
@Override
public List<I_M_HU_Storage> retrieveStorages(final I_M_HU hu)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(hu);
return delegate.retrieveStorages(hu);
}
@Override
public void save(final I_M_HU_Item_Storage storageLine)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(storageLine);
delegate.save(storageLine);
}
@Override
public List<I_M_HU_Item_Storage> retrieveItemStorages(final I_M_HU_Item item)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(item);
|
return delegate.retrieveItemStorages(item);
}
@Override
public I_M_HU_Item_Storage retrieveItemStorage(final I_M_HU_Item item, @NonNull final ProductId productId)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(item);
return delegate.retrieveItemStorage(item, productId);
}
@Override
public void save(final I_M_HU_Item item)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(item);
delegate.save(item);
}
@Override
public I_C_UOM getC_UOMOrNull(final I_M_HU hu)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(hu);
return delegate.getC_UOMOrNull(hu);
}
@Override
public UOMType getC_UOMTypeOrNull(final I_M_HU hu)
{
final SaveDecoupledHUStorageDAO delegate = getDelegate(hu);
return delegate.getC_UOMTypeOrNull(hu);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\SaveOnCommitHUStorageDAO.java
| 1
|
请完成以下Java代码
|
protected String[] getDeploymentDescriptors(DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {
final ComponentDescription processApplicationComponent = ProcessApplicationAttachments.getProcessApplicationComponent(deploymentUnit);
final String paClassName = processApplicationComponent.getComponentClassName();
String[] deploymentDescriptorResourceNames = null;
Module module = deploymentUnit.getAttachment(MODULE);
Class<?> paClass = null;
try {
paClass = module.getClassLoader().loadClass(paClassName);
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException("Unable to load process application class '"+paClassName+"'.");
}
ProcessApplication annotation = paClass.getAnnotation(ProcessApplication.class);
if(annotation == null) {
deploymentDescriptorResourceNames = new String[]{ PROCESSES_XML };
} else {
deploymentDescriptorResourceNames = annotation.deploymentDescriptors();
}
return deploymentDescriptorResourceNames;
}
protected Enumeration<URL> getProcessesXmlResources(Module module, String[] deploymentDescriptors) throws DeploymentUnitProcessingException {
try {
return module.getClassLoader().getResources(PROCESSES_XML);
} catch (IOException e) {
throw new DeploymentUnitProcessingException(e);
}
}
protected VirtualFile getFile(URL processesXmlResource) throws DeploymentUnitProcessingException {
try {
return VFS.getChild(processesXmlResource.toURI());
} catch(Exception e) {
throw new DeploymentUnitProcessingException(e);
|
}
}
protected boolean isEmptyFile(URL url) {
InputStream inputStream = null;
try {
inputStream = url.openStream();
return inputStream.available() == 0;
} catch (IOException e) {
throw new ProcessEngineException("Could not open stream for " + url, e);
} finally {
IoUtil.closeSilently(inputStream);
}
}
protected ProcessesXml parseProcessesXml(URL url) {
final ProcessesXmlParser processesXmlParser = new ProcessesXmlParser();
ProcessesXml processesXml = processesXmlParser.createParse()
.sourceUrl(url)
.execute()
.getProcessesXml();
return processesXml;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessesXmlProcessor.java
| 1
|
请完成以下Java代码
|
public CaseDefinitionEntity findCaseDefinitionByKeyAndVersionAndTenantId(String caseDefinitionKey, Integer caseDefinitionVersion, String tenantId) {
Map<String, Object> params = new HashMap<>();
params.put("caseDefinitionKey", caseDefinitionKey);
params.put("caseDefinitionVersion", caseDefinitionVersion);
params.put("tenantId", tenantId);
List<CaseDefinitionEntity> results = getDbSqlSession().selectList("selectCaseDefinitionsByKeyAndVersionAndTenantId", params);
if (results.size() == 1) {
return results.get(0);
} else if (results.size() > 1) {
throw new FlowableException(
"There are " + results.size() + " case definitions with key = '" + caseDefinitionKey + "' and version = '" + caseDefinitionVersion
+ "' in tenant = '" + tenantId + "'.");
}
return null;
}
@Override
public void updateCaseDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateCaseDefinitionTenantIdForDeploymentId", params);
}
@Override
@SuppressWarnings("unchecked")
public List<CaseDefinition> findCaseDefinitionsByQueryCriteria(CaseDefinitionQueryImpl caseDefinitionQuery) {
setSafeInValueLists(caseDefinitionQuery);
|
return getDbSqlSession().selectList("selectCaseDefinitionsByQueryCriteria", caseDefinitionQuery);
}
@Override
public long findCaseDefinitionCountByQueryCriteria(CaseDefinitionQueryImpl caseDefinitionQuery) {
setSafeInValueLists(caseDefinitionQuery);
return (Long) getDbSqlSession().selectOne("selectCaseDefinitionCountByQueryCriteria", caseDefinitionQuery);
}
protected void setSafeInValueLists(CaseDefinitionQueryImpl caseDefinitionQuery) {
if (caseDefinitionQuery.getAuthorizationGroups() != null) {
caseDefinitionQuery.setSafeAuthorizationGroups(createSafeInValuesList(caseDefinitionQuery.getAuthorizationGroups()));
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisCaseDefinitionDataManager.java
| 1
|
请完成以下Java代码
|
public class CatchEventJsonConverter extends BaseBpmnJsonConverter {
public static void fillTypes(
Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap,
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
fillJsonTypes(convertersToBpmnMap);
fillBpmnTypes(convertersToJsonMap);
}
public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_EVENT_CATCH_TIMER, CatchEventJsonConverter.class);
convertersToBpmnMap.put(STENCIL_EVENT_CATCH_MESSAGE, CatchEventJsonConverter.class);
convertersToBpmnMap.put(STENCIL_EVENT_CATCH_SIGNAL, CatchEventJsonConverter.class);
}
public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
convertersToJsonMap.put(IntermediateCatchEvent.class, CatchEventJsonConverter.class);
}
protected String getStencilId(BaseElement baseElement) {
IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) baseElement;
List<EventDefinition> eventDefinitions = catchEvent.getEventDefinitions();
if (eventDefinitions.size() != 1) {
// return timer event as default;
return STENCIL_EVENT_CATCH_TIMER;
}
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof MessageEventDefinition) {
return STENCIL_EVENT_CATCH_MESSAGE;
} else if (eventDefinition instanceof SignalEventDefinition) {
return STENCIL_EVENT_CATCH_SIGNAL;
} else {
return STENCIL_EVENT_CATCH_TIMER;
}
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
IntermediateCatchEvent catchEvent = (IntermediateCatchEvent) baseElement;
addEventProperties(catchEvent, propertiesNode);
|
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
IntermediateCatchEvent catchEvent = new IntermediateCatchEvent();
String stencilId = BpmnJsonConverterUtil.getStencilId(elementNode);
if (STENCIL_EVENT_CATCH_TIMER.equals(stencilId)) {
convertJsonToTimerDefinition(elementNode, catchEvent);
} else if (STENCIL_EVENT_CATCH_MESSAGE.equals(stencilId)) {
convertJsonToMessageDefinition(elementNode, catchEvent);
} else if (STENCIL_EVENT_CATCH_SIGNAL.equals(stencilId)) {
convertJsonToSignalDefinition(elementNode, catchEvent);
}
return catchEvent;
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\CatchEventJsonConverter.java
| 1
|
请完成以下Spring Boot application配置
|
spring.application.name=config-server
server.port=7001
# git
spring.cloud.config.server.git.uri=http://git.oschina.net/didispace/SpringBoot-Learning/
spring.cloud.config.server.git.searchPaths=Chapter9-1-4/config-repo
spring.cloud.config.serve
|
r.git.username=username
spring.cloud.config.server.git.password=password
#
spring.profiles.active=native
|
repos\SpringBoot-Learning-master\1.x\Chapter9-1-4\config-server\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
@Override
public void setSinglePackage (final boolean SinglePackage)
{
set_Value (COLUMNNAME_SinglePackage, SinglePackage);
}
|
@Override
public boolean isSinglePackage()
{
return get_ValueAsBoolean(COLUMNNAME_SinglePackage);
}
@Override
public void setWorkplaceIndicator_ID (final int WorkplaceIndicator_ID)
{
throw new IllegalArgumentException ("WorkplaceIndicator_ID is virtual column"); }
@Override
public int getWorkplaceIndicator_ID()
{
return get_ValueAsInt(COLUMNNAME_WorkplaceIndicator_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step.java
| 1
|
请完成以下Java代码
|
public Collection<Class<? extends PPOrderCandidateUpdatedEvent>> getHandledEventType() {return ImmutableList.of(PPOrderCandidateUpdatedEvent.class);}
@Override
public void handleEvent(final PPOrderCandidateUpdatedEvent event)
{
final PPOrderCandidateId ppOrderCandidateId = event.getPpOrderCandidateId();
final ImmutableSet<PPOrderId> ppOrderIds = ppOrderCandidateDAO.getPPOrderIds(ppOrderCandidateId);
final PPOrderId ppOrderId = ppOrderIds.size() == 1 ? ppOrderIds.iterator().next() : null;
updateDistributionDetailsByPPOrderCandidateId(ppOrderCandidateId, ppOrderId);
final Set<DDOrderCandidateId> updatedDDOrderCandidateIds = updateDistributionCandidatesByPPOrderCandidateId(ppOrderCandidateId, ppOrderId);
updateDistributionOrdersByDDOrderCandidateIds(updatedDDOrderCandidateIds, ppOrderId);
}
private void updateDistributionDetailsByPPOrderCandidateId(@NonNull final PPOrderCandidateId ppOrderCandidateId, @Nullable final PPOrderId newPPOrderId)
{
candidateRepositoryWriteService.updateCandidatesByQuery(
CandidatesQuery.builder()
.businessCase(CandidateBusinessCase.DISTRIBUTION)
.distributionDetailsQuery(DistributionDetailsQuery.builder().ppOrderCandidateId(ppOrderCandidateId.getRepoId()).build())
.build(),
candidate -> {
final DistributionDetail distributionDetail = candidate.getBusinessCaseDetail(DistributionDetail.class)
.orElseThrow(() -> new AdempiereException("No DistributionDetail found for " + candidate));
return candidate.withBusinessCaseDetail(distributionDetail.withPPOrderId(newPPOrderId));
|
});
}
private Set<DDOrderCandidateId> updateDistributionCandidatesByPPOrderCandidateId(@NonNull final PPOrderCandidateId ppOrderCandidateId, @Nullable final PPOrderId newPPOrderId)
{
final HashSet<DDOrderCandidateId> ddOrderCandidateIds = new HashSet<>();
ddOrderCandidateRepository.updateByQuery(
DDOrderCandidateQuery.builder().ppOrderCandidateId(ppOrderCandidateId).excludePPOrderId(newPPOrderId).build(),
candidate -> {
ddOrderCandidateIds.add(candidate.getId());
return candidate.withForwardPPOrderId(newPPOrderId);
}
);
return ddOrderCandidateIds;
}
private void updateDistributionOrdersByDDOrderCandidateIds(@NonNull final Set<DDOrderCandidateId> ddOrderCandidateIds, @Nullable final PPOrderId newPPOrderId)
{
final Set<DDOrderId> ddOrderIds = ddOrderCandidateAllocRepository.getByCandidateIds(ddOrderCandidateIds).getDDOrderIds();
ddOrderLowLevelDAO.updateForwardPPOrderByIds(ddOrderIds, newPPOrderId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\material_dispo\PPOrderCandidateListeners.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Flyway firstFlyway(@Qualifier("configFlywayBooksDb") FlywayBookProperties properties,
@Qualifier("dataSourceBooksDb") HikariDataSource dataSource) {
return Flyway.configure()
.dataSource(dataSource)
.locations(properties.getLocation())
.load();
}
// second database, authorsdb
@Bean(name = "configAuthorsDb")
@ConfigurationProperties("app.datasource.ds2")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "configFlywayAuthorsDb")
public FlywayAuthorProperties secondFlywayProperties() {
return new FlywayAuthorProperties();
}
@Bean(name = "dataSourceAuthorsDb")
@ConfigurationProperties("app.datasource.ds2")
|
public HikariDataSource secondDataSource(@Qualifier("configAuthorsDb") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
@FlywayDataSource
@Bean(initMethod = "migrate")
public Flyway secondFlyway(@Qualifier("configFlywayAuthorsDb") FlywayAuthorProperties properties,
@Qualifier("dataSourceAuthorsDb") HikariDataSource dataSource) {
return Flyway.configure()
.dataSource(dataSource)
.locations(properties.getLocation())
.load();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayMySQLTwoDatabases\src\main\java\com\bookstore\config\ConfigureDataSources.java
| 2
|
请完成以下Java代码
|
public void updateNotifyRord(String id, int notifyTimes, String status) {
RpNotifyRecord notifyRecord = rpNotifyService.getNotifyRecordById(id);
notifyRecord.setNotifyTimes(notifyTimes);
notifyRecord.setStatus(status);
notifyRecord.setLastNotifyTime(new Date());
rpNotifyService.updateNotifyRecord(notifyRecord);
}
/**
* 创建商户通知日志记录.<br/>
*
* @param notifyId
* 通知记录ID.<br/>
* @param merchantNo
* 商户编号.<br/>
* @param merchantOrderNo
* 商户订单号.<br/>
* @param request
* 请求信息.<br/>
* @param response
* 返回信息.<br/>
|
* @param httpStatus
* 通知状态(HTTP状态).<br/>
* @return 创建结果
*/
public long saveNotifyRecordLogs(String notifyId, String merchantNo, String merchantOrderNo, String request, String response,
int httpStatus) {
RpNotifyRecordLog notifyRecordLog = new RpNotifyRecordLog();
notifyRecordLog.setHttpStatus(httpStatus);
notifyRecordLog.setMerchantNo(merchantNo);
notifyRecordLog.setMerchantOrderNo(merchantOrderNo);
notifyRecordLog.setNotifyId(notifyId);
notifyRecordLog.setRequest(request);
notifyRecordLog.setResponse(response);
notifyRecordLog.setCreateTime(new Date());
notifyRecordLog.setEditTime(new Date());
return rpNotifyService.createNotifyRecordLog(notifyRecordLog);
}
}
|
repos\roncoo-pay-master\roncoo-pay-app-notify\src\main\java\com\roncoo\pay\app\notify\core\NotifyPersist.java
| 1
|
请完成以下Java代码
|
public Optional<ShippableOrder> findShippableOrder(int orderId) {
if (!this.ordersDb.containsKey(orderId)) return Optional.empty();
PersistenceOrder orderRecord = this.ordersDb.get(orderId);
return Optional.of(
new ShippableOrder(orderRecord.orderId, orderRecord.orderItems
.stream().map(orderItem -> new PackageItem(orderItem.productId,
orderItem.itemWeight,
orderItem.quantity * orderItem.unitPrice)
).collect(Collectors.toList())));
}
public static InMemoryOrderStore provider() {
return instance;
}
public static class PersistenceOrder {
public int orderId;
public String paymentMethod;
public String address;
public List<OrderItem> orderItems;
public PersistenceOrder(int orderId, String paymentMethod, String address, List<OrderItem> orderItems) {
|
this.orderId = orderId;
this.paymentMethod = paymentMethod;
this.address = address;
this.orderItems = orderItems;
}
public static class OrderItem {
public int productId;
public float unitPrice;
public float itemWeight;
public int quantity;
public OrderItem(int productId, int quantity, float unitWeight, float unitPrice) {
this.itemWeight = unitWeight;
this.quantity = quantity;
this.unitPrice = unitPrice;
this.productId = productId;
}
}
}
}
|
repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-infrastructure\src\main\java\com\baeldung\dddcontexts\infrastructure\db\InMemoryOrderStore.java
| 1
|
请完成以下Java代码
|
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof String && obj.toString().trim().length() == 0) {
return true;
}
if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
return true;
}
if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
return true;
}
if (obj instanceof Map && ((Map) obj).isEmpty()) {
return true;
}
return false;
}
public static boolean isIdCard(String idCard) {
Pattern pattern = Pattern.compile("^(^\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$");
return pattern.matcher(idCard).matches();
}
/**
* 组织机构代码
*
* @param orgCode
* @return
*/
public static final boolean isOrgCode(String orgCode) {
String[] codeNo = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
String[] staVal = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35" };
Pattern pat = Pattern.compile("^[0-9A-Z]{8}-[0-9X]$");
Matcher matcher = pat.matcher(orgCode);
if (!matcher.matches()) {
return false;
}
Map map = new HashMap();
for (int i = 0; i < codeNo.length; i++) {
map.put(codeNo[i], staVal[i]);
}
final int[] wi = { 3, 7, 9, 10, 5, 8, 4, 2 };
String[] all = orgCode.split("-");
final char[] values = all[0].toCharArray();
|
int parity = 0;
for (int i = 0; i < values.length; i++) {
final String val = Character.toString(values[i]);
parity += wi[i] * Integer.parseInt(map.get(val).toString());
}
String cheak = (11 - parity % 11) == 10 ? "X" : Integer.toString((11 - parity % 11));
return cheak.equals(all[1]);
}
/**
* 参数长度校验
*
* @param propertyName
* @param property
* @param isRequire
* @param minLength
* @param maxLength
* @return
*/
public static String lengthValidate(String propertyName, String property, boolean isRequire, int minLength, int maxLength) {
int propertyLenght = property.length();
if (isRequire && propertyLenght == 0) {
return propertyName + "不能为空,"; // 校验不能为空
} else if (isRequire && minLength != 0 && propertyLenght < minLength) {
return propertyName + "不能少于" + minLength + "个字符,"; // 必填情况下校验最少长度
} else if (maxLength != 0 && propertyLenght > maxLength) {
return propertyName + "不能多于" + maxLength + "个字符,"; // 校验最大长度
} else {
return ""; // 校验通过则返回空字符串 .
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\utils\ValidateUtils.java
| 1
|
请完成以下Java代码
|
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
|
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationStrategy.java
| 1
|
请完成以下Java代码
|
public void destroy() {
cache.clear();
}
protected void ensureCapacityLimit() {
if (size() > getCapacity()) {
List<HalResourceCacheEntry> resources = new ArrayList<HalResourceCacheEntry>(cache.values());
NavigableSet<HalResourceCacheEntry> remainingResources = new TreeSet<HalResourceCacheEntry>(COMPARATOR);
// remove expired resources
for (HalResourceCacheEntry resource : resources) {
if (expired(resource)) {
remove(resource.getId());
}
else {
remainingResources.add(resource);
}
if (size() <= getCapacity()) {
// abort if capacity is reached
return;
}
|
}
// if still exceed capacity remove oldest
while (remainingResources.size() > capacity) {
HalResourceCacheEntry resourceToRemove = remainingResources.pollFirst();
if (resourceToRemove != null) {
remove(resourceToRemove.getId());
}
else {
break;
}
}
}
}
protected boolean expired(HalResourceCacheEntry entry) {
return entry.getCreateTime() + secondsToLive * 1000 < ClockUtil.getCurrentTime().getTime();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\DefaultHalResourceCache.java
| 1
|
请完成以下Java代码
|
public void infoJobExecutorDoesNotHandleBatchJobs(ProcessEngineConfigurationImpl config) {
logInfo("030",
"JobExecutor is configured for priority range {}-{}. Batch jobs will not be handled, because they are outside the priority range ({}).",
config.getJobExecutorPriorityRangeMin(),
config.getJobExecutorPriorityRangeMax(),
config.getBatchJobPriority());
}
public void debugFailedJobListenerSkipped(String jobId) {
logDebug("031", "Failed job listener skipped for job {} because it's been already re-acquired", jobId);
}
public ProcessEngineException jobExecutorPriorityRangeException(String reason) {
return new ProcessEngineException(exceptionMessage("031", "Invalid configuration for job executor priority range. Reason: {}", reason));
}
public void failedAcquisitionLocks(String processEngine, AcquiredJobs acquiredJobs) {
logDebug("033", "Jobs failed to Lock during Acquisition of jobs for the process engine '{}' : {}", processEngine,
acquiredJobs.getNumberOfJobsFailedToLock());
}
public void jobsToAcquire(String processEngine, int numJobsToAcquire) {
logDebug("034", "Attempting to acquire {} jobs for the process engine '{}'", numJobsToAcquire, processEngine);
}
public void rejectedJobExecutions(String processEngine, int numJobsRejected) {
logDebug("035", "Jobs execution rejections for the process engine '{}' : {}", processEngine, numJobsRejected);
}
public void availableJobExecutionThreads(String processEngine, int numAvailableThreads) {
logDebug("036", "Available job execution threads for the process engine '{}' : {}", processEngine,
numAvailableThreads);
}
public void currentJobExecutions(String processEngine, int numExecutions) {
|
logDebug("037", "Jobs currently in execution for the process engine '{}' : {}", processEngine, numExecutions);
}
public void numJobsInQueue(String processEngine, int numJobsInQueue, int maxQueueSize) {
logDebug("038",
"Jobs currently in queue to be executed for the process engine '{}' : {} (out of the max queue size : {})",
processEngine, numJobsInQueue, maxQueueSize);
}
public void availableThreadsCalculationError() {
logDebug("039", "Arithmetic exception occurred while computing remaining available thread count for logging.");
}
public void totalQueueCapacityCalculationError() {
logDebug("040", "Arithmetic exception occurred while computing total queue capacity for logging.");
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutorLogger.java
| 1
|
请完成以下Java代码
|
public I_M_HU_Trx_Line retrieveCounterpartTrxLine(final I_M_HU_Trx_Line trxLine)
{
final I_M_HU_Trx_Line trxLineCounterpart = trxLine.getParent_HU_Trx_Line();
if (trxLineCounterpart == null)
{
throw new AdempiereException("Counterpart transaction was not found for " + trxLine);
}
if (HUConstants.DEBUG_07277_saveHUTrxLine && trxLineCounterpart.getM_HU_Trx_Line_ID() <= 0)
{
throw new AdempiereException("Counterpart transaction was not saved for " + trxLine
+ "\nCounterpart trx: " + trxLineCounterpart);
}
return trxLineCounterpart;
}
@Override
public List<I_M_HU_Trx_Line> retrieveReferencingTrxLinesForHuId(@NonNull final HuId huId)
{
final IHUTrxQuery huTrxQuery = createHUTrxQuery();
|
huTrxQuery.setM_HU_ID(huId.getRepoId());
return retrieveTrxLines(Env.getCtx(), huTrxQuery, ITrx.TRXNAME_ThreadInherited);
}
@Override
@Deprecated
public List<I_M_HU_Trx_Line> retrieveReferencingTrxLinesForHU(final I_M_HU hu)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(hu);
final String trxName = InterfaceWrapperHelper.getTrxName(hu);
final IHUTrxQuery huTrxQuery = createHUTrxQuery();
huTrxQuery.setM_HU_ID(hu.getM_HU_ID());
return retrieveTrxLines(ctx, huTrxQuery, trxName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxDAO.java
| 1
|
请完成以下Java代码
|
public class StartPlanItemInstanceCmd extends AbstractNeedsPlanItemInstanceCmd {
protected Map<String, Object> childTaskVariables;
protected Map<String, Object> childTaskFormVariables;
protected String childTaskFormOutcome;
protected FormInfo childTaskFormInfo;
public StartPlanItemInstanceCmd(String planItemInstanceId) {
super(planItemInstanceId);
}
public StartPlanItemInstanceCmd(String planItemInstanceId, Map<String, Object> variables,
Map<String, Object> formVariables, String formOutcome, FormInfo formInfo,
Map<String, Object> localVariables,
Map<String, Object> transientVariables, Map<String, Object> childTaskVariables,
Map<String, Object> childTaskFormVariables, String childTaskFormOutcome, FormInfo childTaskFormInfo) {
super(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables);
|
this.childTaskVariables = childTaskVariables;
this.childTaskFormVariables = childTaskFormVariables;
this.childTaskFormOutcome = childTaskFormOutcome;
this.childTaskFormInfo = childTaskFormInfo;
}
@Override
protected void internalExecute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
if (!PlanItemInstanceState.ENABLED.equals(planItemInstanceEntity.getState())) {
throw new FlowableIllegalStateException("Can only enable a plan item instance which is in state ENABLED");
}
CommandContextUtil.getAgenda(commandContext).planStartPlanItemInstanceOperation(planItemInstanceEntity, null,
new ChildTaskActivityBehavior.VariableInfo(childTaskVariables, childTaskFormVariables, childTaskFormOutcome, childTaskFormInfo));
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\StartPlanItemInstanceCmd.java
| 1
|
请完成以下Java代码
|
public void setQtyOrdered (java.math.BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
/** Get Bestellte Menge.
@return Bestellte Menge
*/
@Override
public java.math.BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zusagbar.
@param QtyPromised Zusagbar */
@Override
public void setQtyPromised (java.math.BigDecimal QtyPromised)
|
{
set_Value (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate_Weekly.java
| 1
|
请完成以下Java代码
|
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final int id = evalCtx.getIdToFilterAsInt(-1);
if (id <= 0)
{
throw new IllegalStateException("No ID provided in " + evalCtx);
}
final LookupValue region = regionsByCountryId.values()
.stream()
.map(regions -> regions.getById(id))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
if (region != null)
{
return region;
}
final I_C_Region regionRecord = InterfaceWrapperHelper.create(Env.getCtx(), id, I_C_Region.class, ITrx.TRXNAME_None);
if (regionRecord == null)
{
return LOOKUPVALUE_NULL;
}
return createLookupValue(regionRecord);
}
@Override
public Builder newContextForFetchingList()
{
return LookupDataSourceContext.builder(CONTEXT_LookupTableName)
.setRequiredParameters(PARAMETERS);
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final int countryId = evalCtx.get_ValueAsInt(I_C_Location.COLUMNNAME_C_Country_ID, -1);
if (countryId <= 0)
{
return LookupValuesPage.EMPTY;
}
//
// Determine what we will filter
final String filter = evalCtx.getFilter();
final boolean matchAll;
final String filterUC;
final int limit;
final int offset = evalCtx.getOffset(0);
if (filter == LookupDataSourceContext.FILTER_Any)
{
matchAll = true;
filterUC = null; // N/A
limit = evalCtx.getLimit(Integer.MAX_VALUE);
}
else if (Check.isEmpty(filter, true))
{
return LookupValuesPage.EMPTY;
}
else
{
|
matchAll = false;
filterUC = filter.trim().toUpperCase();
limit = evalCtx.getLimit(100);
}
//
// Get, filter, return
return getRegionLookupValues(countryId)
.getValues()
.stream()
.filter(region -> matchAll || matchesFilter(region, filterUC))
.collect(LookupValuesList.collect())
.pageByOffsetAndLimit(offset, limit);
}
private boolean matchesFilter(final LookupValue region, final String filterUC)
{
final String displayName = region.getDisplayName();
if (Check.isEmpty(displayName))
{
return false;
}
final String displayNameUC = displayName.trim().toUpperCase();
return displayNameUC.contains(filterUC);
}
private LookupValuesList getRegionLookupValues(final int countryId)
{
return regionsByCountryId.getOrLoad(countryId, () -> retrieveRegionLookupValues(countryId));
}
private LookupValuesList retrieveRegionLookupValues(final int countryId)
{
return Services.get(ICountryDAO.class)
.retrieveRegions(Env.getCtx(), countryId)
.stream()
.map(this::createLookupValue)
.collect(LookupValuesList.collect());
}
private IntegerLookupValue createLookupValue(final I_C_Region regionRecord)
{
return IntegerLookupValue.of(regionRecord.getC_Region_ID(), regionRecord.getName());
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRegionLookupDescriptor.java
| 1
|
请完成以下Java代码
|
public void setIsAllowSeparateInvoicing (final boolean IsAllowSeparateInvoicing)
{
set_Value (COLUMNNAME_IsAllowSeparateInvoicing, IsAllowSeparateInvoicing);
}
@Override
public boolean isAllowSeparateInvoicing()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowSeparateInvoicing);
}
@Override
public void setIsHideWhenPrinting (final boolean IsHideWhenPrinting)
{
set_Value (COLUMNNAME_IsHideWhenPrinting, IsHideWhenPrinting);
}
@Override
public boolean isHideWhenPrinting()
{
return get_ValueAsBoolean(COLUMNNAME_IsHideWhenPrinting);
}
@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 setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
|
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_Schema_TemplateLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
JMSConfiguration artemisJmsConfiguration(ObjectProvider<JMSQueueConfiguration> queuesConfiguration,
ObjectProvider<TopicConfiguration> topicsConfiguration) {
JMSConfiguration configuration = new JMSConfigurationImpl();
configuration.getQueueConfigurations().addAll(queuesConfiguration.orderedStream().toList());
configuration.getTopicConfigurations().addAll(topicsConfiguration.orderedStream().toList());
addQueues(configuration, this.properties.getEmbedded().getQueues());
addTopics(configuration, this.properties.getEmbedded().getTopics());
return configuration;
}
private void addQueues(JMSConfiguration configuration, String[] queues) {
boolean persistent = this.properties.getEmbedded().isPersistent();
for (String queue : queues) {
JMSQueueConfigurationImpl jmsQueueConfiguration = new JMSQueueConfigurationImpl();
jmsQueueConfiguration.setName(queue);
jmsQueueConfiguration.setDurable(persistent);
|
jmsQueueConfiguration.setBindings("/queue/" + queue);
configuration.getQueueConfigurations().add(jmsQueueConfiguration);
}
}
private void addTopics(JMSConfiguration configuration, String[] topics) {
for (String topic : topics) {
TopicConfigurationImpl topicConfiguration = new TopicConfigurationImpl();
topicConfiguration.setName(topic);
topicConfiguration.setBindings("/topic/" + topic);
configuration.getTopicConfigurations().add(topicConfiguration);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisEmbeddedServerConfiguration.java
| 2
|
请完成以下Java代码
|
public String getStartUserId() {
return historicProcessInstance.getStartUserId();
}
@Override
public String getStartActivityId() {
return historicProcessInstance.getStartActivityId();
}
@Override
public String getDeleteReason() {
return historicProcessInstance.getDeleteReason();
}
@Override
public String getSuperProcessInstanceId() {
return historicProcessInstance.getSuperProcessInstanceId();
}
@Override
public String getTenantId() {
return historicProcessInstance.getTenantId();
}
|
@Override
public List<HistoricData> getHistoricData() {
return historicData;
}
public void addHistoricData(HistoricData historicEvent) {
historicData.add(historicEvent);
}
public void addHistoricData(Collection<? extends HistoricData> historicEvents) {
historicData.addAll(historicEvents);
}
public void orderHistoricData() {
Collections.sort(
historicData,
new Comparator<HistoricData>() {
@Override
public int compare(HistoricData data1, HistoricData data2) {
return data1.getTime().compareTo(data2.getTime());
}
}
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceHistoryLogImpl.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
|
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Collection<Location> getLocations() {
return locations;
}
public void setLocations(Collection<Location> locations) {
this.locations = locations;
}
}
|
repos\spring-boot-student-master\spring-boot-student-data-mongo\src\main\java\com\xiaolyuh\entity\Person.java
| 1
|
请完成以下Java代码
|
public List<ImageContent> buildImageContents(List<String> images) {
List<ImageContent> imageContents = new ArrayList<>();
for (String imageUrl : images) {
Matcher matcher = LLMConsts.WEB_PATTERN.matcher(imageUrl);
if (matcher.matches()) {
// 来源于网络
imageContents.add(ImageContent.from(imageUrl));
} else {
// 本地文件
String filePath = uploadpath + File.separator + imageUrl;
// 读取文件并转换为 base64 编码字符串
try {
Path path = Paths.get(filePath);
byte[] fileContent = Files.readAllBytes(path);
String base64Data = Base64.getEncoder().encodeToString(fileContent);
|
// 获取文件的 MIME 类型
String mimeType = Files.probeContentType(path);
// 构建 ImageContent 对象
imageContents.add(ImageContent.from(base64Data, mimeType));
} catch (IOException e) {
log.error("读取文件失败: " + filePath, e);
throw new RuntimeException("发送消息失败,读取文件异常:" + e.getMessage(), e);
}
}
}
return imageContents;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\handler\AIChatHandler.java
| 1
|
请完成以下Java代码
|
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* PaperFormat AD_Reference_ID=541073
* Reference name: DpdPaperFormat
*/
public static final int PAPERFORMAT_AD_Reference_ID=541073;
/** A6 = A6 */
public static final String PAPERFORMAT_A6 = "A6";
/** A5 = A5 */
public static final String PAPERFORMAT_A5 = "A5";
/** A4 = A4 */
public static final String PAPERFORMAT_A4 = "A4";
/** Set Papierformat.
@param PaperFormat Papierformat */
@Override
public void setPaperFormat (java.lang.String PaperFormat)
{
set_Value (COLUMNNAME_PaperFormat, PaperFormat);
}
/** Get Papierformat.
@return Papierformat */
@Override
public java.lang.String getPaperFormat ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaperFormat);
}
/** Set URL Api Shipment Service.
|
@param ShipmentServiceApiUrl URL Api Shipment Service */
@Override
public void setShipmentServiceApiUrl (java.lang.String ShipmentServiceApiUrl)
{
set_Value (COLUMNNAME_ShipmentServiceApiUrl, ShipmentServiceApiUrl);
}
/** Get URL Api Shipment Service.
@return URL Api Shipment Service */
@Override
public java.lang.String getShipmentServiceApiUrl ()
{
return (java.lang.String)get_Value(COLUMNNAME_ShipmentServiceApiUrl);
}
/** Set Shipper Product.
@param ShipperProduct Shipper Product */
@Override
public void setShipperProduct (java.lang.String ShipperProduct)
{
set_Value (COLUMNNAME_ShipperProduct, ShipperProduct);
}
/** Get Shipper Product.
@return Shipper Product */
@Override
public java.lang.String getShipperProduct ()
{
return (java.lang.String)get_Value(COLUMNNAME_ShipperProduct);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_Shipper_Config.java
| 1
|
请完成以下Java代码
|
public RequiredFactor getRequiredFactor() {
return this.requiredFactor;
}
/**
* True if not {@link #isMissing()} but was older than the
* {@link RequiredFactor#getValidDuration()}.
* @return true if expired, else false
*/
public boolean isExpired() {
return this.reason == Reason.EXPIRED;
}
/**
* True if no {@link FactorGrantedAuthority#getAuthority()} on the
* {@link org.springframework.security.core.Authentication} matched
* {@link RequiredFactor#getAuthority()}.
* @return true if missing, else false.
*/
public boolean isMissing() {
return this.reason == Reason.MISSING;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
RequiredFactorError that = (RequiredFactorError) o;
return Objects.equals(this.requiredFactor, that.requiredFactor) && this.reason == that.reason;
}
@Override
public int hashCode() {
return Objects.hash(this.requiredFactor, this.reason);
}
@Override
public String toString() {
return "RequiredFactorError{" + "requiredFactor=" + this.requiredFactor + ", reason=" + this.reason + '}';
}
public static RequiredFactorError createMissing(RequiredFactor requiredFactor) {
return new RequiredFactorError(requiredFactor, Reason.MISSING);
}
public static RequiredFactorError createExpired(RequiredFactor requiredFactor) {
return new RequiredFactorError(requiredFactor, Reason.EXPIRED);
}
|
/**
* The reason that the error occurred.
*
* @author Rob Winch
* @since 7.0
*/
private enum Reason {
/**
* The authority was missing.
* @see #isMissing()
*/
MISSING,
/**
* The authority was considered expired.
* @see #isExpired()
*/
EXPIRED
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\RequiredFactorError.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void add(User user) {
userDaoImpl.create(user);
}
@Override
public void remove(User user) {
}
@Override
public void update(User user) {
}
@Override
|
public List<Tweet> fetchTweets(User user) {
return tweetDaoImpl.fetchTweets(user.getEmail());
}
@Override
public User findByUserName(String userName) {
return null;
}
@Override
public User findByEmail(String email) {
return null;
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\repositoryvsdaopattern\UserRepositoryImpl.java
| 2
|
请完成以下Spring Boot application配置
|
spring:
application:
name: admin-client
boot:
admin:
client:
url: http://localhost:8769
server:
port: 8768
management:
endpoints:
web:
exp
|
osure:
include: '*'
endpoint:
health:
show-details: ALWAYS
|
repos\SpringBootLearning-master (1)\springboot-admin\admin-client\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public File downReconciliationFile(String interfaceCode, Date billDate) {
// 支付渠道编码
if (StringUtil.isEmpty(interfaceCode)) {
LOG.info("支付渠道编码为空");
return null;
}
// 对账单下载
return this.downFile(interfaceCode, billDate);
}
/**
* 下载文件
*
* @param interfaceCode
* 接口编码
* @param tradeGainCheckFileTime
* 业务对账文件的获取时间
*/
private File downFile(String interfaceCode, Date billDate) {
LOG.info("银行渠道编号[" + interfaceCode + "],进入下载业务对账文件操作>>>");
try {
|
File file = null;
int downloadTrytimes = 0;
// 默认尝试三次
while (file == null && downloadTrytimes < DOWNLOAD_TRY_TIMES) {
try {
downloadTrytimes++;
// 使用工厂模式
file = reconciliationFactory.fileDown(interfaceCode, billDate);
} catch (Exception e) {
LOG.error("下载账单文件失败", e);
Thread.sleep(10000);
}
}
return file;
} catch (Exception e) {
LOG.error("下载微信账单文件失败", e);
}
return null;
}
}
|
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\biz\ReconciliationFileDownBiz.java
| 1
|
请完成以下Java代码
|
protected void removeConsumer() {
flowableConsumer = null;
}
@Override
public boolean isSingleton() {
return true;
}
public void setIdentityService(IdentityService identityService) {
this.identityService = identityService;
}
public void setRuntimeService(RuntimeService runtimeService) {
this.runtimeService = runtimeService;
}
public void setRepositoryService(RepositoryService repositoryService) {
this.repositoryService = repositoryService;
}
public void setManagementService(ManagementService managementService) {
this.managementService = managementService;
}
public boolean isCopyVariablesToProperties() {
return copyVariablesToProperties;
}
public void setCopyVariablesToProperties(boolean copyVariablesToProperties) {
this.copyVariablesToProperties = copyVariablesToProperties;
}
public boolean isCopyCamelBodyToBody() {
return copyCamelBodyToBody;
}
public void setCopyCamelBodyToBody(boolean copyCamelBodyToBody) {
this.copyCamelBodyToBody = copyCamelBodyToBody;
}
public boolean isCopyVariablesToBodyAsMap() {
return copyVariablesToBodyAsMap;
}
public void setCopyVariablesToBodyAsMap(boolean copyVariablesToBodyAsMap) {
this.copyVariablesToBodyAsMap = copyVariablesToBodyAsMap;
}
public String getCopyVariablesFromProperties() {
return copyVariablesFromProperties;
}
public void setCopyVariablesFromProperties(String copyVariablesFromProperties) {
this.copyVariablesFromProperties = copyVariablesFromProperties;
}
|
public String getCopyVariablesFromHeader() {
return copyVariablesFromHeader;
}
public void setCopyVariablesFromHeader(String copyVariablesFromHeader) {
this.copyVariablesFromHeader = copyVariablesFromHeader;
}
public boolean isCopyCamelBodyToBodyAsString() {
return copyCamelBodyToBodyAsString;
}
public void setCopyCamelBodyToBodyAsString(boolean copyCamelBodyToBodyAsString) {
this.copyCamelBodyToBodyAsString = copyCamelBodyToBodyAsString;
}
public boolean isSetProcessInitiator() {
return StringUtils.isNotEmpty(getProcessInitiatorHeaderName());
}
public Map<String, Object> getReturnVarMap() {
return returnVarMap;
}
public void setReturnVarMap(Map<String, Object> returnVarMap) {
this.returnVarMap = returnVarMap;
}
public String getProcessInitiatorHeaderName() {
return processInitiatorHeaderName;
}
public void setProcessInitiatorHeaderName(String processInitiatorHeaderName) {
this.processInitiatorHeaderName = processInitiatorHeaderName;
}
@Override
public boolean isLenientProperties() {
return true;
}
public long getTimeout() {
return timeout;
}
public int getTimeResolution() {
return timeResolution;
}
}
|
repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableEndpoint.java
| 1
|
请完成以下Java代码
|
public boolean update(final I_C_Invoice_Candidate ic)
{
ic.setApprovalForInvoicing(true);
return MODEL_UPDATED;
}
});
//
// Refresh rows, because they were updated
if (countUpdated > 0)
{
gridTab.dataRefreshAll();
}
//
// Inform the user
|
clientUI.info(windowNo,
"Updated", // AD_Message/title
"#" + countUpdated // message
);
}
private final IQueryBuilder<I_C_Invoice_Candidate> retrieveInvoiceCandidatesToApproveQuery()
{
return gridTab.createQueryBuilder(I_C_Invoice_Candidate.class)
.addOnlyActiveRecordsFilter()
.addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_Processed, true) // not processed
.addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_ApprovalForInvoicing, true) // not already approved
;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\callout\IC_ApproveForInvoicing_Action.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class NettyClientHandlerInitializer extends ChannelInitializer<Channel> {
/**
* 心跳超时时间
*/
private static final Integer READ_TIMEOUT_SECONDS = 60;
@Autowired
private MessageDispatcher messageDispatcher;
@Autowired
private NettyClientHandler nettyClientHandler;
@Override
protected void initChannel(Channel ch) {
|
ch.pipeline()
// 空闲检测
.addLast(new IdleStateHandler(READ_TIMEOUT_SECONDS, 0, 0))
.addLast(new ReadTimeoutHandler(3 * READ_TIMEOUT_SECONDS))
// 编码器
.addLast(new InvocationEncoder())
// 解码器
.addLast(new InvocationDecoder())
// 消息分发器
.addLast(messageDispatcher)
// 客户端处理器
.addLast(nettyClientHandler)
;
}
}
|
repos\SpringBoot-Labs-master\lab-67\lab-67-netty-demo\lab-67-netty-demo-client\src\main\java\cn\iocoder\springboot\lab67\nettyclientdemo\client\handler\NettyClientHandlerInitializer.java
| 2
|
请完成以下Java代码
|
public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());
UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
if(!passwordEncoder.matches(oldPass, user.getPassword())){
throw new BadRequestException("修改失败,旧密码错误");
}
if(passwordEncoder.matches(newPass, user.getPassword())){
throw new BadRequestException("新密码不能与旧密码相同");
}
userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
return new ResponseEntity<>(HttpStatus.OK);
}
@ApiOperation("重置密码")
@PutMapping(value = "/resetPwd")
public ResponseEntity<Object> resetPwd(@RequestBody Set<Long> ids) {
String pwd = passwordEncoder.encode("123456");
userService.resetPwd(ids, pwd);
return new ResponseEntity<>(HttpStatus.OK);
}
@ApiOperation("修改头像")
@PostMapping(value = "/updateAvatar")
public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){
return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
}
|
@Log("修改邮箱")
@ApiOperation("修改邮箱")
@PostMapping(value = "/updateEmail/{code}")
public ResponseEntity<Object> updateUserEmail(@PathVariable String code,@RequestBody User user) throws Exception {
String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword());
UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername());
if(!passwordEncoder.matches(password, userDto.getPassword())){
throw new BadRequestException("密码错误");
}
verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
userService.updateEmail(userDto.getUsername(),user.getEmail());
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误
* @param resources /
*/
private void checkLevel(User resources) {
Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
Integer optLevel = roleService.findByRoles(resources.getRoles());
if (currentLevel > optLevel) {
throw new BadRequestException("角色权限不足");
}
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\UserController.java
| 1
|
请完成以下Java代码
|
public String toDisplayableQRCode()
{
return id.getDisplayableSuffix();
}
public PrintableQRCode toPrintableQRCode()
{
return PrintableQRCode.builder()
.topText(extractPrintableTopText(this))
.bottomText(extractPrintableBottomText(this))
.qrCode(HUQRCodeJsonConverter.toGlobalQRCode(this).getAsString())
.build();
}
public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode)
{
return HUQRCodeJsonConverter.isTypeMatching(globalQRCode);
}
private static String extractPrintableTopText(final HUQRCode qrCode)
{
final StringBuilder result = new StringBuilder();
final HUQRCodeProductInfo product = qrCode.getProduct().orElse(null);
if (product != null)
{
result.append(product.getCode());
result.append(" - ");
result.append(product.getName());
}
for (final HUQRCodeAttribute attribute : qrCode.getAttributes())
{
final String displayValue = StringUtils.trimBlankToNull(attribute.getValueRendered());
if (displayValue != null)
{
if (result.length() > 0)
{
result.append(", ");
}
result.append(displayValue);
}
}
return result.toString();
}
@Override
public Optional<BigDecimal> getWeightInKg()
{
return getAttribute(Weightables.ATTR_WeightNet)
.map(HUQRCodeAttribute::getValueAsBigDecimal)
.filter(weight -> weight.signum() > 0);
}
@Override
public Optional<LocalDate> getBestBeforeDate()
{
return getAttribute(AttributeConstants.ATTR_BestBeforeDate).map(HUQRCodeAttribute::getValueAsLocalDate);
}
@Override
|
public Optional<LocalDate> getProductionDate()
{
return getAttribute(AttributeConstants.ProductionDate).map(HUQRCodeAttribute::getValueAsLocalDate);
}
@Override
public Optional<String> getLotNumber()
{
return getAttribute(AttributeConstants.ATTR_LotNumber).map(HUQRCodeAttribute::getValue);
}
private Optional<HUQRCodeAttribute> getAttribute(@NonNull final AttributeCode attributeCode)
{
return attributes.stream().filter(attribute -> AttributeCode.equals(attribute.getCode(), attributeCode)).findFirst();
}
private static String extractPrintableBottomText(final HUQRCode qrCode)
{
return qrCode.getPackingInfo().getHuUnitType().getShortDisplayName() + " ..." + qrCode.toDisplayableQRCode();
}
public Optional<HUQRCodeProductInfo> getProduct() {return Optional.ofNullable(product);}
@JsonIgnore
public Optional<ProductId> getProductId() {return getProduct().map(HUQRCodeProductInfo::getId);}
@JsonIgnore
public ProductId getProductIdNotNull() {return getProductId().orElseThrow(() -> new AdempiereException("QR Code does not contain product information: " + this));}
public HuPackingInstructionsId getPackingInstructionsId() {return getPackingInfo().getPackingInstructionsId();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCode.java
| 1
|
请完成以下Java代码
|
public static class WebuiViewToOpen
{
@JsonProperty("viewId")
String viewId;
@JsonProperty("profileId")
String profileId;
@JsonProperty("target")
ViewOpenTarget target;
@lombok.Builder
@JsonCreator
private WebuiViewToOpen(
@JsonProperty("viewId") @NonNull final String viewId,
@JsonProperty("profileId") @Nullable final String profileId,
@JsonProperty("target") @NonNull final ViewOpenTarget target)
{
this.viewId = viewId;
this.profileId = profileId;
this.target = target;
}
public static WebuiViewToOpen modalOverlay(@NonNull final String viewId)
{
return builder().viewId(viewId).target(ViewOpenTarget.ModalOverlay).build();
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@lombok.Value
public static class DisplayQRCode
{
@JsonProperty("code")
String code;
@lombok.Builder
@JsonCreator
private DisplayQRCode(@JsonProperty("code") @NonNull final String code)
{
this.code = code;
}
|
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@lombok.Value
@lombok.Builder
public static class WebuiNewRecord
{
/**
* If this string is used as field value
* then the frontend will try to open the new record modal window to populate that field.
* <p>
* Used mainly to trigger new BPartner.
*/
public static final String FIELD_VALUE_NEW = "NEW";
@NonNull String windowId;
/**
* Field values to be set by frontend, after the NEW record is created
*/
@NonNull @Singular Map<String, String> fieldValues;
public enum TargetTab
{
SAME_TAB, NEW_TAB,
}
@NonNull @Builder.Default TargetTab targetTab = TargetTab.SAME_TAB;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessExecutionResult.java
| 1
|
请完成以下Java代码
|
public class SendTaskParseHandler extends AbstractActivityBpmnParseHandler<SendTask> {
private static final Logger logger = LoggerFactory.getLogger(SendTaskParseHandler.class);
public Class<? extends BaseElement> getHandledType() {
return SendTask.class;
}
protected void executeParse(BpmnParse bpmnParse, SendTask sendTask) {
if (StringUtils.isNotEmpty(sendTask.getType())) {
if (sendTask.getType().equalsIgnoreCase("mail")) {
sendTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createMailActivityBehavior(sendTask));
} else if (sendTask.getType().equalsIgnoreCase("mule")) {
sendTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createMuleActivityBehavior(sendTask));
} else if (sendTask.getType().equalsIgnoreCase("camel")) {
|
sendTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createCamelActivityBehavior(sendTask));
}
} else if (
ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE.equalsIgnoreCase(sendTask.getImplementationType()) &&
StringUtils.isNotEmpty(sendTask.getOperationRef())
) {
WebServiceActivityBehavior webServiceActivityBehavior = bpmnParse
.getActivityBehaviorFactory()
.createWebServiceActivityBehavior(sendTask);
sendTask.setBehavior(webServiceActivityBehavior);
} else {
logger.warn("One of the attributes 'type' or 'operation' is mandatory on sendTask " + sendTask.getId());
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SendTaskParseHandler.java
| 1
|
请完成以下Java代码
|
public boolean isGraphicalNotationDefined() {
return hasGraphicalNotation();
}
@Override
public void setHasGraphicalNotation(boolean hasGraphicalNotation) {
this.isGraphicalNotationDefined = hasGraphicalNotation;
}
@Override
public String getDiagramResourceName() {
return diagramResourceName;
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCategory() {
return category;
|
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String getDecisionType() {
return decisionType;
}
@Override
public void setDecisionType(String decisionType) {
this.decisionType = decisionType;
}
@Override
public String toString() {
return "DecisionEntity[" + id + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DecisionEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Article getArticleById(int articleId) {
return entityManager.find(Article.class, articleId);
}
@SuppressWarnings("unchecked")
@Override
public List<Article> getAllArticles() {
String hql = "FROM Article as atcl ORDER BY atcl.articleId";
return (List<Article>) entityManager.createQuery(hql).getResultList();
}
@Override
public void addArticle(Article article) {
entityManager.persist(article);
}
@Override
public void updateArticle(Article article) {
Article artcl = getArticleById(article.getArticleId());
artcl.setTitle(article.getTitle());
artcl.setCategory(article.getCategory());
|
entityManager.flush();
}
@Override
public void deleteArticle(int articleId) {
entityManager.remove(getArticleById(articleId));
}
@Override
public boolean articleExists(String title, String category) {
String hql = "FROM Article as atcl WHERE atcl.title = ? and atcl.category = ?";
int count = entityManager.createQuery(hql)
.setParameter(0, title)
.setParameter(1, category).getResultList().size();
return count > 0;
}
}
|
repos\SpringBootBucket-master\springboot-hibernate\src\main\java\com\xncoding\pos\dao\repository\impl\ArticleDAO.java
| 2
|
请完成以下Java代码
|
public void setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
@Override
public void 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 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 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_I_BPartner.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getIsAutoSett() {
return isAutoSett;
}
public void setIsAutoSett(String isAutoSett) {
this.isAutoSett = isAutoSett == null ? null : isAutoSett.trim();
}
public String getPayKey() {
return payKey;
}
public void setPayKey(String payKey) {
this.payKey = payKey;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode == null ? null : productCode.trim();
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName == null ? null : productName.trim();
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
|
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public Integer getRiskDay() {
return riskDay;
}
public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay;
}
public String getAuditStatusDesc() {
return PublicEnum.getEnum(this.getAuditStatus()).getDesc();
}
public String getFundIntoTypeDesc() {
return FundInfoTypeEnum.getEnum(this.getFundIntoType()).getDesc();
}
public String getSecurityRating() {
return securityRating;
}
public void setSecurityRating(String securityRating) {
this.securityRating = securityRating;
}
public String getMerchantServerIp() {
return merchantServerIp;
}
public void setMerchantServerIp(String merchantServerIp) {
this.merchantServerIp = merchantServerIp;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserPayConfig.java
| 2
|
请完成以下Java代码
|
public boolean save (String whereClause, String trxName)
{
m_whereClause = whereClause;
return save(trxName);
} // save
/**
* Save LOB.
* see also org.compiere.session.ServerBean#updateLOB
* @param trxName trx name
* @return true if saved
*/
public boolean save(String trxName)
{
final boolean[] success = new boolean[] { false };
Services.get(ITrxManager.class).run(trxName, new TrxRunnable()
{
@Override
public void run(String localTrxName) throws Exception
{
success[0] = save0(localTrxName);
}
});
return success[0];
}
private final boolean save0 (String trxName)
{
if (m_value == null
|| (!(m_value instanceof String || m_value instanceof byte[]))
|| (m_value instanceof String && m_value.toString().length() == 0)
|| (m_value instanceof byte[] && ((byte[])m_value).length == 0)
)
{
StringBuilder sql = new StringBuilder("UPDATE ")
.append(m_tableName)
.append(" SET ").append(m_columnName)
.append("=null WHERE ").append(m_whereClause);
int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), trxName);
log.debug("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value);
if (no == 0)
log.warn("[" + trxName + "] - not updated - " + sql);
return true;
}
final String sql;
final Object[] sqlParams;
if(MigrationScriptFileLoggerHolder.isEnabled())
{
final String valueBase64enc = BaseEncoding.base64().encode((byte[])m_value);
sql = "UPDATE " + m_tableName + " SET " + m_columnName + "=DECODE(" + DB.TO_STRING(valueBase64enc) + ", 'base64') WHERE " + m_whereClause;
sqlParams = new Object[] {};
}
else
{
sql = "UPDATE " + m_tableName + " SET " + m_columnName + "=? WHERE " + m_whereClause;
sqlParams = new Object[]{m_value};
|
}
PreparedStatement pstmt = null;
boolean success = true;
try
{
pstmt = DB.prepareStatement(sql, trxName);
DB.setParameters(pstmt, sqlParams);
final int no = pstmt.executeUpdate();
if (no != 1)
{
log.warn("[" + trxName + "] - Not updated #" + no + " - " + sql);
success = false;
}
}
catch (Throwable e)
{
log.error("[" + trxName + "] - " + sql, e);
success = false;
}
finally
{
DB.close(pstmt);
pstmt = null;
}
return success;
} // save
/**
* String Representation
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("PO_LOB[");
sb.append(m_tableName).append(".").append(m_columnName)
.append(",DisplayType=").append(m_displayType)
.append("]");
return sb.toString();
} // toString
} // PO_LOB
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\PO_LOB.java
| 1
|
请完成以下Java代码
|
public <T, ET extends T> TypedSqlQuery<ET> createUUIDSelectionQuery(
@NonNull final IContextAware ctx,
@NonNull final Class<ET> clazz,
@NonNull final String querySelectionUUID)
{
final String tableName = InterfaceWrapperHelper.getTableName(clazz);
final POInfo poInfo = POInfo.getPOInfo(tableName);
final String keyColumnName = poInfo.getKeyColumnName();
final String keyColumnNameFQ = tableName + "." + keyColumnName;
//
// Build the query used to retrieve models by querying the selection.
// NOTE: we are using LEFT OUTER JOIN instead of INNER JOIN because
// * methods like hasNext() are comparing the rowsFetched counter with rowsCount to detect if we reached the end of the selection (optimization).
// * POBufferedIterator is using LIMIT/OFFSET clause for fetching the next page and eliminating rows from here would fuck the paging if one record was deleted in meantime.
// So we decided to load everything here, and let the hasNext() method to deal with the case when the record is really missing.
final String selectionSqlFrom = "(SELECT "
+ I_T_Query_Selection.COLUMNNAME_UUID + " as ZZ_UUID"
+ ", " + I_T_Query_Selection.COLUMNNAME_Record_ID + " as ZZ_Record_ID"
+ ", " + I_T_Query_Selection.COLUMNNAME_Line + " as " + SELECTION_LINE_ALIAS
|
+ " FROM " + I_T_Query_Selection.Table_Name
+ ") s "
+ "\n LEFT OUTER JOIN " + tableName + " ON (" + keyColumnNameFQ + "=s.ZZ_Record_ID)";
final String selectionWhereClause = "s.ZZ_UUID=?";
final String selectionOrderBy = "s." + SELECTION_LINE_ALIAS;
return new TypedSqlQuery<>(
ctx.getCtx(),
clazz,
selectionWhereClause,
ctx.getTrxName())
.setParameters(querySelectionUUID)
.setSqlFrom(selectionSqlFrom)
.setOrderBy(selectionOrderBy);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\QuerySelectionHelper.java
| 1
|
请完成以下Spring Boot application配置
|
elasticjob.reg-center.server-lists=localhost:2181
elasticjob.reg-center.namespace=didispace
elasticjob.jobs.my-simple-job.elastic-job-class=com.didispace.chapter72.MySimpleJob
elasticjob.jobs.m
|
y-simple-job.cron=0/5 * * * * ?
elasticjob.jobs.my-simple-job.sharding-total-count=1
|
repos\SpringBoot-Learning-master\2.x\chapter7-2\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public Integer generateRandomWithThreadLocalRandom() {
int randomWithThreadLocalRandom = ThreadLocalRandom.current()
.nextInt();
return randomWithThreadLocalRandom;
}
public Integer generateRandomWithThreadLocalRandomInARange(int min, int max) {
int randomWithThreadLocalRandomInARange = ThreadLocalRandom.current()
.nextInt(min, max);
return randomWithThreadLocalRandomInARange;
}
public Integer generateRandomWithThreadLocalRandomFromZero(int max) {
int randomWithThreadLocalRandomFromZero = ThreadLocalRandom.current()
.nextInt(max);
return randomWithThreadLocalRandomFromZero;
}
public Integer generateRandomWithSplittableRandom(int min, int max) {
SplittableRandom splittableRandom = new SplittableRandom();
int randomWithSplittableRandom = splittableRandom.nextInt(min, max);
return randomWithSplittableRandom;
}
public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) {
SplittableRandom splittableRandom = new SplittableRandom();
IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max);
return limitedIntStreamWithinARangeWithSplittableRandom;
}
public Integer generateRandomWithSecureRandom() {
SecureRandom secureRandom = new SecureRandom();
int randomWithSecureRandom = secureRandom.nextInt();
return randomWithSecureRandom;
}
|
public Integer generateRandomWithSecureRandomWithinARange(int min, int max) {
SecureRandom secureRandom = new SecureRandom();
int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min;
return randomWithSecureRandomWithinARange;
}
public Integer generateRandomWithRandomDataGenerator(int min, int max) {
RandomDataGenerator randomDataGenerator = new RandomDataGenerator();
int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max);
return randomWithRandomDataGenerator;
}
public Integer generateRandomWithXoRoShiRo128PlusRandom(int min, int max) {
XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom();
int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max - min) + min;
return randomWithXoRoShiRo128PlusRandom;
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-3\src\main\java\com\baeldung\randomnumbers\RandomNumbersGenerator.java
| 1
|
请完成以下Java代码
|
public static final <T> boolean addVEditorButtonUsingBorderLayout(final Class<T> editorClass, final Container editorContainer, final JButton editorButton)
{
final VEditorDialogButtonAlign buttonAlign = getFromUIManager(editorClass);
boolean added = false;
if (buttonAlign == VEditorDialogButtonAlign.Hide || buttonAlign == null)
{
// don't add it
}
else if (buttonAlign == VEditorDialogButtonAlign.Left)
{
editorContainer.add(editorButton, BorderLayout.WEST);
added = true;
}
else if (buttonAlign == VEditorDialogButtonAlign.Right)
{
editorContainer.add(editorButton, BorderLayout.EAST);
added = true;
}
return added;
}
/**
* Creates the {@link UIDefaults} key for given <code>editorClass</code>.
*
* @param editorClass
* @return UI defaults key
*/
public static final <T> String createUIKey(final Class<T> editorClass)
{
return createUIKey(editorClass.getSimpleName());
}
/**
* Creates the {@link UIDefaults} key for given <code>editorClassKey</code>.
*
* @param editorClass
* @return UI defaults key
*/
public static final String createUIKey(final String editorClassKey)
{
final String uiKey = editorClassKey + ".DialogButtonAlign";
return uiKey;
}
/** @return {@link VEditorDialogButtonAlign} value of given <code>editorClass</code> from {@link UIManager}. */
private static final <T> VEditorDialogButtonAlign getFromUIManager(final Class<T> editorClass)
{
|
//
// Editor property
{
final String alignUIKey = createUIKey(editorClass);
final VEditorDialogButtonAlign align = (VEditorDialogButtonAlign)UIManager.get(alignUIKey);
if (align != null)
{
return align;
}
}
//
// Default property
{
final VEditorDialogButtonAlign align = (VEditorDialogButtonAlign)UIManager.get(DEFAULT_EditorUI);
if (align != null)
{
return align;
}
}
//
// Fallback to default value
return DEFAULT_Value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\VEditorDialogButtonAlign.java
| 1
|
请完成以下Java代码
|
public class C_ValidCombination_UpdateDescriptionForAll extends JavaProcess
{
private final transient IAccountBL accountBL = Services.get(IAccountBL.class);
@Override
protected void prepare()
{
// nothing
}
@Override
protected String doIt() throws Exception
{
final Iterator<I_C_ValidCombination> accounts = retriveAccounts();
int countAll = 0;
int countOK = 0;
while (accounts.hasNext())
{
final I_C_ValidCombination account = accounts.next();
final boolean updated = updateValueDescription(account);
countAll++;
if (updated)
{
countOK++;
}
}
return "@Updated@/@Total@ #" + countOK + "/" + countAll;
}
private Iterator<I_C_ValidCombination> retriveAccounts()
{
final IQueryBuilder<I_C_ValidCombination> queryBuilder = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_ValidCombination.class, getCtx(), ITrx.TRXNAME_None)
.addOnlyContextClient()
.addOnlyActiveRecordsFilter();
queryBuilder.orderBy()
.addColumn(I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID);
final Iterator<I_C_ValidCombination> accounts = queryBuilder.create()
.iterate(I_C_ValidCombination.class);
return accounts;
}
/**
|
*
* @param account
* @return true if updated; false if got errors (which will be logged)
*/
private boolean updateValueDescription(I_C_ValidCombination account)
{
DB.saveConstraints();
try
{
DB.getConstraints().addAllowedTrxNamePrefix(ITrx.TRXNAME_PREFIX_LOCAL);
accountBL.setValueDescription(account);
InterfaceWrapperHelper.save(account);
return true;
}
catch (Exception e)
{
addLog(account.getCombination() + ": " + e.getLocalizedMessage());
log.warn(e.getLocalizedMessage(), e);
}
finally
{
DB.restoreConstraints();
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\C_ValidCombination_UpdateDescriptionForAll.java
| 1
|
请完成以下Java代码
|
public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
|
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BfsDataType.java
| 1
|
请完成以下Java代码
|
public KeyValues getLowCardinalityKeyValues(DataLoaderObservationContext context) {
return KeyValues.of(errorType(context), loaderType(context), outcome(context));
}
@Override
public KeyValues getHighCardinalityKeyValues(DataLoaderObservationContext context) {
return KeyValues.of(loaderSize(context));
}
protected KeyValue errorType(DataLoaderObservationContext context) {
if (context.getError() != null) {
return KeyValue.of(DataLoaderLowCardinalityKeyNames.ERROR_TYPE, context.getError().getClass().getSimpleName());
}
return ERROR_TYPE_NONE;
}
protected KeyValue loaderType(DataLoaderObservationContext context) {
if (StringUtils.hasText(context.getDataLoader().getName())) {
return KeyValue.of(DataLoaderLowCardinalityKeyNames.LOADER_NAME, context.getDataLoader().getName());
|
}
return LOADER_TYPE_UNKNOWN;
}
protected KeyValue outcome(DataLoaderObservationContext context) {
if (context.getError() != null) {
return OUTCOME_ERROR;
}
return OUTCOME_SUCCESS;
}
protected KeyValue loaderSize(DataLoaderObservationContext context) {
return KeyValue.of(DataLoaderHighCardinalityKeyNames.LOADER_SIZE, String.valueOf(context.getResult().size()));
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DefaultDataLoaderObservationConvention.java
| 1
|
请完成以下Java代码
|
protected HistoryCleanupJobHandlerConfiguration resolveJobHandlerConfiguration(HistoryCleanupContext context) {
HistoryCleanupJobHandlerConfiguration config = new HistoryCleanupJobHandlerConfiguration();
config.setImmediatelyDue(context.isImmediatelyDue());
config.setMinuteFrom(context.getMinuteFrom());
config.setMinuteTo(context.getMinuteTo());
return config;
}
@Override
protected int resolveRetries(HistoryCleanupContext context) {
return context.getMaxRetries();
}
@Override
public Date resolveDueDate(HistoryCleanupContext context) {
return resolveDueDate(context.isImmediatelyDue());
}
private Date resolveDueDate(boolean isImmediatelyDue) {
CommandContext commandContext = Context.getCommandContext();
if (isImmediatelyDue) {
return ClockUtil.getCurrentTime();
} else {
final BatchWindow currentOrNextBatchWindow = commandContext.getProcessEngineConfiguration().getBatchWindowManager()
.getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration());
|
if (currentOrNextBatchWindow != null) {
return currentOrNextBatchWindow.getStart();
} else {
return null;
}
}
}
public ParameterValueProvider getJobPriorityProvider() {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
long historyCleanupJobPriority = configuration.getHistoryCleanupJobPriority();
return new ConstantValueProvider(historyCleanupJobPriority);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobDeclaration.java
| 1
|
请完成以下Java代码
|
public String getFieldName()
{
return fieldName;
}
@Override
public DocumentFieldWidgetType getWidgetType()
{
return widgetType;
}
@Override
public boolean isValueSet()
{
return valueSet;
}
|
@Override
public Object getValue()
{
return value;
}
public MutableDocumentFieldChangedEvent setValue(final Object value)
{
this.value = value;
valueSet = true;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\MutableDocumentFieldChangedEvent.java
| 1
|
请完成以下Java代码
|
private DefaultMutableTreeNode assertNoCycles(final ProductId productId)
{
final DefaultMutableTreeNode productNode = new DefaultMutableTreeNode(productId);
final IProductBOMDAO productBOMDAO = Services.get(IProductBOMDAO.class);
final List<I_PP_Product_BOMLine> productBOMLines = productBOMDAO.retrieveBOMLinesByComponentIdInTrx(productId);
boolean first = true;
for (final I_PP_Product_BOMLine productBOMLine : productBOMLines)
{
// Don't navigate the Co/ByProduct lines (gh480)
if (isByOrCoProduct(productBOMLine))
{
continue;
}
// If not the first bom line at this level
if (!first)
{
clearSeenProducts();
markProductAsSeen(productId);
}
first = false;
final DefaultMutableTreeNode bomNode = assertNoCycles(productBOMLine);
if (bomNode != null)
{
productNode.add(bomNode);
}
}
return productNode;
}
private static boolean isByOrCoProduct(final I_PP_Product_BOMLine bomLine)
{
final BOMComponentType componentType = BOMComponentType.ofCode(Objects.requireNonNull(bomLine.getComponentType()));
return componentType.isByOrCoProduct();
}
@Nullable
private DefaultMutableTreeNode assertNoCycles(final I_PP_Product_BOMLine bomLine)
{
final I_PP_Product_BOM bom = bomLine.getPP_Product_BOM();
if (!bom.isActive())
{
return null;
}
// Check Child = Parent error
final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID());
final ProductId parentProductId = ProductId.ofRepoId(bom.getM_Product_ID());
|
if (productId.equals(parentProductId))
{
throw new BOMCycleException(bom, productId);
}
// Check BOM Loop Error
if (!markProductAsSeen(parentProductId))
{
throw new BOMCycleException(bom, parentProductId);
}
return assertNoCycles(parentProductId);
}
private void clearSeenProducts()
{
seenProductIds.clear();
}
private boolean markProductAsSeen(final ProductId productId)
{
return seenProductIds.add(productId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMCycleDetection.java
| 1
|
请完成以下Java代码
|
public void onMsg(TbContext ctx, TbMsg msg) {
try {
String relationType = config.isCheckAllKeys() ?
allKeysData(msg) && allKeysMetadata(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE :
atLeastOneData(msg) || atLeastOneMetadata(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE;
ctx.tellNext(msg, relationType);
} catch (Exception e) {
ctx.tellFailure(msg, e);
}
}
private boolean allKeysData(TbMsg msg) {
if (!messageNamesList.isEmpty()) {
Map<String, String> dataMap = dataToMap(msg);
return processAllKeys(messageNamesList, dataMap);
}
return true;
}
private boolean allKeysMetadata(TbMsg msg) {
if (!metadataNamesList.isEmpty()) {
Map<String, String> metadataMap = metadataToMap(msg);
return processAllKeys(metadataNamesList, metadataMap);
}
return true;
}
private boolean atLeastOneData(TbMsg msg) {
if (!messageNamesList.isEmpty()) {
Map<String, String> dataMap = dataToMap(msg);
return processAtLeastOne(messageNamesList, dataMap);
}
return false;
}
|
private boolean atLeastOneMetadata(TbMsg msg) {
if (!metadataNamesList.isEmpty()) {
Map<String, String> metadataMap = metadataToMap(msg);
return processAtLeastOne(metadataNamesList, metadataMap);
}
return false;
}
private boolean processAllKeys(List<String> data, Map<String, String> map) {
for (String field : data) {
if (!map.containsKey(field)) {
return false;
}
}
return true;
}
private boolean processAtLeastOne(List<String> data, Map<String, String> map) {
for (String field : data) {
if (map.containsKey(field)) {
return true;
}
}
return false;
}
private Map<String, String> metadataToMap(TbMsg msg) {
return msg.getMetaData().getData();
}
@SuppressWarnings("unchecked")
private Map<String, String> dataToMap(TbMsg msg) {
return (Map<String, String>) gson.fromJson(msg.getData(), Map.class);
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\filter\TbCheckMessageNode.java
| 1
|
请完成以下Java代码
|
public String getErrorPath(){
return errPath;
}
// public static void main(String[] args) throws IOException {
// File file = ResourceUtils.getFile("classpath:spider.jpg");
// File temfile = new File("C:\\Users\\bd2\\Desktop\\sb.png");
// img2txt(file);
// }
public File save(byte[] bytes,String name) throws IOException {
File newFile = new File(FILE_PATH + File.separator + name);
if(!newFile.exists()){
newFile.createNewFile();
}
IOUtils.write(bytes,new FileOutputStream(newFile));
return img2txt(newFile);
}
private File img2txt(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
BufferedImage scaled = getScaledImg(image);
char[][] array = getImageMatrix(scaled);
StringBuffer sb = new StringBuffer();
for (char[] cs : array) {
for (char c : cs) {
sb.append(c);
// System.out.print(c);
}
sb.append("\r\n");
// System.out.println();
}
String outName = file.getAbsolutePath() + ".txt";
File outFile = new File(outName);
IOUtils.write(sb.toString(), new FileOutputStream(outFile));
return outFile;
}
private static char[][] getImageMatrix(BufferedImage img) {
int w = img.getWidth(), h = img.getHeight();
char[][] rst = new char[w][h];
for (int i = 0; i < w; i++)
for (int j = 0; j < h; j++) {
int rgb = img.getRGB(i, j);
// 注意溢出
|
int r = Integer.valueOf(Integer.toBinaryString(rgb).substring(0, 8), 2);
int g = (rgb & 0xff00) >> 8;
int b = rgb & 0xff;
int gray = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b);
// 把int gray转换成char
int len = toChar.length();
int base = 256 / len + 1;
int charIdx = gray / base;
rst[j][i] = toChar.charAt(charIdx); // 注意i和j的处理顺序,如果是rst[j][i],图像是逆时针90度打印的,仔细体会下getRGB(i,j)这
}
return rst;
}
private static BufferedImage getScaledImg(BufferedImage image) {
BufferedImage rst = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
rst.getGraphics().drawImage(image, 0, 0, width, height, null);
return rst;
}
}
|
repos\spring-boot-quick-master\quick-img2txt\src\main\java\com\quick\img2txt\Img2TxtService.java
| 1
|
请完成以下Java代码
|
public static String sendPostWithOkHttp(String targetUrl) throws IOException {
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.get("application/json; charset=utf-8");
String jsonInput = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
RequestBody body = RequestBody.create(jsonInput, JSON);
Request request = new Request.Builder()
.url(targetUrl)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
|
public static String sendPostWithSpringWebClient(String targetUrl) {
WebClient webClient = WebClient.builder()
.baseUrl(targetUrl)
.defaultHeader(HttpHeaders.CONTENT_TYPE, org.springframework.http.MediaType.APPLICATION_JSON_VALUE)
.build();
String jsonInput = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
return webClient.post()
.bodyValue(jsonInput)
.retrieve()
.bodyToMono(String.class)
.block(); // Blocking for synchronous execution
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking-6\src\main\java\com\baeldung\curltohttprequest\CurlToHttpRequest.java
| 1
|
请完成以下Java代码
|
public static byte[] encodeInteger(BigInteger bigInt) {
if (bigInt == null) {
throw new NullPointerException("encodeInteger called with null parameter");
}
return encodeBase64(toIntegerBytes(bigInt), false);
}
/**
* Returns a byte-array representation of a <code>BigInteger</code> without sign bit.
*
* @param bigInt
* <code>BigInteger</code> to be converted
* @return a byte array representation of the BigInteger parameter
*/
static byte[] toIntegerBytes(BigInteger bigInt) {
int bitlen = bigInt.bitLength();
// round bitlen
bitlen = ((bitlen + 7) >> 3) << 3;
byte[] bigBytes = bigInt.toByteArray();
if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
return bigBytes;
}
// set up params for copying everything but sign bit
int startSrc = 0;
|
int len = bigBytes.length;
// if bigInt is exactly byte-aligned, just skip signbit in copy
if ((bigInt.bitLength() % 8) == 0) {
startSrc = 1;
len--;
}
int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
byte[] resizedBytes = new byte[bitlen / 8];
System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
return resizedBytes;
}
/**
* Resets this Base64 object to its initial newly constructed state.
*/
private void reset() {
buffer = null;
pos = 0;
readPos = 0;
currentLinePos = 0;
modulus = 0;
eof = false;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\digest\_apacheCommonsCodec\Base64.java
| 1
|
请完成以下Java代码
|
public void notifyExternalSystemsAboutPrintJob(@NonNull final PrintingClientRequest request)
{
externalSystemMessageSender.send(toPrintingClientExternalSystemRequest(request));
}
@NonNull
private JsonExternalSystemRequest toPrintingClientExternalSystemRequest(@NonNull final PrintingClientRequest request)
{
final I_ExternalSystem_Config_PrintingClient childConfigRecord = queryBL.createQueryBuilder(I_ExternalSystem_Config_PrintingClient.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(X_ExternalSystem_Config_PrintingClient.COLUMNNAME_ExternalSystem_Config_ID, request.getExternalSystemParentConfigId())
.create()
.firstOnlyNotNull(I_ExternalSystem_Config_PrintingClient.class);
final Map<String, String> parameters = new HashMap<>();
parameters.put(ExternalSystemConstants.PARAM_TARGET_DIRECTORY, childConfigRecord.getTarget_Directory());
|
parameters.put(ExternalSystemConstants.PARAM_PRINTING_QUEUE_ID, String.valueOf(request.getPrintingQueueId()));
return JsonExternalSystemRequest.builder()
.externalSystemConfigId(JsonMetasfreshId.of(childConfigRecord.getExternalSystem_Config_ID()))
.externalSystemName(JsonExternalSystemName.of(ExternalSystemType.PrintClient.getValue()))
.parameters(parameters)
.orgCode(orgDAO.getById(OrgId.ofRepoId(request.getOrgId())).getValue())
.command(EXTERNAL_SYSTEM_COMMAND_PRINTING_CLIENT)
.adPInstanceId(request.getPInstanceId() != null ? JsonMetasfreshId.of(request.getPInstanceId()) : null)
.traceId(externalSystemConfigService.getTraceId())
.externalSystemChildConfigValue(childConfigRecord.getExternalSystemValue())
.writeAuditEndpoint(null)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\printingclient\PrintingClientExternalSystemService.java
| 1
|
请完成以下Java代码
|
private int getWindowNo()
{
if (_windowNo == null)
{
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
_windowNo = _nextWindowNo.incrementAndGet();
}
else
{
_windowNo = parentDocument.getWindowNo();
}
}
return _windowNo;
}
private boolean isWritable()
{
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
return isNewDocument();
}
else
{
return parentDocument.isWritable();
}
}
|
private ReentrantReadWriteLock createLock()
{
// don't create locks for any other entity which is not window
final DocumentEntityDescriptor entityDescriptor = getEntityDescriptor();
if (entityDescriptor.getDocumentType() != DocumentType.Window)
{
return null;
}
//
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
return new ReentrantReadWriteLock();
}
else
{
// don't create lock for included documents
return null;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\Document.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OtlpTracingProperties {
/**
* URL to the OTel collector's HTTP API.
*/
private @Nullable String endpoint;
/**
* Call timeout for the OTel Collector to process an exported batch of data. This
* timeout spans the entire call: resolving DNS, connecting, writing the request body,
* server processing, and reading the response body. If the call requires redirects or
* retries all must complete within one timeout period.
*/
private Duration timeout = Duration.ofSeconds(10);
/**
* Connect timeout for the OTel collector connection.
*/
private Duration connectTimeout = Duration.ofSeconds(10);
/**
* Transport used to send the spans.
*/
private Transport transport = Transport.HTTP;
/**
* Method used to compress the payload.
*/
private Compression compression = Compression.NONE;
/**
* Custom HTTP headers you want to pass to the collector, for example auth headers.
*/
private Map<String, String> headers = new HashMap<>();
public @Nullable String getEndpoint() {
return this.endpoint;
}
public void setEndpoint(@Nullable String endpoint) {
this.endpoint = endpoint;
}
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
|
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Transport getTransport() {
return this.transport;
}
public void setTransport(Transport transport) {
this.transport = transport;
}
public Compression getCompression() {
return this.compression;
}
public void setCompression(Compression compression) {
this.compression = compression;
}
public Map<String, String> getHeaders() {
return this.headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public enum Compression {
/**
* Gzip compression.
*/
GZIP,
/**
* No compression.
*/
NONE
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\otlp\OtlpTracingProperties.java
| 2
|
请完成以下Java代码
|
private Flux<?> filterMultiValue(Publisher<?> publisher, EvaluationContext ctx, ExpressionAttribute attribute) {
return Flux.from(publisher)
.doOnNext((result) -> setFilterObject(ctx, result))
.flatMap((result) -> postFilter(ctx, result, attribute));
}
private void setFilterObject(EvaluationContext ctx, Object result) {
TypedValue rootObject = ctx.getRootObject();
Assert.notNull(rootObject, "rootObject cannot be null");
MethodSecurityExpressionOperations methodOperations = (MethodSecurityExpressionOperations) rootObject
.getValue();
Assert.notNull(methodOperations, "methodOperations cannot be null");
methodOperations.setFilterObject(result);
}
private Mono<?> postFilter(EvaluationContext ctx, Object result, ExpressionAttribute attribute) {
return ReactiveExpressionUtils.evaluateAsBoolean(attribute.getExpression(), ctx)
.flatMap((granted) -> granted ? Mono.just(result) : Mono.empty());
}
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
|
@Override
public Advice getAdvice() {
return this;
}
@Override
public boolean isPerInstance() {
return true;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PostFilterAuthorizationReactiveMethodInterceptor.java
| 1
|
请完成以下Java代码
|
class CredProtectAuthenticationExtensionsClientInputSerializer
extends StdSerializer<CredProtectAuthenticationExtensionsClientInput> {
protected CredProtectAuthenticationExtensionsClientInputSerializer() {
super(CredProtectAuthenticationExtensionsClientInput.class);
}
@Override
public void serialize(CredProtectAuthenticationExtensionsClientInput input, JsonGenerator jgen,
SerializationContext ctxt) throws JacksonException {
CredProtectAuthenticationExtensionsClientInput.CredProtect credProtect = input.getInput();
String policy = toString(credProtect.getCredProtectionPolicy());
jgen.writePOJOProperty("credentialProtectionPolicy", policy);
jgen.writePOJOProperty("enforceCredentialProtectionPolicy", credProtect.isEnforceCredentialProtectionPolicy());
}
|
private static String toString(CredProtectAuthenticationExtensionsClientInput.CredProtect.ProtectionPolicy policy) {
switch (policy) {
case USER_VERIFICATION_OPTIONAL:
return "userVerificationOptional";
case USER_VERIFICATION_OPTIONAL_WITH_CREDENTIAL_ID_LIST:
return "userVerificationOptionalWithCredentialIdList";
case USER_VERIFICATION_REQUIRED:
return "userVerificationRequired";
default:
throw new IllegalArgumentException("Unsupported ProtectionPolicy " + policy);
}
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\jackson\CredProtectAuthenticationExtensionsClientInputSerializer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Filter createCSRFHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME);
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
cookie = new Cookie(CSRF_COOKIE_NAME, token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
|
}
/**
* Angular sends the CSRF token in a custom header named "X-XSRF-TOKEN"
* rather than the default "X-CSRF-TOKEN" that Spring security expects.
* Hence we are now telling Spring security to expect the token in the
* "X-XSRF-TOKEN" header.<br><br>
*
* This customization is added to the <code>csrf()</code> filter.
*
* @return
*/
private CsrfTokenRepository getCSRFTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName(CSRF_ANGULAR_HEADER_NAME);
return repository;
}
}
|
repos\spring-boot-microservices-master\api-gateway\src\main\java\com\rohitghatol\microservice\gateway\config\OAuthConfiguration.java
| 2
|
请完成以下Java代码
|
Mono<Void> remove(String sessionId) {
return this.sessionRedisOperations.opsForZSet().remove(getExpirationsKey(), sessionId).then();
}
/**
* Retrieve the session ids that have the expiration time less than the value passed
* in {@code expiredBefore}.
* @param expiredBefore the expiration time
* @return a {@link Flux} that emits the session ids
*/
Flux<String> retrieveExpiredSessions(Instant expiredBefore) {
Range<Double> range = Range.closed(0D, (double) expiredBefore.toEpochMilli());
Limit limit = Limit.limit().count(this.retrieveCount);
return this.sessionRedisOperations.opsForZSet()
.reverseRangeByScore(getExpirationsKey(), range, limit)
.cast(String.class);
|
}
private String getExpirationsKey() {
return this.namespace + "sessions:expirations";
}
/**
* Set the namespace for the keys used by this class.
* @param namespace the namespace
*/
void setNamespace(String namespace) {
Assert.hasText(namespace, "namespace cannot be null or empty");
this.namespace = namespace;
}
}
|
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\SortedSetReactiveRedisSessionExpirationStore.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String home(Locale locale, Model model) {
return "redirect:/cars";
}
static {
carList.add(new Car("Honda", "Civic"));
carList.add(new Car("Toyota", "Camry"));
carList.add(new Car("Nissan", "Altima"));
}
@RequestMapping(value = "/cars", method = RequestMethod.GET)
public String init(@ModelAttribute("model") ModelMap model) {
model.addAttribute("carList", carList);
return "index";
}
|
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCar(@ModelAttribute("car") Car car) {
if (null != car && null != car.getMake() && null != car.getModel() && !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
carList.add(car);
}
return "redirect:/cars";
}
@RequestMapping(value = "/commons", method = RequestMethod.GET)
public String showCommonsPage(Model model) {
model.addAttribute("statuses", Arrays.asList("200 OK", "404 Not Found", "500 Internal Server Error"));
model.addAttribute("lastChar", new LastCharMethod());
model.addAttribute("random", new Random());
model.addAttribute("statics", new DefaultObjectWrapperBuilder(new Version("2.3.28")).build().getStaticModels());
return "commons";
}
}
|
repos\tutorials-master\spring-web-modules\spring-freemarker\src\main\java\com\baeldung\freemarker\controller\SpringController.java
| 2
|
请完成以下Java代码
|
public void updateSuspensionState(ProcessDefinitionSuspensionStateDto dto) {
if (dto.getProcessDefinitionId() != null) {
String message = "Only processDefinitionKey can be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
try {
dto.updateSuspensionState(getProcessEngine());
} catch (IllegalArgumentException e) {
String message = String.format("Could not update the suspension state of Process Definitions due to: %s", e.getMessage()) ;
throw new InvalidRequestException(Status.BAD_REQUEST, e, message);
}
}
@Override
public void deleteProcessDefinitionsByKey(String processDefinitionKey, boolean cascade, boolean skipCustomListeners, boolean skipIoMappings) {
RepositoryService repositoryService = getProcessEngine().getRepositoryService();
DeleteProcessDefinitionsBuilder builder = repositoryService.deleteProcessDefinitions()
.byKey(processDefinitionKey);
deleteProcessDefinitions(builder, cascade, skipCustomListeners, skipIoMappings);
}
@Override
public void deleteProcessDefinitionsByKeyAndTenantId(String processDefinitionKey, boolean cascade, boolean skipCustomListeners, boolean skipIoMappings, String tenantId) {
RepositoryService repositoryService = getProcessEngine().getRepositoryService();
|
DeleteProcessDefinitionsBuilder builder = repositoryService.deleteProcessDefinitions()
.byKey(processDefinitionKey)
.withTenantId(tenantId);
deleteProcessDefinitions(builder, cascade, skipCustomListeners, skipIoMappings);
}
protected void deleteProcessDefinitions(DeleteProcessDefinitionsBuilder builder, boolean cascade, boolean skipCustomListeners, boolean skipIoMappings) {
if (skipCustomListeners) {
builder = builder.skipCustomListeners();
}
if (cascade) {
builder = builder.cascade();
}
if (skipIoMappings) {
builder = builder.skipIoMappings();
}
try {
builder.delete();
} catch (NotFoundException e) { // rewrite status code from bad request (400) to not found (404)
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\ProcessDefinitionRestServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getDOCUMENTID() {
return documentid;
}
/**
* Sets the value of the documentid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDOCUMENTID(String value) {
this.documentid = value;
}
/**
* Gets the value of the linenumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLINENUMBER() {
return linenumber;
}
/**
* Sets the value of the linenumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLINENUMBER(String value) {
this.linenumber = value;
}
/**
* Gets the value of the datequal property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATEQUAL() {
return datequal;
}
/**
* Sets the value of the datequal property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATEQUAL(String value) {
this.datequal = value;
}
/**
* Gets the value of the datefrom property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATEFROM() {
|
return datefrom;
}
/**
* Sets the value of the datefrom property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATEFROM(String value) {
this.datefrom = value;
}
/**
* Gets the value of the dateto property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATETO() {
return dateto;
}
/**
* Sets the value of the dateto property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATETO(String value) {
this.dateto = value;
}
/**
* Gets the value of the days property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDAYS() {
return days;
}
/**
* Sets the value of the days property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDAYS(String value) {
this.days = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DDATE1.java
| 2
|
请完成以下Java代码
|
protected void createHUDocumentsFromTypedModel(final HUDocumentsCollector documentsCollector, final I_M_InOut inout)
{
// 05089: HU Editor shall be displayed only for Receipts
if (inout.isSOTrx())
{
throw new AdempiereException("@M_InOut_ID@ @IsSOTrx@=@Y@");
}
final String docStatus = inout.getDocStatus();
final List<String> expectedDocStatuses = Arrays.asList(
X_M_InOut.DOCSTATUS_Completed,
X_M_InOut.DOCSTATUS_Reversed
);
if (!expectedDocStatuses.contains(docStatus))
{
throw new AdempiereException("@Invalid@ @M_InOut_ID@ @DocStatus@: "
+ "Actual: " + docStatus
+ ", Expected: " + expectedDocStatuses
+ ")");
}
final List<IHUDocumentLine> docLines = createHUDocumentLines(documentsCollector, inout);
final IHUDocument doc = new MInOutHUDocument(inout, docLines);
documentsCollector.getHUDocuments().add(doc);
}
private List<IHUDocumentLine> createHUDocumentLines(final HUDocumentsCollector documentsCollector, final I_M_InOut inOut)
{
final List<I_M_InOutLine> ioLines = Services.get(IInOutDAO.class).retrieveLines(inOut);
if (ioLines.isEmpty())
{
throw AdempiereException.newWithTranslatableMessage("@NoLines@ (@M_InOut_ID@: " + inOut.getDocumentNo() + ")");
}
final List<IHUDocumentLine> sourceLines = new ArrayList<>(ioLines.size());
for (final I_M_InOutLine ioLine : ioLines)
|
{
//
// Create HU Document Line
final List<I_M_Transaction> mtrxs = Services.get(IMTransactionDAO.class).retrieveReferenced(ioLine);
for (final I_M_Transaction mtrx : mtrxs)
{
final MInOutLineHUDocumentLine sourceLine = new MInOutLineHUDocumentLine(ioLine, mtrx);
sourceLines.add(sourceLine);
}
//
// Create Target Qty
final Capacity targetCapacity = Capacity.createCapacity(
ioLine.getMovementQty(), // qty
ProductId.ofRepoId(ioLine.getM_Product_ID()),
uomDAO.getById(ioLine.getC_UOM_ID()),
false // allowNegativeCapacity
);
documentsCollector.getTargetCapacities().add(targetCapacity);
}
return sourceLines;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\MInOutHUDocumentFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WebSecurityConfig {
@Autowired
private CsrfTokenRepository jwtCsrfTokenRepository;
@Autowired
private SecretService secretService;
// ordered so we can use binary search below
private final String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" };
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
.csrf()
.csrfTokenRepository(jwtCsrfTokenRepository)
.ignoringAntMatchers(ignoreCsrfAntMatchers)
.and()
.authorizeRequests()
.antMatchers("/**")
.permitAll();
return http.build();
}
private class JwtCsrfValidatorFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// NOTE: A real implementation should have a nonce cache so the token cannot be reused
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
if (
// only care if it's a POST
"POST".equals(request.getMethod()) &&
|
// ignore if the request path is in our list
Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 &&
// make sure we have a token
token != null) {
// CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired
try {
Jwts.parser()
.setSigningKeyResolver(secretService.getSigningKeyResolver()).build()
.parseClaimsJws(token.getToken());
} catch (JwtException e) {
// most likely an ExpiredJwtException, but this will handle any
request.setAttribute("exception", e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
RequestDispatcher dispatcher = request.getRequestDispatcher("expired-jwt");
dispatcher.forward(request, response);
}
}
filterChain.doFilter(request, response);
}
}
}
|
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\config\WebSecurityConfig.java
| 2
|
请完成以下Java代码
|
public Builder code(String code) {
this.code = code;
return this;
}
/**
* Sets the error code.
* @param errorCode the error code
* @return the {@link Builder}
*/
public Builder errorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
/**
* Sets the error description.
* @param errorDescription the error description
* @return the {@link Builder}
*/
public Builder errorDescription(String errorDescription) {
this.errorDescription = errorDescription;
return this;
}
/**
* Sets the error uri.
* @param errorUri the error uri
* @return the {@link Builder}
|
*/
public Builder errorUri(String errorUri) {
this.errorUri = errorUri;
return this;
}
/**
* Builds a new {@link OAuth2AuthorizationResponse}.
* @return a {@link OAuth2AuthorizationResponse}
*/
public OAuth2AuthorizationResponse build() {
if (StringUtils.hasText(this.code) && StringUtils.hasText(this.errorCode)) {
throw new IllegalArgumentException("code and errorCode cannot both be set");
}
Assert.hasText(this.redirectUri, "redirectUri cannot be empty");
OAuth2AuthorizationResponse authorizationResponse = new OAuth2AuthorizationResponse();
authorizationResponse.redirectUri = this.redirectUri;
authorizationResponse.state = this.state;
if (StringUtils.hasText(this.code)) {
authorizationResponse.code = this.code;
}
else {
authorizationResponse.error = new OAuth2Error(this.errorCode, this.errorDescription, this.errorUri);
}
return authorizationResponse;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AuthorizationResponse.java
| 1
|
请完成以下Java代码
|
private static DESKeySpec getDesKeySpec(String source) throws Exception {
if (source == null || source.isEmpty()) {
return null;
}
String strKey = "Passw0rd";
return new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8));
}
/**
* 对称加密
*/
public static String desEncrypt(String source) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = getDesKeySpec(source);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, IV);
return byte2hex(cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))).toUpperCase();
}
/**
* 对称解密
*/
public static String desDecrypt(String source) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
byte[] src = hex2byte(source.getBytes(StandardCharsets.UTF_8));
DESKeySpec desKeySpec = getDesKeySpec(source);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
cipher.init(Cipher.DECRYPT_MODE, secretKey, IV);
byte[] retByte = cipher.doFinal(src);
return new String(retByte);
|
}
private static String byte2hex(byte[] inStr) {
String stmp;
StringBuilder out = new StringBuilder(inStr.length * 2);
for (byte b : inStr) {
stmp = Integer.toHexString(b & 0xFF);
if (stmp.length() == 1) {
out.append("0").append(stmp);
} else {
out.append(stmp);
}
}
return out.toString();
}
private static byte[] hex2byte(byte[] b) {
int size = 2;
if ((b.length % size) != 0) {
throw new IllegalArgumentException("长度不是偶数");
}
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += size) {
String item = new String(b, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\EncryptUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public FormLoginConfigurer<H> failureForwardUrl(String forwardUrl) {
failureHandler(new ForwardAuthenticationFailureHandler(forwardUrl));
return this;
}
/**
* Forward Authentication Success Handler
* @param forwardUrl the target URL in case of success
* @return the {@link FormLoginConfigurer} for additional customization
*/
public FormLoginConfigurer<H> successForwardUrl(String forwardUrl) {
successHandler(new ForwardAuthenticationSuccessHandler(forwardUrl));
return this;
}
@Override
public void init(H http) {
super.init(http);
initDefaultLoginFilter(http);
ExceptionHandlingConfigurer<H> exceptions = http.getConfigurer(ExceptionHandlingConfigurer.class);
if (exceptions != null) {
AuthenticationEntryPoint entryPoint = getAuthenticationEntryPoint();
RequestMatcher requestMatcher = getAuthenticationEntryPointMatcher(http);
exceptions.defaultDeniedHandlerForMissingAuthority((ep) -> ep.addEntryPointFor(entryPoint, requestMatcher),
FactorGrantedAuthority.PASSWORD_AUTHORITY);
}
}
@Override
protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
return getRequestMatcherBuilder().matcher(HttpMethod.POST, loginProcessingUrl);
}
/**
* Gets the HTTP parameter that is used to submit the username.
* @return the HTTP parameter that is used to submit the username
*/
private String getUsernameParameter() {
return getAuthenticationFilter().getUsernameParameter();
|
}
/**
* Gets the HTTP parameter that is used to submit the password.
* @return the HTTP parameter that is used to submit the password
*/
private String getPasswordParameter() {
return getAuthenticationFilter().getPasswordParameter();
}
/**
* If available, initializes the {@link DefaultLoginPageGeneratingFilter} shared
* object.
* @param http the {@link HttpSecurityBuilder} to use
*/
private void initDefaultLoginFilter(H http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !isCustomLoginPage()) {
loginPageGeneratingFilter.setFormLoginEnabled(true);
loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter());
loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter());
loginPageGeneratingFilter.setLoginPageUrl(getLoginPage());
loginPageGeneratingFilter.setFailureUrl(getFailureUrl());
loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl());
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\FormLoginConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void customize(ServerBuilder builder) {
builder.withJsonConverter(
new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter(this.objectMapper));
}
}
static class Jackson2XmlMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final ObjectMapper objectMapper;
Jackson2XmlMessageConvertersCustomizer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void customize(ClientBuilder builder) {
builder.withXmlConverter(new org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter(
this.objectMapper));
}
@Override
public void customize(ServerBuilder builder) {
builder.withXmlConverter(new org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter(
|
this.objectMapper));
}
}
private static class PreferJackson2OrJacksonUnavailableCondition extends AnyNestedCondition {
PreferJackson2OrJacksonUnavailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jackson2")
static class Jackson2Preferred {
}
@ConditionalOnMissingBean(JacksonJsonHttpMessageConvertersCustomizer.class)
static class JacksonUnavailable {
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\Jackson2HttpMessageConvertersConfiguration.java
| 2
|
请完成以下Java代码
|
final class Digester {
private final String algorithm;
private int iterations;
/**
* Create a new Digester.
* @param algorithm the digest algorithm; for example, "SHA-1" or "SHA-256".
* @param iterations the number of times to apply the digest algorithm to the input
*/
Digester(String algorithm, int iterations) {
// eagerly validate the algorithm
createDigest(algorithm);
this.algorithm = algorithm;
setIterations(iterations);
}
byte[] digest(byte[] value) {
MessageDigest messageDigest = createDigest(this.algorithm);
for (int i = 0; i < this.iterations; i++) {
value = messageDigest.digest(value);
}
return value;
|
}
void setIterations(int iterations) {
if (iterations <= 0) {
throw new IllegalArgumentException("Iterations value must be greater than zero");
}
this.iterations = iterations;
}
private static MessageDigest createDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("No such hashing algorithm", ex);
}
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\Digester.java
| 1
|
请完成以下Java代码
|
private ProductsToPickRow toRow_IssueComponentsToPickingOrder(final PickingPlanLine planLine)
{
final SourceDocumentInfo sourceDocumentInfo = planLine.getSourceDocumentInfo();
final ProductInfo productInfo = productInfos.getByProductId(planLine.getProductId());
final IssueToBOMLine issueToBOMLine = Objects.requireNonNull(planLine.getIssueToBOMLine());
final ProductsToPickRowId rowId = ProductsToPickRowId.builder()
.productId(productInfo.getProductId())
.shipmentScheduleId(sourceDocumentInfo.getScheduleId().getShipmentScheduleId())
.issueToOrderBOMLineId(issueToBOMLine.getIssueToOrderBOMLineId())
.build();
return ProductsToPickRow.builder()
.rowId(rowId)
.rowType(ProductsToPickRowType.ISSUE_COMPONENTS_TO_PICKING_ORDER)
.shipperId(sourceDocumentInfo.getShipperId())
//
.productInfo(productInfo)
.qty(planLine.getQty())
//
.build()
.withUpdatesFromPickingCandidateIfNotNull(sourceDocumentInfo.getExistingPickingCandidate());
}
private ProductsToPickRow toRow_Unallocable(@NonNull final PickingPlanLine planLine)
{
final SourceDocumentInfo sourceDocumentInfo = planLine.getSourceDocumentInfo();
final ProductInfo productInfo = productInfos.getByProductId(planLine.getProductId());
final ProductsToPickRowId rowId = ProductsToPickRowId.builder()
.productId(productInfo.getProductId())
|
.shipmentScheduleId(sourceDocumentInfo.getScheduleId().getShipmentScheduleId())
.build();
return ProductsToPickRow.builder()
.rowId(rowId)
.rowType(ProductsToPickRowType.UNALLOCABLE)
.shipperId(sourceDocumentInfo.getShipperId())
//
.productInfo(productInfo)
.qty(planLine.getQty())
//
.build()
.withUpdatesFromPickingCandidateIfNotNull(sourceDocumentInfo.getExistingPickingCandidate());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\factory\ProductsToPickRowsDataFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ExplainedOptional<HUInfo> resolvePickFromHUQRCode(@NonNull final PickingJobLine line)
{
return resolvedHUInfos.computeIfAbsent(
line.getId(),
k -> huService.resolvePickFromHUQRCode(
getHUQRCode(),
line.getProductId(),
getCustomerId(line),
getWarehouseId(line)
));
}
@NonNull
private BPartnerId getCustomerId(@NonNull final PickingJobLine line)
{
return CoalesceUtil.coalesceSuppliersNotNull(
line::getCustomerId,
() -> getJob().getCustomerId()
);
}
@NonNull
private WarehouseId getWarehouseId(@NonNull final PickingJobLine line)
|
{
final ShipmentScheduleId shipmentScheduleId = line.getScheduleId().getShipmentScheduleId();
return shipmentSchedules.getById(shipmentScheduleId).getWarehouseId();
}
private void log(@NonNull String message)
{
log(null, message);
}
private void log(@Nullable final PickingJobLine line, @NonNull String message)
{
final StringBuilder sb = new StringBuilder();
if (line != null)
{
sb.append("Line: ").append(line.getId().getRepoId()).append(" - ");
}
sb.append(message);
String messageFinal = sb.toString();
logger.debug(messageFinal);
logs.add(messageFinal);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\get_next_eligible_line\GetNextEligibleLineToPackCommand.java
| 2
|
请完成以下Java代码
|
private void addCustomValidationExample() {
var nameField = new TextField("Name");
var emailField = new TextField("Email");
var phoneField = new TextField("Phone");
var saveButton = new Button("Save");
var binder = new Binder<>(Contact.class);
binder.forField(nameField)
.asRequired()
.bind(Contact::getName, Contact::setName);
binder.forField(emailField)
.withValidator(email -> email.contains("@"), "Not a valid email address")
.bind(Contact::getEmail, Contact::setEmail);
binder.forField(phoneField)
.withValidator(phone -> phone.matches("\\d{3}-\\d{3}-\\d{4}"), "Not a valid phone number")
.bind(Contact::getPhone, Contact::setPhone);
|
var contact = new Contact("John Doe", "john@doe.com", "123-456-7890");
binder.setBean(contact);
saveButton.addClickListener(e -> {
if (binder.validate().isOk()) {
Notification.show("Saved " + contact);
}
});
add(new VerticalLayout(
new H2("Custom Validation Example"),
nameField,
emailField,
phoneField,
saveButton
));
}
}
|
repos\tutorials-master\vaadin\src\main\java\com\baeldung\introduction\FormView.java
| 1
|
请完成以下Java代码
|
static class OrderLineComparator implements Comparator<Integer> {
Map<Integer, MOrderLine> index;
OrderLineComparator(Map<Integer, MOrderLine> olIndex) {
index = olIndex;
}
@Override
public int compare(Integer ol1, Integer ol2) {
return index.get(ol1).getPriceActual().compareTo(index.get(ol2).getPriceActual());
}
}
// metas: begin
static class OrderLinePromotionCandidate {
BigDecimal qty;
MOrderLine orderLine;
I_M_PromotionReward promotionReward;
}
private static void addDiscountLine(MOrder order, List<OrderLinePromotionCandidate> candidates) throws Exception
{
for (OrderLinePromotionCandidate candidate : candidates)
{
final String rewardMode = candidate.promotionReward.getRewardMode();
if (MPromotionReward.REWARDMODE_Charge.equals(rewardMode))
{
BigDecimal discount = candidate.orderLine.getPriceActual().multiply(candidate.qty);
discount = discount.subtract(candidate.promotionReward.getAmount());
BigDecimal qty = Env.ONE;
int C_Charge_ID = candidate.promotionReward.getC_Charge_ID();
I_M_Promotion promotion = candidate.promotionReward.getM_Promotion();
addDiscountLine(order, null, discount, qty, C_Charge_ID, promotion);
}
else if (MPromotionReward.REWARDMODE_SplitQuantity.equals(rewardMode))
{
if (candidate.promotionReward.getAmount().signum() != 0)
{
throw new AdempiereException("@NotSupported@ @M_PromotionReward@ @Amount@ (@RewardMode@:"+rewardMode+"@)");
}
MOrderLine nol = new MOrderLine(order);
MOrderLine.copyValues(candidate.orderLine, nol);
// task 09358: get rid of this; instead, update qtyReserved at one central place
|
// nol.setQtyReserved(Env.ZERO);
nol.setQtyDelivered(Env.ZERO);
nol.setQtyInvoiced(Env.ZERO);
nol.setQtyLostSales(Env.ZERO);
nol.setQty(candidate.qty);
nol.setPrice(Env.ZERO);
nol.setDiscount(Env.ONEHUNDRED);
setPromotion(nol, candidate.promotionReward.getM_Promotion());
setNextLineNo(nol);
nol.saveEx();
}
else
{
throw new AdempiereException("@NotSupported@ @RewardMode@ "+rewardMode);
}
}
}
private static void setPromotion(MOrderLine nol, I_M_Promotion promotion)
{
nol.addDescription(promotion.getName());
nol.set_ValueOfColumn("M_Promotion_ID", promotion.getM_Promotion_ID());
if (promotion.getC_Campaign_ID() > 0)
{
nol.setC_Campaign_ID(promotion.getC_Campaign_ID());
}
}
private static void setNextLineNo(MOrderLine ol)
{
if (ol != null && Integer.toString(ol.getLine()).endsWith("0")) {
for(int i = 0; i < 9; i++) {
int line = ol.getLine() + i + 1;
int r = DB.getSQLValue(ol.get_TrxName(), "SELECT C_OrderLine_ID FROM C_OrderLine WHERE C_Order_ID = ? AND Line = ?", ol.getC_Order_ID(), line);
if (r <= 0) {
ol.setLine(line);
return;
}
}
}
ol.setLine(0);
}
// metas: end
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\model\PromotionRule.java
| 1
|
请完成以下Java代码
|
public void setIdIn(String[] groupIds) {
this.ids = groupIds;
}
@CamundaQueryParam("name")
public void setName(String groupName) {
this.name = groupName;
}
@CamundaQueryParam("nameLike")
public void setNameLike(String groupNameLike) {
this.nameLike = groupNameLike;
}
@CamundaQueryParam("type")
public void setType(String groupType) {
this.type = groupType;
}
@CamundaQueryParam("member")
public void setMember(String member) {
this.member = member;
}
@CamundaQueryParam("memberOfTenant")
public void setMemberOfTenant(String tenantId) {
this.tenantId = tenantId;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected GroupQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createGroupQuery();
}
@Override
protected void applyFilters(GroupQuery query) {
if (id != null) {
query.groupId(id);
}
|
if (ids != null) {
query.groupIdIn(ids);
}
if (name != null) {
query.groupName(name);
}
if (nameLike != null) {
query.groupNameLike(nameLike);
}
if (type != null) {
query.groupType(type);
}
if (member != null) {
query.groupMember(member);
}
if (tenantId != null) {
query.memberOfTenant(tenantId);
}
}
@Override
protected void applySortBy(GroupQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_GROUP_ID_VALUE)) {
query.orderByGroupId();
} else if (sortBy.equals(SORT_BY_GROUP_NAME_VALUE)) {
query.orderByGroupName();
} else if (sortBy.equals(SORT_BY_GROUP_TYPE_VALUE)) {
query.orderByGroupType();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\GroupQueryDto.java
| 1
|
请完成以下Java代码
|
public int getAmount() {
return amount;
}
public double getPrice() {
return price;
}
public Market getMarket() {
return market;
}
public Currency getCurrency() {
return currency;
}
|
public String getSymbol() {
return symbol;
}
@Override
public String toString() {
return new StringJoiner(", ", MarketData.class.getSimpleName() + "[", "]").add("amount=" + amount)
.add("price=" + price)
.add("market=" + market)
.add("currency=" + currency)
.add("symbol='" + symbol + "'")
.toString();
}
}
|
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\sbe\MarketData.java
| 1
|
请完成以下Java代码
|
public boolean isAutoStoreVariables() {
return autoStoreVariables;
}
public void setAutoStoreVariables(boolean autoStoreVariables) {
this.autoStoreVariables = autoStoreVariables;
}
public boolean isDoNotIncludeVariables() {
return doNotIncludeVariables;
}
public void setDoNotIncludeVariables(boolean doNotIncludeVariables) {
this.doNotIncludeVariables = doNotIncludeVariables;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
if (inParameters == null) {
inParameters = new ArrayList<>();
}
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
|
@Override
public ScriptTask clone() {
ScriptTask clone = new ScriptTask();
clone.setValues(this);
return clone;
}
public void setValues(ScriptTask otherElement) {
super.setValues(otherElement);
setScriptFormat(otherElement.getScriptFormat());
setScript(otherElement.getScript());
setResultVariable(otherElement.getResultVariable());
setSkipExpression(otherElement.getSkipExpression());
setAutoStoreVariables(otherElement.isAutoStoreVariables());
setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables());
inParameters = null;
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
inParameters = new ArrayList<>();
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptTask.java
| 1
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Human other = (Human) obj;
if (age != other.age) {
|
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Human [name=").append(name).append(", age=").append(age).append("]");
return builder.toString();
}
}
|
repos\tutorials-master\core-java-modules\core-java-lambdas\src\main\java\com\baeldung\java8\entity\Human.java
| 1
|
请完成以下Java代码
|
public void setI_BPartner_GlobalID_ID (int I_BPartner_GlobalID_ID)
{
if (I_BPartner_GlobalID_ID < 1)
set_ValueNoCheck (COLUMNNAME_I_BPartner_GlobalID_ID, null);
else
set_ValueNoCheck (COLUMNNAME_I_BPartner_GlobalID_ID, Integer.valueOf(I_BPartner_GlobalID_ID));
}
/** Get Import BPartnerr Global ID.
@return Import BPartnerr Global ID */
@Override
public int getI_BPartner_GlobalID_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_I_BPartner_GlobalID_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Import-Fehlermeldung.
@param I_ErrorMsg
Meldungen, die durch den Importprozess generiert wurden
*/
@Override
public void setI_ErrorMsg (java.lang.String I_ErrorMsg)
{
set_Value (COLUMNNAME_I_ErrorMsg, I_ErrorMsg);
}
/** Get Import-Fehlermeldung.
@return Meldungen, die durch den Importprozess generiert wurden
*/
@Override
public java.lang.String getI_ErrorMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_I_ErrorMsg);
}
/** Set Importiert.
@param I_IsImported
Ist dieser Import verarbeitet worden?
*/
@Override
public void setI_IsImported (boolean I_IsImported)
{
set_Value (COLUMNNAME_I_IsImported, Boolean.valueOf(I_IsImported));
}
/** Get Importiert.
@return Ist dieser Import verarbeitet worden?
*/
@Override
public boolean isI_IsImported ()
{
Object oo = get_Value(COLUMNNAME_I_IsImported);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
|
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set URL3.
@param URL3
Vollständige Web-Addresse, z.B. https://metasfresh.com/
*/
@Override
public void setURL3 (java.lang.String URL3)
{
set_Value (COLUMNNAME_URL3, URL3);
}
/** Get URL3.
@return Vollständige Web-Addresse, z.B. https://metasfresh.com/
*/
@Override
public java.lang.String getURL3 ()
{
return (java.lang.String)get_Value(COLUMNNAME_URL3);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner_GlobalID.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<InputStreamResource> downloadFile1() throws IOException {
File file = new File(FILE_PATH);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + file.getName())
.contentType(MediaType.APPLICATION_PDF).contentLength(file.length())
.body(resource);
}
// Using ResponseEntity<ByteArrayResource>
@GetMapping("/download2")
public ResponseEntity<ByteArrayResource> downloadFile2() throws IOException{
Path path = Paths.get(FILE_PATH);
byte[] data = Files.readAllBytes(path);
ByteArrayResource resource = new ByteArrayResource(data);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + path.getFileName().toString())
.contentType(MediaType.APPLICATION_PDF).contentLength(data.length)
.body(resource);
}
//Using HttpServeltResponse
|
@GetMapping("/download3")
public void downloadFile3(HttpServletResponse response) throws IOException{
File file = new File(FILE_PATH);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSourceCode\SpringDownloadFiles\src\main\java\spring\basic\FileDownloadController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InvoiceDueDateProviderService
{
private final List<InvoiceDueDateProvider> invoiceDueDateProviders;
private final PaymentTermBasedDueDateProvider defaultInvoicedueDateProvider;
public InvoiceDueDateProviderService(
@NonNull final Optional<List<InvoiceDueDateProvider>> invoiceDueDateProviders,
@NonNull final PaymentTermBasedDueDateProvider defaultInvoicedueDateProvider)
{
this.invoiceDueDateProviders = invoiceDueDateProviders
.orElse(ImmutableList.of())
.stream()
.filter(p -> !p.equals(defaultInvoicedueDateProvider))
.collect(ImmutableList.toImmutableList());
this.defaultInvoicedueDateProvider = defaultInvoicedueDateProvider;
|
}
public LocalDate provideDueDateFor(@NonNull final InvoiceId invoiceId)
{
for (final InvoiceDueDateProvider provider : invoiceDueDateProviders)
{
final LocalDate dueDate = provider.provideDueDateOrNull(invoiceId);
if (dueDate != null)
{
return dueDate;
}
}
return defaultInvoicedueDateProvider.provideDueDateOrNull(invoiceId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\InvoiceDueDateProviderService.java
| 2
|
请完成以下Java代码
|
protected String formatTableRecordReference(@NonNull final ITableRecordReference recordRef)
{
// Retrieve the record
final Object record;
try
{
final IContextAware context = PlainContextAware.createUsingOutOfTransaction();
record = recordRef.getModel(context);
}
catch (final Exception e)
{
logger.info("Failed retrieving record for " + recordRef, e);
return "<" + recordRef.getRecord_ID() + ">";
}
|
if (record == null)
{
logger.info("Failed retrieving record for " + recordRef);
return "<" + recordRef.getRecord_ID() + ">";
}
final String documentNo = Services.get(IDocumentBL.class).getDocumentNo(record);
return documentNo;
}
@Override
protected String formatText(final String text)
{
return text == null ? "" : text;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotificationDetailMessageFormat.java
| 1
|
请完成以下Java代码
|
public Response token(MultivaluedMap<String, String> params,
@HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) throws JOSEException {
//Check grant_type params
String grantType = params.getFirst("grant_type");
if (grantType == null || grantType.isEmpty())
return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST);
if (!supportedGrantTypes.contains(grantType)) {
return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST);
}
//Client Authentication
String[] clientCredentials = extract(authHeader);
if (clientCredentials.length != 2) {
return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST);
}
String clientId = clientCredentials[0];
Client client = appDataRepository.getClient(clientId);
if (client == null) {
return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST);
}
String clientSecret = clientCredentials[1];
if (!clientSecret.equals(client.getClientSecret())) {
return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED);
}
AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get();
JsonObject tokenResponse = null;
try {
tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params);
} catch (WebApplicationException e) {
return e.getResponse();
} catch (Exception e) {
|
return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR);
}
return Response.ok(tokenResponse)
.header("Cache-Control", "no-store")
.header("Pragma", "no-cache")
.build();
}
private String[] extract(String authHeader) {
if (authHeader != null && authHeader.startsWith("Basic ")) {
return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":");
}
return new String[]{};
}
private Response responseError(String error, String errorDescription, Response.Status status) {
JsonObject errorResponse = Json.createObjectBuilder()
.add("error", error)
.add("error_description", errorDescription)
.build();
return Response.status(status)
.entity(errorResponse).build();
}
}
|
repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-authorization-server\src\main\java\com\baeldung\oauth2\authorization\server\api\TokenEndpoint.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Modification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String description;
private String modification;
@ManyToOne(fetch = FetchType.LAZY)
private Chapter chapter;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
|
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getModification() {
return modification;
}
public void setModification(String modification) {
this.modification = modification;
}
public Chapter getChapter() {
return chapter;
}
public void setChapter(Chapter chapter) {
this.chapter = chapter;
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootOptimisticForceIncrement\src\main\java\com\bookstore\entity\Modification.java
| 2
|
请完成以下Java代码
|
public String getConnectionBackendId(final Connection connection, final boolean throwDBException)
{
Check.assumeNotNull(connection, "connection not null");
final int pgBackendPID;
final String sql = "{ ? = call pg_backend_pid() }";
CallableStatement stmt = null;
try
{
if (connection.isClosed() && !throwDBException)
{
return "<connection is closed, not trying to get backend PID>";
}
stmt = connection.prepareCall(sql);
stmt.registerOutParameter(1, Types.INTEGER);
stmt.execute();
pgBackendPID = stmt.getInt(1);
}
catch (SQLException e)
{
if (throwDBException)
{
throw new DBException(e, sql);
}
|
else
{
return "<caught " + e + " with message " + e.getMessage() + " when trying to get backend PID>";
}
}
finally
{
DB.close(stmt);
stmt = null;
}
return String.valueOf(pgBackendPID);
}
private static List<String> getAquiredConnectionInfos(final ComboPooledDataSource dataSource) throws Exception
{
final List<String> infos = BasicResourcePool_MetasfreshObserver.getAquiredConnectionInfos(dataSource);
return infos != null ? infos : ImmutableList.of();
}
} // DB_PostgreSQL
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\DB_PostgreSQL.java
| 1
|
请完成以下Java代码
|
private void init()
{
elements = new Object[size];
}
public Object nextElement() throws java.util.NoSuchElementException
{
if ( elements[place] != null && place != current)
{
place++;
return elements[place - 1];
}
else
{
place = 0;
throw new java.util.NoSuchElementException();
}
}
public boolean hasMoreElements()
{
if( place < elements.length && current != place )
return true;
return false;
}
public void setSize(int size)
{
this.size = size;
}
public int getCurrentSize()
{
return current;
}
public void rehash()
{
tmpElements = new Object[size];
int count = 0;
for ( int x = 0; x < elements.length; x++ )
{
if( elements[x] != null )
{
tmpElements[count] = elements[x];
count++;
}
}
elements = (Object[])tmpElements.clone();
tmpElements = null;
current = count;
}
public void setGrow(int grow)
{
this.grow = grow;
}
public void grow()
{
size = size+=(size/grow);
rehash();
}
public void add(Object o)
{
if( current == elements.length )
grow();
try
{
elements[current] = o;
current++;
}
catch(java.lang.ArrayStoreException ase)
|
{
}
}
public void add(int location,Object o)
{
try
{
elements[location] = o;
}
catch(java.lang.ArrayStoreException ase)
{
}
}
public void remove(int location)
{
elements[location] = null;
}
public int location(Object o) throws NoSuchObjectException
{
int loc = -1;
for ( int x = 0; x < elements.length; x++ )
{
if((elements[x] != null && elements[x] == o )||
(elements[x] != null && elements[x].equals(o)))
{
loc = x;
break;
}
}
if( loc == -1 )
throw new NoSuchObjectException();
return(loc);
}
public Object get(int location)
{
return elements[location];
}
public java.util.Enumeration elements()
{
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\storage\Array.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class CommentService {
private final ArticleRepository articleRepository;
private final UserRepository userRepository;
public Mono<CommentView> addComment(String slug, CreateCommentRequest request, User currentUser) {
return articleRepository.findBySlugOrFail(slug)
.flatMap(article -> addComment(request, currentUser, article));
}
public Mono<Void> deleteComment(String commentId, String slug, User user) {
return articleRepository.findBySlugOrFail(slug)
.flatMap(article -> article.getCommentById(commentId)
.map(comment -> deleteComment(article, comment, user))
.orElse(Mono.empty())
);
}
public Mono<MultipleCommentsView> getComments(String slug, Optional<User> user) {
return articleRepository.findBySlug(slug)
.zipWhen(article -> userRepository.findById(article.getAuthorId()))
.map(tuple -> {
var article = tuple.getT1();
var author = tuple.getT2();
return getComments(user, article, author);
});
}
private Mono<Void> deleteComment(Article article, Comment comment, User user) {
if (!comment.isAuthor(user)) {
return Mono.error(new InvalidRequestException("Comment", "only author can delete comment"));
}
article.deleteComment(comment);
return articleRepository.save(article).then();
|
}
private Mono<CommentView> addComment(CreateCommentRequest request, User currentUser, Article article) {
var comment = request.toComment(UUID.randomUUID().toString(), currentUser.getId());
article.addComment(comment);
var profileView = CommentView.toCommentView(comment, ProfileView.toOwnProfile(currentUser));
return articleRepository.save(article).thenReturn(profileView);
}
private MultipleCommentsView getComments(Optional<User> user, Article article, User author) {
var comments = article.getComments();
var authorProfile = user
.map(viewer -> toProfileViewForViewer(author, viewer))
.orElse(toUnfollowedProfileView(author));
var commentViews = comments.stream()
.map(comment -> CommentView.toCommentView(comment, authorProfile))
.toList();
return MultipleCommentsView.of(commentViews);
}
}
|
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\CommentService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PickFrom
{
public static PickFrom ofHuId(@NonNull final HuId huId)
{
return builder().huId(huId).build();
}
public static PickFrom ofHUInfo(@NonNull final HUInfo huInfo)
{
return ofHuId(huInfo.getId());
}
public static PickFrom ofPickingOrderId(@NonNull final PPOrderId pickingOrderId)
{
return builder().pickingOrderId(pickingOrderId).build();
}
@Nullable
HuId huId;
@Nullable
PPOrderId pickingOrderId;
@Builder
private PickFrom(
@Nullable HuId huId,
@Nullable PPOrderId pickingOrderId)
|
{
this.pickingOrderId = pickingOrderId;
this.huId = huId;
}
public boolean isPickFromHU()
{
return getHuId() != null;
}
public boolean isPickFromPickingOrder()
{
return getPickingOrderId() != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickFrom.java
| 2
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
ExecutionEntity sourceInstanceExecution = determineSourceInstanceExecution(commandContext);
// Outline:
// 1. find topmost scope execution beginning at scopeExecution that has exactly
// one child (this is the topmost scope we can cancel)
// 2. cancel all children of the topmost execution
// 3. cancel the activity of the topmost execution itself (if applicable)
// 4. remove topmost execution (and concurrent parent) if topmostExecution is not the process instance
ExecutionEntity topmostCancellableExecution = sourceInstanceExecution;
ExecutionEntity parentScopeExecution = (ExecutionEntity) topmostCancellableExecution.getParentScopeExecution(false);
// if topmostCancellableExecution's scope execution has no other non-event-scope children,
// we have reached the correct execution
while (parentScopeExecution != null && (parentScopeExecution.getNonEventScopeExecutions().size() <= 1)) {
topmostCancellableExecution = parentScopeExecution;
parentScopeExecution = (ExecutionEntity) topmostCancellableExecution.getParentScopeExecution(false);
}
if (topmostCancellableExecution.isPreserveScope()) {
topmostCancellableExecution.interrupt(cancellationReason, skipCustomListeners, skipIoMappings, externallyTerminated);
topmostCancellableExecution.leaveActivityInstance();
topmostCancellableExecution.setActivity(null);
} else {
topmostCancellableExecution.deleteCascade(cancellationReason, skipCustomListeners, skipIoMappings, externallyTerminated, false);
ModificationUtil.handleChildRemovalInScope(topmostCancellableExecution);
|
}
return null;
}
protected abstract ExecutionEntity determineSourceInstanceExecution(CommandContext commandContext);
protected ExecutionEntity findSuperExecution(ExecutionEntity parentScopeExecution, ExecutionEntity topmostCancellableExecution){
ExecutionEntity superExecution = null;
if(parentScopeExecution == null) {
superExecution = topmostCancellableExecution.getSuperExecution();
}
return superExecution;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractInstanceCancellationCmd.java
| 1
|
请完成以下Java代码
|
protected boolean isEligibleForMaterialTracking(final I_C_Invoice document)
{
// Reversals are not eligible, because their original-invoice counterpart is also unlinked.
if (Services.get(IInvoiceBL.class).isReversal(document))
{
return false;
}
// Sales Invoices are not eligible
if (document.isSOTrx())
{
return false;
}
return false;
}
@Override
protected List<I_C_InvoiceLine> retrieveDocumentLines(final I_C_Invoice document)
{
|
final List<I_C_InvoiceLine> documentLines = Services.get(IInvoiceDAO.class).retrieveLines(document);
return documentLines;
}
/**
* Gets order line's ASI (where the material tracking is set)
*/
@Override
protected AttributeSetInstanceId getM_AttributeSetInstance(final I_C_InvoiceLine documentLine)
{
if (documentLine.getC_OrderLine_ID() <= 0)
{
return null;
}
final I_C_OrderLine orderLine = documentLine.getC_OrderLine();
return AttributeSetInstanceId.ofRepoIdOrNone(orderLine.getM_AttributeSetInstance_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\C_Invoice.java
| 1
|
请完成以下Java代码
|
public Optional<QuantityTU> calculateQtyTU(
@NonNull final BigDecimal qty,
@NonNull final I_C_UOM targetUom,
@NonNull final QuantityUOMConverter uomConverter)
{
// Infinite capacity => one pack would be sufficient
if (infiniteCapacity)
{
return Optional.of(QuantityTU.ONE);
}
// Qty is zero => zero packs
if (qty.signum() == 0)
{
return Optional.of(QuantityTU.ZERO);
}
// Capacity is ZERO => N/A
if (capacity.signum() <= 0)
{
return Optional.empty();
}
// Convert Qty to Capacity's UOM
final BigDecimal qtyConv = uomConverter.convertQty(productId, qty, uom, targetUom);
final int qtyTUs = qtyConv.divide(capacity, 0, RoundingMode.UP).intValueExact();
return Optional.of(QuantityTU.ofInt(qtyTUs));
}
public Capacity multiply(final int multiplier)
{
Check.assume(multiplier >= 0, "multiplier = {} needs to be 0", multiplier);
// If capacity is infinite, there is no point to multiply it
if (infiniteCapacity)
{
return this;
}
final BigDecimal capacityNew = capacity.multiply(BigDecimal.valueOf(multiplier));
return createCapacity(
capacityNew,
productId,
uom,
allowNegativeCapacity);
}
public I_C_UOM getC_UOM()
{
return uom;
}
|
@Override
public String toString()
{
return "Capacity ["
+ "infiniteCapacity=" + infiniteCapacity
+ ", capacity(qty)=" + capacity
+ ", product=" + productId
+ ", uom=" + (uom == null ? "null" : uom.getUOMSymbol())
+ ", allowNegativeCapacity=" + allowNegativeCapacity
+ "]";
}
public Quantity computeQtyCUs(final int qtyTUs)
{
if (qtyTUs < 0)
{
throw new AdempiereException("@QtyPacks@ < 0");
}
return multiply(qtyTUs).toQuantity();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Capacity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static @Nullable BeanDefinition createExpressionDefinitionFromValueOrExpression(String valueElementName,
String expressionElementName, ParserContext parserContext, Element element, boolean oneRequired) {
Assert.hasText(valueElementName, "'valueElementName' must not be empty");
Assert.hasText(expressionElementName, "'expressionElementName' must not be empty");
String valueElementValue = element.getAttribute(valueElementName);
String expressionElementValue = element.getAttribute(expressionElementName);
boolean hasAttributeValue = StringUtils.hasText(valueElementValue);
boolean hasAttributeExpression = StringUtils.hasText(expressionElementValue);
if (hasAttributeValue && hasAttributeExpression) {
parserContext.getReaderContext().error("Only one of '" + valueElementName + "' or '"
+ expressionElementName + "' is allowed", element);
}
if (oneRequired && (!hasAttributeValue && !hasAttributeExpression)) {
parserContext.getReaderContext().error("One of '" + valueElementName + "' or '"
+ expressionElementName + "' is required", element);
}
BeanDefinition expressionDef;
if (hasAttributeValue) {
expressionDef = new RootBeanDefinition(LiteralExpression.class);
|
expressionDef.getConstructorArgumentValues().addGenericArgumentValue(valueElementValue);
}
else {
expressionDef = createExpressionDefIfAttributeDefined(expressionElementName, element);
}
return expressionDef;
}
public static @Nullable BeanDefinition createExpressionDefIfAttributeDefined(
String expressionElementName, Element element) {
Assert.hasText(expressionElementName, "'expressionElementName' must no be empty");
String expressionElementValue = element.getAttribute(expressionElementName);
if (StringUtils.hasText(expressionElementValue)) {
BeanDefinitionBuilder expressionDefBuilder =
BeanDefinitionBuilder.genericBeanDefinition(ExpressionFactoryBean.class);
expressionDefBuilder.addConstructorArgValue(expressionElementValue);
return expressionDefBuilder.getRawBeanDefinition();
}
return null;
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\NamespaceUtils.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
static byte[] getContent(String samlObject, String relayState, final Map<String, String> queryParams) {
if (Objects.nonNull(relayState)) {
return String
.format("%s=%s&%s=%s&%s=%s", samlObject, queryParams.get(samlObject),
Saml2ParameterNames.RELAY_STATE, queryParams.get(Saml2ParameterNames.RELAY_STATE),
Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG))
.getBytes(StandardCharsets.UTF_8);
}
else {
return String
.format("%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.SIG_ALG,
queryParams.get(Saml2ParameterNames.SIG_ALG))
.getBytes(StandardCharsets.UTF_8);
}
}
String getId() {
return this.id;
}
Issuer getIssuer() {
return this.issuer;
}
byte[] getContent() {
return this.content;
}
String getAlgorithm() {
return this.algorithm;
}
|
byte[] getSignature() {
return this.signature;
}
boolean hasSignature() {
return this.signature != null;
}
}
}
interface DecryptionConfigurer {
void decrypt(XMLObject object);
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\internal\OpenSamlOperations.java
| 2
|
请完成以下Java代码
|
public class WebServer {
private final InetSocketAddress address = new InetSocketAddress(8080);
private final Path path = Path.of("/");
public static void main(String[] args) {
WebServer webServer = new WebServer();
HttpServer server = webServer.createWithHandler401Response();
server.start();
}
private HttpServer createBasic() {
return SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
}
private HttpServer createWithHandler() throws IOException {
HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users"));
server.createContext("/test", handler);
return server;
}
private HttpServer createWithHandler401Response() {
Predicate<Request> findAllowedPath = r -> r.getRequestURI()
.getPath()
.equals("/test/allowed");
HttpHandler allowedResponse = HttpHandlers.of(200, Headers.of("Allow", "GET"), "Welcome");
HttpHandler deniedResponse = HttpHandlers.of(401, Headers.of("Deny", "GET"), "Denied");
|
HttpHandler handler = HttpHandlers.handleOrElse(findAllowedPath, allowedResponse, deniedResponse);
HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
server.createContext("/test", handler);
return server;
}
private HttpServer createWithFilter() throws IOException {
Filter filter = SimpleFileServer.createOutputFilter(System.out, SimpleFileServer.OutputLevel.INFO);
HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users"));
return HttpServer.create(new InetSocketAddress(8080), 10, "/test", handler, filter);
}
}
|
repos\tutorials-master\core-java-modules\core-java-18\src\main\java\com\baeldung\simplewebserver\WebServer.java
| 1
|
请完成以下Java代码
|
public MessageEventPayload getMessagePayload() {
return messagePayload;
}
public void setMessagePayload(MessageEventPayload messagePayload) {
this.messagePayload = messagePayload;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BPMNMessageImpl that = (BPMNMessageImpl) o;
return (
Objects.equals(getElementId(), that.getElementId()) &&
Objects.equals(messagePayload, that.getMessagePayload())
);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((messagePayload == null) ? 0 : messagePayload.hashCode());
|
return result;
}
@Override
public String toString() {
return (
"BPMNMessageImpl{" +
", elementId='" +
getElementId() +
'\'' +
", messagePayload='" +
(messagePayload != null ? messagePayload.toString() : null) +
'\'' +
'}'
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNMessageImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PriceLimitRuleResult
{
public static PriceLimitRuleResult notApplicable(@NonNull final String reason)
{
return notApplicable(TranslatableStrings.anyLanguage(reason));
}
public static PriceLimitRuleResult notApplicable(@NonNull final ITranslatableString reason)
{
return PriceLimitRuleResult._builder()
.applicable(false)
.notApplicableReason(reason)
.build();
}
public static PriceLimitRuleResult priceLimit(@NonNull final BigDecimal priceLimit, final String priceLimitExplanation)
{
return priceLimit(priceLimit, TranslatableStrings.anyLanguage(priceLimitExplanation));
}
public static PriceLimitRuleResult priceLimit(@NonNull final BigDecimal priceLimit, @NonNull final ITranslatableString priceLimitExplanation)
{
return PriceLimitRuleResult._builder()
.applicable(true)
.priceLimit(priceLimit)
.priceLimitExplanation(priceLimitExplanation)
.build();
}
private boolean applicable;
private ITranslatableString notApplicableReason;
private BigDecimal priceLimit;
/** Explanation about how the price limit was calculated, from where it comes etc */
private ITranslatableString priceLimitExplanation;
@Builder(builderMethodName = "_builder")
private PriceLimitRuleResult(
final boolean applicable,
final ITranslatableString notApplicableReason,
final BigDecimal priceLimit,
final ITranslatableString priceLimitExplanation)
{
if (applicable)
{
Check.assumeNotNull(priceLimit, "Parameter priceLimit is not null");
Check.assumeNotNull(priceLimitExplanation, "Parameter priceLimitExplanation is not null");
this.applicable = true;
|
this.priceLimit = priceLimit;
this.priceLimitExplanation = priceLimitExplanation;
this.notApplicableReason = null;
}
else
{
Check.assumeNotNull(notApplicableReason, "Parameter notApplicableReason is not null");
this.applicable = false;
this.notApplicableReason = notApplicableReason;
this.priceLimit = null;
this.priceLimitExplanation = null;
}
}
public BooleanWithReason checkApplicableAndBelowPriceLimit(@NonNull final BigDecimal priceActual)
{
if (!applicable)
{
return BooleanWithReason.falseBecause(notApplicableReason);
}
if (priceLimit.signum() == 0)
{
return BooleanWithReason.falseBecause("limit price is ZERO");
}
final boolean belowPriceLimit = priceActual.compareTo(priceLimit) < 0;
if (belowPriceLimit)
{
return BooleanWithReason.trueBecause(priceLimitExplanation);
}
else
{
return BooleanWithReason.falseBecause("Price " + priceActual + " is above " + priceLimit + "(limit price)");
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\limit\PriceLimitRuleResult.java
| 2
|
请完成以下Java代码
|
private static Optional<InstantAndOrgId> calculateEarliestPreparationTime(final PackageableList packageables)
{
return packageables.stream()
.map(Packageable::getPreparationDate)
.filter(Objects::nonNull)
.min(InstantAndOrgId::compareTo);
}
@Override
public DocumentId getId()
{
return rowId.getDocumentId();
}
@Override
public boolean isProcessed()
{
return false;
}
@Nullable
@Override
public DocumentPath getDocumentPath()
{
// TODO Auto-generated method stub
return null;
}
|
@Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
public boolean isLocked()
{
return lockedByUser != null;
}
public boolean isNotLocked()
{
return !isLocked();
}
public boolean isLockedBy(@NonNull final UserId userId)
{
return lockedByUser != null
&& UserId.equals(userId, lockedByUser.getIdAs(UserId::ofRepoId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\PackageableRow.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.