instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public int getRevisionNext() {
return revision + 1;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public boolean isInserted() {
return isInserted;
}
public void setInserted(boolean isInserted) {
this.isInserted = isInserted; | }
public boolean isUpdated() {
return isUpdated;
}
public void setUpdated(boolean isUpdated) {
this.isUpdated = isUpdated;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractEntity.java | 1 |
请完成以下Java代码 | public QueueBuilder lazy() {
return withArgument("x-queue-mode", "lazy");
}
/**
* Set the master locator mode which determines which node a queue master will be
* located on a cluster of nodes.
* @param locator {@link LeaderLocator}.
* @return the builder.
* @since 2.2
*/
public QueueBuilder leaderLocator(LeaderLocator locator) {
return withArgument("x-queue-master-locator", locator.getValue());
}
/**
* Set the 'x-single-active-consumer' queue argument.
* @return the builder.
* @since 2.2.2
*/
public QueueBuilder singleActiveConsumer() {
return withArgument("x-single-active-consumer", true);
}
/**
* Set the queue argument to declare a queue of type 'quorum' instead of 'classic'.
* @return the builder.
* @since 2.2.2
*/
public QueueBuilder quorum() {
return withArgument("x-queue-type", "quorum");
}
/**
* Set the queue argument to declare a queue of type 'stream' instead of 'classic'.
* @return the builder.
* @since 2.4
*/
public QueueBuilder stream() {
return withArgument("x-queue-type", "stream");
}
/**
* Set the delivery limit; only applies to quorum queues.
* @param limit the limit.
* @return the builder.
* @since 2.2.2
* @see #quorum()
*/
public QueueBuilder deliveryLimit(int limit) {
return withArgument("x-delivery-limit", limit);
}
/**
* Builds a final queue.
* @return the Queue instance.
*/
public Queue build() {
return new Queue(this.name, this.durable, this.exclusive, this.autoDelete, getArguments());
}
/**
* Overflow argument values.
*/
public enum Overflow {
/**
* Drop the oldest message.
*/
dropHead("drop-head"),
/**
* Reject the new message.
*/
rejectPublish("reject-publish"); | private final String value;
Overflow(String value) {
this.value = value;
}
/**
* Return the value.
* @return the value.
*/
public String getValue() {
return this.value;
}
}
/**
* Locate the queue leader.
*
* @since 2.3.7
*
*/
public enum LeaderLocator {
/**
* Deploy on the node with the fewest queue leaders.
*/
minLeaders("min-masters"),
/**
* Deploy on the node we are connected to.
*/
clientLocal("client-local"),
/**
* Deploy on a random node.
*/
random("random");
private final String value;
LeaderLocator(String value) {
this.value = value;
}
/**
* Return the value.
* @return the value.
*/
public String getValue() {
return this.value;
}
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\QueueBuilder.java | 1 |
请完成以下Java代码 | public class ResultVo extends HashMap<String, Object> {
public ResultVo() {
put("code", 200);
put("msg", "success");
}
public static ResultVo ok() {
return new ResultVo();
}
public static ResultVo ok(Object data) {
ResultVo resultVo = new ResultVo();
resultVo.put("data", data);
return resultVo;
}
public static ResultVo error(String msg) {
ResultVo resultVo = new ResultVo();
resultVo.put("code", 500); | resultVo.put("msg", msg);
return resultVo;
}
public static ResultVo error(int code, String msg) {
ResultVo resultVo = new ResultVo();
resultVo.put("code", code);
resultVo.put("msg", msg);
return resultVo;
}
@Override
public ResultVo put(String key, Object value) {
super.put(key, value);
return this;
}
} | repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\vo\ResultVo.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("class", classRef)
.add("methodName", methodName)
.add("parameters", parameterTypeRefs)
.toString();
}
public Method getMethod()
{
// Get if not expired
{
final WeakReference<Method> weakRef = methodRef.get();
final Method method = weakRef != null ? weakRef.get() : null;
if (method != null)
{
return method;
}
}
// Load the class
try
{
final Class<?> clazz = classRef.getReferencedClass();
final Class<?>[] parameterTypes = parameterTypeRefs.stream()
.map(parameterTypeRef -> parameterTypeRef.getReferencedClass())
.toArray(size -> new Class<?>[size]); | final Method methodNew = clazz.getDeclaredMethod(methodName, parameterTypes);
methodRef.set(new WeakReference<>(methodNew));
return methodNew;
}
catch (final Exception ex)
{
throw new IllegalStateException("Cannot load expired field: " + classRef + "/" + methodName + " (" + parameterTypeRefs + ")", ex);
}
}
@VisibleForTesting
void forget()
{
methodRef.set(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\reflect\MethodReference.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public String getProcessDefinitionNameLike() {
return processDefinitionNameLike;
}
public String getActivityId() {
return activityId;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public Boolean getRetriesLeft() {
return retriesLeft; | }
public Date getNow() {
return ClockUtil.getCurrentTime();
}
protected void ensureVariablesInitialized() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
String dbType = processEngineConfiguration.getDatabaseType();
for(QueryVariableValue var : variables) {
var.initialize(variableSerializers, dbType);
}
}
public List<QueryVariableValue> getVariables() {
return variables;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static DDOrderQueryBuilder ddOrdersAssignedToUser(@NonNull final UserId responsibleId, @NonNull DistributionJobSorting sorting)
{
return newDDOrdersQuery()
.orderBys(sorting.toDDOrderQueryOrderBys())
.responsibleId(ValueRestriction.equalsTo(responsibleId));
}
public static DDOrderQuery toActiveNotAssignedDDOrderQuery(final @NonNull DDOrderReferenceQuery query)
{
final DistributionFacetIdsCollection activeFacetIds = query.getActiveFacetIds();
final InSetPredicate<WarehouseId> warehouseToIds = extractWarehouseToIds(query);
return newDDOrdersQuery()
.orderBys(query.getSorting().toDDOrderQueryOrderBys())
.responsibleId(ValueRestriction.isNull())
.warehouseFromIds(activeFacetIds.getWarehouseFromIds())
.warehouseToIds(warehouseToIds)
.locatorToIds(InSetPredicate.onlyOrAny(query.getLocatorToId()))
.salesOrderIds(activeFacetIds.getSalesOrderIds())
.manufacturingOrderIds(activeFacetIds.getManufacturingOrderIds())
.datesPromised(activeFacetIds.getDatesPromised())
.productIds(activeFacetIds.getProductIds())
.qtysEntered(activeFacetIds.getQuantities())
.plantIds(activeFacetIds.getPlantIds())
.build();
}
@Nullable
private static InSetPredicate<WarehouseId> extractWarehouseToIds(final @NotNull DDOrderReferenceQuery query)
{
final Set<WarehouseId> facetWarehouseToIds = query.getActiveFacetIds().getWarehouseToIds();
final WarehouseId onlyWarehouseToId = query.getWarehouseToId();
if (onlyWarehouseToId != null)
{
if (facetWarehouseToIds.isEmpty() || facetWarehouseToIds.contains(onlyWarehouseToId))
{ | return InSetPredicate.only(onlyWarehouseToId);
}
else
{
return InSetPredicate.none();
}
}
else if (!facetWarehouseToIds.isEmpty())
{
return InSetPredicate.only(facetWarehouseToIds);
}
else
{
return InSetPredicate.any();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobQueries.java | 2 |
请完成以下Java代码 | public void setPA_Achievement_ID (int PA_Achievement_ID)
{
if (PA_Achievement_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, Integer.valueOf(PA_Achievement_ID));
}
/** Get Achievement.
@return Performance Achievement
*/
public int getPA_Achievement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Achievement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Measure getPA_Measure() throws RuntimeException
{
return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name)
.getPO(getPA_Measure_ID(), get_TrxName()); }
/** Set Measure.
@param PA_Measure_ID
Concrete Performance Measurement
*/
public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null);
else | set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Achievement.java | 1 |
请完成以下Java代码 | public void findAndRegisterMbeans() throws Exception {
register(new ProcessDefinitionsMBean(jmxConfigurator.getProcessEngineConfig()), new ObjectName(jmxConfigurator.getDomain(), "type", "Deployments"));
register(new JobExecutorMBean(jmxConfigurator.getProcessEngineConfig()), new ObjectName(jmxConfigurator.getDomain(), "type", "JobExecutor"));
}
public void createJmxConnector(String host) throws IOException {
String serviceUrlPath = jmxConfigurator.getServiceUrlPath();
Integer registryPort = jmxConfigurator.getRegistryPort();
Integer connectorPort = jmxConfigurator.getConnectorPort();
if (serviceUrlPath == null) {
LOGGER.warn("Service url path is null. JMX connector creation skipped");
return;
}
if (registryPort == null) {
LOGGER.warn("Registry port is null. JMX connector creation skipped.");
return;
}
try {
registry = LocateRegistry.createRegistry(registryPort);
LOGGER.debug("Created JMXConnector RMI registry on port {}", registryPort);
} catch (RemoteException ex) {
// The registry may had been created, we could get the registry instead
}
// must start with leading slash
String path = serviceUrlPath.startsWith("/") ? serviceUrlPath : "/" + serviceUrlPath;
// Create an RMI connector and start it
final JMXServiceURL url;
if (connectorPort > 0) { | url = new JMXServiceURL("service:jmx:rmi://" + host + ":" + connectorPort + "/jndi/rmi://" + host + ":" + registryPort + path);
} else {
url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + registryPort + path);
}
cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
// use async thread for starting the JMX Connector
// (no need to use a thread pool or enlist in JMX as this thread is
// terminated when the JMX connector has been started)
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
LOGGER.debug("Staring JMX Connector thread to listen at: {}", url);
cs.start();
LOGGER.info("JMX Connector thread started and listening at: {}", url);
} catch (IOException ioe) {
if (ioe.getCause() instanceof javax.naming.NameAlreadyBoundException) {
LOGGER.warn("JMX connection:{} already exists.", url);
} else {
LOGGER.warn("Could not start JMXConnector thread at: {}. JMX Connector not in use.", url, ioe);
}
}
}
}, "jmxConnectorStarterThread");
thread.start();
}
} | repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\DefaultManagementAgent.java | 1 |
请完成以下Java代码 | public void onOpen(EventSource eventSource, Response response) {
log.info("OpenAI服务器连接成功!,traceId[{}]", traceId);
}
@SneakyThrows
@Override
public void onEvent(EventSource eventSource, String id, String type, String data) {
log.info("on event data: {}", data);
if (data.equals("[DONE]")) {
log.info("OpenAI服务器发送结束标志!,traceId[{}]", traceId);
/**
* 1、完成token计算
* 2、完成数据存储
* 3、返回json格式,用于页面渲染
*/
sseEmitter.send(SseEmitter.event()
.id("[DONE]")
.data("[DONE]")
.reconnectTime(3000));
return;
}
JSONObject jsonObject = JSONUtil.parseObj(data);
JSONArray choicesJsonArray = jsonObject.getJSONArray("choices");
String content = null;
if (choicesJsonArray.isEmpty()) {
content = "";
} else {
JSONObject choiceJson = choicesJsonArray.getJSONObject(0);
JSONObject deltaJson = choiceJson.getJSONObject("delta");
String text = deltaJson.getStr("content");
if (text != null) {
content = text;
answer.add(content);
sseEmitter.send(SseEmitter.event()
.data(content)
.reconnectTime(2000));
}
} | }
@Override
public void onClosed(EventSource eventSource) {
log.info("OpenAI服务器关闭连接!,traceId[{}]", traceId);
log.info("complete answer: {}", StrUtil.join("", answer));
sseEmitter.complete();
}
@SneakyThrows
@Override
public void onFailure(EventSource eventSource, Throwable t, Response response) {
// TODO 处理前端中断
log.error("OpenAI服务器连接异常!response:[{}],traceId[{}] 当前内容:{}", response, traceId, StrUtil.join("", answer), t);
eventSource.cancel();
sseEmitter.completeWithError(t);
}
} | repos\spring-boot-quick-master\quick-sse\src\main\java\com\quick\event\ChatGPTEventListener.java | 1 |
请完成以下Java代码 | public void setOr(boolean or) {
this.or = or;
}
public boolean isOrAlphabetic() {
return orAlphabetic;
}
public void setOrAlphabetic(boolean orAlphabetic) {
this.orAlphabetic = orAlphabetic;
}
public boolean isNot() {
return not;
}
public void setNot(boolean not) {
this.not = not;
}
public boolean isNotAlphabetic() {
return notAlphabetic;
}
public void setNotAlphabetic(boolean notAlphabetic) {
this.notAlphabetic = notAlphabetic;
} | @Override
public String toString() {
return "SpelRelational{" +
"equal=" + equal +
", equalAlphabetic=" + equalAlphabetic +
", notEqual=" + notEqual +
", notEqualAlphabetic=" + notEqualAlphabetic +
", lessThan=" + lessThan +
", lessThanAlphabetic=" + lessThanAlphabetic +
", lessThanOrEqual=" + lessThanOrEqual +
", lessThanOrEqualAlphabetic=" + lessThanOrEqualAlphabetic +
", greaterThan=" + greaterThan +
", greaterThanAlphabetic=" + greaterThanAlphabetic +
", greaterThanOrEqual=" + greaterThanOrEqual +
", greaterThanOrEqualAlphabetic=" + greaterThanOrEqualAlphabetic +
", and=" + and +
", andAlphabetic=" + andAlphabetic +
", or=" + or +
", orAlphabetic=" + orAlphabetic +
", not=" + not +
", notAlphabetic=" + notAlphabetic +
'}';
}
} | repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelRelational.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DatabaseDto findById(String id) {
Database database = databaseRepository.findById(id).orElseGet(Database::new);
ValidationUtil.isNull(database.getId(),"Database","id",id);
return databaseMapper.toDto(database);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(Database resources) {
resources.setId(IdUtil.simpleUUID());
databaseRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Database resources) {
Database database = databaseRepository.findById(resources.getId()).orElseGet(Database::new);
ValidationUtil.isNull(database.getId(),"Database","id",resources.getId());
database.copy(resources);
databaseRepository.save(database);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<String> ids) {
for (String id : ids) {
databaseRepository.deleteById(id); | }
}
@Override
public boolean testConnection(Database resources) {
try {
return SqlUtils.testConnection(resources.getJdbcUrl(), resources.getUserName(), resources.getPwd());
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
@Override
public void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DatabaseDto databaseDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("数据库名称", databaseDto.getName());
map.put("数据库连接地址", databaseDto.getJdbcUrl());
map.put("用户名", databaseDto.getUserName());
map.put("创建日期", databaseDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DatabaseServiceImpl.java | 2 |
请完成以下Java代码 | public int getC_PurchaseCandidate_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PurchaseCandidate_ID);
}
@Override
public void setIsAdvised (boolean IsAdvised)
{
set_Value (COLUMNNAME_IsAdvised, Boolean.valueOf(IsAdvised));
}
@Override
public boolean isAdvised()
{
return get_ValueAsBoolean(COLUMNNAME_IsAdvised);
}
@Override
public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate()
{
return get_ValueAsPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class);
}
@Override
public void setMD_Candidate(de.metas.material.dispo.model.I_MD_Candidate MD_Candidate)
{
set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate);
}
@Override
public void setMD_Candidate_ID (int MD_Candidate_ID)
{
if (MD_Candidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_MD_Candidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MD_Candidate_ID, Integer.valueOf(MD_Candidate_ID));
}
@Override
public int getMD_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID);
}
@Override
public void setMD_Candidate_Purchase_Detail_ID (int MD_Candidate_Purchase_Detail_ID)
{
if (MD_Candidate_Purchase_Detail_ID < 1)
set_ValueNoCheck (COLUMNNAME_MD_Candidate_Purchase_Detail_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MD_Candidate_Purchase_Detail_ID, Integer.valueOf(MD_Candidate_Purchase_Detail_ID));
}
@Override
public int getMD_Candidate_Purchase_Detail_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_Purchase_Detail_ID); | }
@Override
public void setM_ReceiptSchedule_ID (int M_ReceiptSchedule_ID)
{
if (M_ReceiptSchedule_ID < 1)
set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ReceiptSchedule_ID, Integer.valueOf(M_ReceiptSchedule_ID));
}
@Override
public int getM_ReceiptSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID);
}
@Override
public void setPlannedQty (java.math.BigDecimal PlannedQty)
{
set_Value (COLUMNNAME_PlannedQty, PlannedQty);
}
@Override
public java.math.BigDecimal getPlannedQty()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPP_Product_Planning_ID (int PP_Product_Planning_ID)
{
if (PP_Product_Planning_ID < 1)
set_Value (COLUMNNAME_PP_Product_Planning_ID, null);
else
set_Value (COLUMNNAME_PP_Product_Planning_ID, Integer.valueOf(PP_Product_Planning_ID));
}
@Override
public int getPP_Product_Planning_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID);
}
@Override
public void setQtyOrdered (java.math.BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public java.math.BigDecimal getQtyOrdered()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Purchase_Detail.java | 1 |
请完成以下Java代码 | public static Optional<PaymentTermBreakId> optionalOfRepoId(
@Nullable final Integer paymentTermId,
@Nullable final Integer paymentTermBreakId)
{
return Optional.ofNullable(ofRepoIdOrNull(paymentTermId, paymentTermBreakId));
}
@Nullable
public static PaymentTermBreakId ofRepoIdOrNull(
@Nullable final PaymentTermId paymentTermId,
@Nullable final Integer paymentTermBreakId)
{
return paymentTermId != null && paymentTermBreakId != null && paymentTermBreakId > 0 ? ofRepoId(paymentTermId, paymentTermBreakId) : null;
}
@Jacksonized
@Builder
private PaymentTermBreakId(@NonNull final PaymentTermId paymentTermId, final int repoId) | {
this.paymentTermId = paymentTermId;
this.repoId = Check.assumeGreaterThanZero(repoId, "C_PaymentTerm_Break_ID");
}
public static int toRepoId(@Nullable final PaymentTermBreakId paymentTermBreakId)
{
return paymentTermBreakId != null ? paymentTermBreakId.getRepoId() : -1;
}
public static boolean equals(final @Nullable PaymentTermBreakId id1, final @Nullable PaymentTermBreakId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\payment\paymentterm\PaymentTermBreakId.java | 1 |
请完成以下Java代码 | public class X_AD_Org extends org.compiere.model.PO implements I_AD_Org, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1255990917L;
/** Standard Constructor */
public X_AD_Org (final Properties ctx, final int AD_Org_ID, @Nullable final String trxName)
{
super (ctx, AD_Org_ID, trxName);
}
/** Load Constructor */
public X_AD_Org (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_ReplicationStrategy getAD_ReplicationStrategy()
{
return get_ValueAsPO(COLUMNNAME_AD_ReplicationStrategy_ID, org.compiere.model.I_AD_ReplicationStrategy.class);
}
@Override
public void setAD_ReplicationStrategy(final org.compiere.model.I_AD_ReplicationStrategy AD_ReplicationStrategy)
{
set_ValueFromPO(COLUMNNAME_AD_ReplicationStrategy_ID, org.compiere.model.I_AD_ReplicationStrategy.class, AD_ReplicationStrategy);
}
@Override
public void setAD_ReplicationStrategy_ID (final int AD_ReplicationStrategy_ID)
{
if (AD_ReplicationStrategy_ID < 1)
set_Value (COLUMNNAME_AD_ReplicationStrategy_ID, null);
else
set_Value (COLUMNNAME_AD_ReplicationStrategy_ID, AD_ReplicationStrategy_ID);
}
@Override
public int getAD_ReplicationStrategy_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_ReplicationStrategy_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{ | return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsEUOneStopShop (final boolean IsEUOneStopShop)
{
set_Value (COLUMNNAME_IsEUOneStopShop, IsEUOneStopShop);
}
@Override
public boolean isEUOneStopShop()
{
return get_ValueAsBoolean(COLUMNNAME_IsEUOneStopShop);
}
@Override
public void setIsSummary (final boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, IsSummary);
}
@Override
public boolean isSummary()
{
return get_ValueAsBoolean(COLUMNNAME_IsSummary);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org.java | 1 |
请完成以下Java代码 | public void onApplicationEvent(@Nullable ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
ApplicationEnvironmentPreparedEvent environmentPreparedEvent = (ApplicationEnvironmentPreparedEvent) event;
onApplicationEnvironmentPreparedEvent(environmentPreparedEvent);
}
}
protected void onApplicationEnvironmentPreparedEvent(
@NonNull ApplicationEnvironmentPreparedEvent environmentPreparedEvent) {
Assert.notNull(environmentPreparedEvent, "ApplicationEnvironmentPreparedEvent must not be null");
Environment environment = environmentPreparedEvent.getEnvironment();
if (isSystemPropertyNotSet(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY)) {
String logLevel = environment.getProperty(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY,
environment.getProperty(SPRING_DATA_GEMFIRE_LOGGING_LOG_LEVEL,
environment.getProperty(SPRING_DATA_GEMFIRE_CACHE_LOG_LEVEL)));
setSystemProperty(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY, logLevel);
}
}
protected boolean isSystemPropertySet(@Nullable String propertyName) {
return StringUtils.hasText(propertyName) && StringUtils.hasText(System.getProperty(propertyName));
}
protected boolean isSystemPropertyNotSet(@Nullable String propertyName) {
return !isSystemPropertySet(propertyName);
}
protected void setSystemProperty(@NonNull String propertyName, @Nullable String propertyValue) { | Assert.hasText(propertyName, () -> String.format("PropertyName [%s] is required", propertyName));
if (StringUtils.hasText(propertyValue)) {
System.setProperty(propertyName, propertyValue);
}
}
@Override
public boolean supportsEventType(@NonNull ResolvableType eventType) {
Class<?> rawType = eventType.getRawClass();
return rawType != null && Arrays.stream(EVENT_TYPES).anyMatch(it -> it.isAssignableFrom(rawType));
}
@Override
public boolean supportsSourceType(@Nullable Class<?> sourceType) {
return sourceType != null && Arrays.stream(SOURCE_TYPES).anyMatch(it -> it.isAssignableFrom(sourceType));
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\logging\GeodeLoggingApplicationListener.java | 1 |
请完成以下Java代码 | public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User password(String password) {
this.password = password;
return this;
}
/**
* Get password
* @return password
**/
@ApiModelProperty(value = "")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User phone(String phone) {
this.phone = phone;
return this;
}
/**
* Get phone
* @return phone
**/
@ApiModelProperty(value = "")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public User userStatus(Integer userStatus) {
this.userStatus = userStatus;
return this;
}
/**
* User Status
* @return userStatus
**/
@ApiModelProperty(value = "User Status")
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(this.id, user.id) && | Objects.equals(this.username, user.username) &&
Objects.equals(this.firstName, user.firstName) &&
Objects.equals(this.lastName, user.lastName) &&
Objects.equals(this.email, user.email) &&
Objects.equals(this.password, user.password) &&
Objects.equals(this.phone, user.phone) &&
Objects.equals(this.userStatus, user.userStatus);
}
@Override
public int hashCode() {
return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\User.java | 1 |
请完成以下Java代码 | public class DefaultWebSecurityExpressionHandler extends AbstractSecurityExpressionHandler<FilterInvocation>
implements SecurityExpressionHandler<FilterInvocation> {
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private String defaultRolePrefix = DEFAULT_ROLE_PREFIX;
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(@Nullable Authentication authentication,
FilterInvocation fi) {
FilterInvocationExpressionRoot root = new FilterInvocationExpressionRoot(() -> authentication, fi);
root.setAuthorizationManagerFactory(getAuthorizationManagerFactory());
root.setPermissionEvaluator(getPermissionEvaluator());
if (!DEFAULT_ROLE_PREFIX.equals(this.defaultRolePrefix)) {
// Ensure SecurityExpressionRoot can strip the custom role prefix
root.setDefaultRolePrefix(this.defaultRolePrefix);
}
return root;
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
getDefaultAuthorizationManagerFactory().setTrustResolver(trustResolver);
}
/** | * <p>
* Sets the default prefix to be added to
* {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasAnyRole(String...)}
* or
* {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasRole(String)}.
* For example, if hasRole("ADMIN") or hasRole("ROLE_ADMIN") is passed in, then the
* role ROLE_ADMIN will be used when the defaultRolePrefix is "ROLE_" (default).
* </p>
*
* <p>
* If null or empty, then no default role prefix is used.
* </p>
* @param defaultRolePrefix the default prefix to add to roles. Default "ROLE_".
* @deprecated Use
* {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead
*/
@Deprecated(since = "7.0")
public void setDefaultRolePrefix(@Nullable String defaultRolePrefix) {
if (defaultRolePrefix == null) {
defaultRolePrefix = "";
}
getDefaultAuthorizationManagerFactory().setRolePrefix(defaultRolePrefix);
this.defaultRolePrefix = defaultRolePrefix;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\expression\DefaultWebSecurityExpressionHandler.java | 1 |
请完成以下Java代码 | public class ActivitiElContext extends ELContext {
protected ELResolver elResolver;
private ActivitiFunctionMapper functions;
private ActivitiVariablesMapper variables;
public ActivitiElContext() {
this(null);
}
public ActivitiElContext(ELResolver elResolver) {
this.elResolver = elResolver;
}
public ELResolver getELResolver() {
return elResolver;
}
public FunctionMapper getFunctionMapper() {
if (functions == null) {
functions = new ActivitiFunctionMapper();
}
return functions; | }
public VariableMapper getVariableMapper() {
if (variables == null) {
variables = new ActivitiVariablesMapper();
}
return variables;
}
public void setFunction(String prefix, String localName, Method method) {
if (functions == null) {
functions = new ActivitiFunctionMapper();
}
functions.setFunction(prefix, localName, method);
}
public ValueExpression setVariable(String name, ValueExpression expression) {
if (variables == null) {
variables = new ActivitiVariablesMapper();
}
return variables.setVariable(name, expression);
}
} | repos\Activiti-develop\activiti-core-common\activiti-expression-language\src\main\java\org\activiti\core\el\ActivitiElContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
} | public void setName(String name) {
this.name = name;
}
public Role() {
}
public Role(String name) {
this.name = name;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\model\Role.java | 2 |
请完成以下Java代码 | public static String cnapsCode(String code) {
if (oConvertUtils.isEmpty(code)) {
return "";
}
return formatRight(code, 2);
}
/**
* 将右边的格式化成*
* @param str 字符串
* @param reservedLength 保留长度
* @return 格式化后的字符串
*/
public static String formatRight(String str, int reservedLength){
String name = str.substring(0, reservedLength);
String stars = String.join("", Collections.nCopies(str.length()-reservedLength, "*"));
return name + stars;
}
/**
* 将左边的格式化成*
* @param str 字符串
* @param reservedLength 保留长度
* @return 格式化后的字符串
*/
public static String formatLeft(String str, int reservedLength){
int len = str.length();
String show = str.substring(len-reservedLength);
String stars = String.join("", Collections.nCopies(len-reservedLength, "*"));
return stars + show; | }
/**
* 将中间的格式化成*
* @param str 字符串
* @param beginLen 开始保留长度
* @param endLen 结尾保留长度
* @return 格式化后的字符串
*/
public static String formatBetween(String str, int beginLen, int endLen){
int len = str.length();
String begin = str.substring(0, beginLen);
String end = str.substring(len-endLen);
String stars = String.join("", Collections.nCopies(len-beginLen-endLen, "*"));
return begin + stars + end;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\desensitization\util\SensitiveInfoUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RemoteDevToolsProperties {
public static final String DEFAULT_CONTEXT_PATH = "/.~~spring-boot!~";
public static final String DEFAULT_SECRET_HEADER_NAME = "X-AUTH-TOKEN";
/**
* Context path used to handle the remote connection.
*/
private String contextPath = DEFAULT_CONTEXT_PATH;
/**
* A shared secret required to establish a connection (required to enable remote
* support).
*/
private @Nullable String secret;
/**
* HTTP header used to transfer the shared secret.
*/
private String secretHeaderName = DEFAULT_SECRET_HEADER_NAME;
private final Restart restart = new Restart();
private final Proxy proxy = new Proxy();
public String getContextPath() {
return this.contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public @Nullable String getSecret() {
return this.secret;
}
public void setSecret(@Nullable String secret) {
this.secret = secret;
}
public String getSecretHeaderName() {
return this.secretHeaderName;
}
public void setSecretHeaderName(String secretHeaderName) {
this.secretHeaderName = secretHeaderName;
}
public Restart getRestart() {
return this.restart;
}
public Proxy getProxy() {
return this.proxy;
}
public static class Restart {
/**
* Whether to enable remote restart.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) { | this.enabled = enabled;
}
}
public static class Proxy {
/**
* The host of the proxy to use to connect to the remote application.
*/
private @Nullable String host;
/**
* The port of the proxy to use to connect to the remote application.
*/
private @Nullable Integer port;
public @Nullable String getHost() {
return this.host;
}
public void setHost(@Nullable String host) {
this.host = host;
}
public @Nullable Integer getPort() {
return this.port;
}
public void setPort(@Nullable Integer port) {
this.port = port;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\RemoteDevToolsProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ReportContext build()
{
return new ReportContext(this);
}
public Builder setCtx(final Properties ctx)
{
this.ctx = ctx;
return this;
}
public Builder setAD_Process_ID(final AdProcessId AD_Process_ID)
{
this.AD_Process_ID = AD_Process_ID;
return this;
}
public Builder setPInstanceId(final PInstanceId pinstanceId)
{
this.pinstanceId = pinstanceId;
return this;
}
public Builder setAD_Language(final String AD_Language)
{
this.AD_Language = AD_Language;
return this;
}
public Builder setOutputType(final OutputType outputType)
{
this.outputType = outputType;
return this;
}
public Builder setType(@NonNull final ProcessType type)
{
this.type = type;
return this;
}
public Builder setJSONPath(final String JSONPath)
{
this.JSONPath = JSONPath;
return this;
}
public Builder setRecord(final int AD_Table_ID, final int Record_ID)
{
this.AD_Table_ID = AD_Table_ID;
this.Record_ID = Record_ID;
return this;
}
public Builder setReportTemplatePath(final String reportTemplatePath)
{
this.reportTemplatePath = reportTemplatePath;
return this;
}
public Builder setSQLStatement(final String sqlStatement)
{
this.sqlStatement = sqlStatement;
return this; | }
public Builder setApplySecuritySettings(final boolean applySecuritySettings)
{
this.applySecuritySettings = applySecuritySettings;
return this;
}
private ImmutableList<ProcessInfoParameter> getProcessInfoParameters()
{
return Services.get(IADPInstanceDAO.class).retrieveProcessInfoParameters(pinstanceId)
.stream()
.map(this::transformProcessInfoParameter)
.collect(ImmutableList.toImmutableList());
}
private ProcessInfoParameter transformProcessInfoParameter(final ProcessInfoParameter piParam)
{
//
// Corner case: REPORT_SQL_QUERY
// => replace @AD_PInstance_ID@ placeholder with actual value
if (ReportConstants.REPORT_PARAM_SQL_QUERY.equals(piParam.getParameterName()))
{
final String parameterValue = piParam.getParameterAsString();
if (parameterValue != null)
{
final String parameterValueEffective = parameterValue.replace(ReportConstants.REPORT_PARAM_SQL_QUERY_AD_PInstance_ID_Placeholder, String.valueOf(pinstanceId.getRepoId()));
return ProcessInfoParameter.of(ReportConstants.REPORT_PARAM_SQL_QUERY, parameterValueEffective);
}
}
//
// Default: don't touch the original parameter
return piParam;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\server\ReportContext.java | 2 |
请完成以下Java代码 | class CoreSecurityRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
registerExceptionEventsHints(hints);
registerExpressionEvaluationHints(hints);
registerMethodSecurityHints(hints);
hints.resources().registerResourceBundle("org.springframework.security.messages");
registerDefaultJdbcSchemaFileHint(hints);
registerSecurityContextHints(hints);
}
private void registerMethodSecurityHints(RuntimeHints hints) {
hints.reflection()
.registerType(
TypeReference
.of("org.springframework.security.access.expression.method.MethodSecurityExpressionRoot"),
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
hints.reflection()
.registerType(AbstractAuthenticationToken.class,
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
}
private void registerExpressionEvaluationHints(RuntimeHints hints) {
hints.reflection()
.registerTypes(
List.of(TypeReference.of(SecurityExpressionOperations.class),
TypeReference.of(SecurityExpressionRoot.class)),
(builder) -> builder.withMembers(MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_METHODS));
}
private void registerExceptionEventsHints(RuntimeHints hints) {
hints.reflection()
.registerTypes(getDefaultAuthenticationExceptionEventPublisherTypes(), | (builder) -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
}
private List<TypeReference> getDefaultAuthenticationExceptionEventPublisherTypes() {
return Stream
.of(AuthenticationFailureBadCredentialsEvent.class, AuthenticationFailureCredentialsExpiredEvent.class,
AuthenticationFailureDisabledEvent.class, AuthenticationFailureExpiredEvent.class,
AuthenticationFailureLockedEvent.class, AuthenticationFailureProviderNotFoundEvent.class,
AuthenticationFailureProxyUntrustedEvent.class, AuthenticationFailureServiceExceptionEvent.class,
AuthenticationServiceException.class, AccountExpiredException.class, BadCredentialsException.class,
CredentialsExpiredException.class, DisabledException.class, LockedException.class,
UsernameNotFoundException.class, ProviderNotFoundException.class)
.map(TypeReference::of)
.toList();
}
private void registerDefaultJdbcSchemaFileHint(RuntimeHints hints) {
hints.resources().registerPattern(JdbcDaoImpl.DEFAULT_USER_SCHEMA_DDL_LOCATION);
}
private void registerSecurityContextHints(RuntimeHints hints) {
hints.reflection()
.registerType(SecurityContextImpl.class,
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\aot\hint\CoreSecurityRuntimeHints.java | 1 |
请完成以下Java代码 | public void setTaskId(String taskId) {
startTask(taskId);
}
/**
* @see #associateExecutionById(String)
*/
public void setExecution(Execution execution) {
associateExecutionById(execution.getId());
}
/**
* @see #associateExecutionById(String)
*/
protected void setExecutionId(String executionId) {
associateExecutionById(executionId);
}
/**
* Returns the id of the currently associated process instance or 'null'
*/
public String getProcessInstanceId() {
Execution execution = associationManager.getExecution();
return execution != null ? execution.getProcessInstanceId() : null;
}
/**
* Returns the id of the task associated with the current conversation or 'null'.
*/
public String getTaskId() {
Task task = getTask();
return task != null ? task.getId() : null;
}
/**
* Returns the currently associated {@link Task} or 'null'
*
* @throws ProcessEngineCdiException
* if no {@link Task} is associated. Use {@link #isTaskAssociated()}
* to check whether an association exists.
*
*/
public Task getTask() {
return associationManager.getTask();
}
/**
* Returns the currently associated execution or 'null'
*/
public Execution getExecution() { | return associationManager.getExecution();
}
/**
* @see #getExecution()
*/
public String getExecutionId() {
Execution e = getExecution();
return e != null ? e.getId() : null;
}
/**
* Returns the {@link ProcessInstance} currently associated or 'null'
*
* @throws ProcessEngineCdiException
* if no {@link Execution} is associated. Use
* {@link #isAssociated()} to check whether an association exists.
*/
public ProcessInstance getProcessInstance() {
Execution execution = getExecution();
if(execution != null && !(execution.getProcessInstanceId().equals(execution.getId()))){
return processEngine
.getRuntimeService()
.createProcessInstanceQuery()
.processInstanceId(execution.getProcessInstanceId())
.singleResult();
}
return (ProcessInstance) execution;
}
// internal implementation //////////////////////////////////////////////////////////
protected void assertExecutionAssociated() {
if (associationManager.getExecution() == null) {
throw new ProcessEngineCdiException("No execution associated. Call busniessProcess.associateExecutionById() or businessProcess.startTask() first.");
}
}
protected void assertTaskAssociated() {
if (associationManager.getTask() == null) {
throw new ProcessEngineCdiException("No task associated. Call businessProcess.startTask() first.");
}
}
protected void assertCommandContextNotActive() {
if(Context.getCommandContext() != null) {
throw new ProcessEngineCdiException("Cannot use this method of the BusinessProcess bean from an active command context.");
}
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\BusinessProcess.java | 1 |
请完成以下Java代码 | public void setPP_Order_Qty_ID (final int PP_Order_Qty_ID)
{
if (PP_Order_Qty_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Qty_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Qty_ID, PP_Order_Qty_ID);
}
@Override
public int getPP_Order_Qty_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Qty_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override | public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_PP_Order_Qty.java | 1 |
请完成以下Java代码 | public class Dept implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@Schema(description = "主键")
@TableId(value = "id", type = IdType.ASSIGN_ID)
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
/**
* 租户ID
*/
@Schema(description = "租户ID")
private String tenantId;
/**
* 父主键
*/
@Schema(description = "父主键")
@JsonSerialize(using = ToStringSerializer.class)
private Long parentId;
/**
* 祖级机构主键
*/
@Schema(description = "祖级机构主键")
private String ancestors;
/**
* 部门名
*/
@Schema(description = "部门名")
private String deptName; | /**
* 部门全称
*/
@Schema(description = "部门全称")
private String fullName;
/**
* 排序
*/
@Schema(description = "排序")
private Integer sort;
/**
* 备注
*/
@Schema(description = "备注")
private String remark;
/**
* 是否已删除
*/
@TableLogic
@Schema(description = "是否已删除")
private Integer isDeleted;
} | repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\entity\Dept.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("admin123")).roles("ADMIN")
.and()
.withUser("hamdamboy").password(passwordEncoder().encode("hamdamboy")).roles("USER");
}
/**
* REST control file and folders, especially using specific
* if using ** (double star) that is all files in the existing folder.
* **/
@Override
protected void configure(HttpSecurity http) throws Exception { | http
.authorizeRequests()
.antMatchers("/index").permitAll()
.antMatchers("/profile/**").authenticated()
.antMatchers("/admin/**").hasRole("ADMIN") // Admin
.antMatchers("/management/**").hasAnyRole("ADMIN", "MANAGER")
.antMatchers("/api/public/**").hasRole("ADMIN") // REST condition.
// .antMatchers("/api/public/test1").authenticated()
// .antMatchers("/api/public/test2").authenticated()
.and()
.httpBasic();
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\3. SpringSecureRestControl\src\main\java\spring\security\security\SpringSecurity.java | 2 |
请完成以下Spring Boot application配置 | server.port=80
#Mongo \u914D\u7F6E
spring.data.mongodb.host=192.168.35.128
spring.data.mongodb.port=27017
#spring.data.mongodb.uri=mongodb://192.168.35.128/test
spring.data.mongodb.database=test
#\u65E5\u5FD7\u914D\u7F6E
logging.level.com.xiaolyuh=debug
logging.level.org.springframework.we | b=debug
logging.level.org.springframework.transaction=debug
logging.level.org.springframework.data.mongodb=debug
debug=false | repos\spring-boot-student-master\spring-boot-student-data-mongo\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public Affinity operation(ConnectionSettings.Affinity.Operation operation) {
this.affinity.operation(operation);
return this;
}
public Affinity reuse(boolean reuse) {
this.affinity.reuse(reuse);
return this;
}
public Affinity strategy(ConnectionSettings.AffinityStrategy strategy) {
this.affinity.strategy(strategy);
return this;
}
}
public static final class OAuth2 {
private final OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings;
private OAuth2(OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings) {
this.oAuth2Settings = oAuth2Settings;
}
public OAuth2 tokenEndpointUri(String uri) {
this.oAuth2Settings.tokenEndpointUri(uri);
return this;
}
public OAuth2 clientId(String clientId) {
this.oAuth2Settings.clientId(clientId);
return this;
}
public OAuth2 clientSecret(String clientSecret) {
this.oAuth2Settings.clientSecret(clientSecret);
return this;
}
public OAuth2 grantType(String grantType) {
this.oAuth2Settings.grantType(grantType);
return this;
}
public OAuth2 parameter(String name, String value) {
this.oAuth2Settings.parameter(name, value);
return this;
}
public OAuth2 shared(boolean shared) {
this.oAuth2Settings.shared(shared);
return this;
}
public OAuth2 sslContext(SSLContext sslContext) {
this.oAuth2Settings.tls().sslContext(sslContext);
return this;
} | }
public static final class Recovery {
private final ConnectionBuilder.RecoveryConfiguration recoveryConfiguration;
private Recovery(ConnectionBuilder.RecoveryConfiguration recoveryConfiguration) {
this.recoveryConfiguration = recoveryConfiguration;
}
public Recovery activated(boolean activated) {
this.recoveryConfiguration.activated(activated);
return this;
}
public Recovery backOffDelayPolicy(BackOffDelayPolicy backOffDelayPolicy) {
this.recoveryConfiguration.backOffDelayPolicy(backOffDelayPolicy);
return this;
}
public Recovery topology(boolean activated) {
this.recoveryConfiguration.topology(activated);
return this;
}
}
} | repos\spring-amqp-main\spring-rabbitmq-client\src\main\java\org\springframework\amqp\rabbitmq\client\SingleAmqpConnectionFactory.java | 1 |
请完成以下Java代码 | public void insert(EventLogEntryEntity eventLogEntryEntity) {
getDbSqlSession().insert(eventLogEntryEntity);
}
@SuppressWarnings("unchecked")
public List<EventLogEntry> findAllEventLogEntries() {
return getDbSqlSession().selectList("selectAllEventLogEntries");
}
@SuppressWarnings("unchecked")
public List<EventLogEntry> findEventLogEntries(long startLogNr, long pageSize) {
Map<String, Object> params = new HashMap<>(2);
params.put("startLogNr", startLogNr);
if (pageSize > 0) {
params.put("endLogNr", startLogNr + pageSize + 1);
} | return getDbSqlSession().selectList("selectEventLogEntries", params);
}
@SuppressWarnings("unchecked")
public List<EventLogEntry> findEventLogEntriesByProcessInstanceId(String processInstanceId) {
Map<String, Object> params = new HashMap<>(2);
params.put("processInstanceId", processInstanceId);
return getDbSqlSession().selectList("selectEventLogEntriesByProcessInstanceId", params);
}
public void deleteEventLogEntry(long logNr) {
getDbSqlSession().getSqlSession().delete("deleteEventLogEntry", logNr);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventLogEntryEntityManager.java | 1 |
请完成以下Java代码 | public int height() {
return root == null ? -1 : root.height;
}
private Node insert(Node root, int key) {
if (root == null) {
return new Node(key);
} else if (root.key > key) {
root.left = insert(root.left, key);
} else if (root.key < key) {
root.right = insert(root.right, key);
} else {
throw new RuntimeException("duplicate Key!");
}
return rebalance(root);
}
private Node delete(Node node, int key) {
if (node == null) {
return node;
} else if (node.key > key) {
node.left = delete(node.left, key);
} else if (node.key < key) {
node.right = delete(node.right, key);
} else {
if (node.left == null || node.right == null) {
node = (node.left == null) ? node.right : node.left;
} else {
Node mostLeftChild = mostLeftChild(node.right);
node.key = mostLeftChild.key;
node.right = delete(node.right, node.key);
}
}
if (node != null) {
node = rebalance(node);
}
return node;
}
private Node mostLeftChild(Node node) {
Node current = node;
/* loop down to find the leftmost leaf */
while (current.left != null) {
current = current.left;
}
return current;
}
private Node rebalance(Node z) {
updateHeight(z);
int balance = getBalance(z);
if (balance > 1) {
if (height(z.right.right) > height(z.right.left)) {
z = rotateLeft(z);
} else {
z.right = rotateRight(z.right);
z = rotateLeft(z);
}
} else if (balance < -1) {
if (height(z.left.left) > height(z.left.right)) {
z = rotateRight(z);
} else { | z.left = rotateLeft(z.left);
z = rotateRight(z);
}
}
return z;
}
private Node rotateRight(Node y) {
Node x = y.left;
Node z = x.right;
x.right = y;
y.left = z;
updateHeight(y);
updateHeight(x);
return x;
}
private Node rotateLeft(Node y) {
Node x = y.right;
Node z = x.left;
x.left = y;
y.right = z;
updateHeight(y);
updateHeight(x);
return x;
}
private void updateHeight(Node n) {
n.height = 1 + Math.max(height(n.left), height(n.right));
}
private int height(Node n) {
return n == null ? -1 : n.height;
}
public int getBalance(Node n) {
return (n == null) ? 0 : height(n.right) - height(n.left);
}
} | repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\avltree\AVLTree.java | 1 |
请完成以下Java代码 | public List<String> queryUsernameByIds(List<String> userIds) {
return List.of();
}
@Override
public List<String> queryUsernameByDepartPositIds(List<String> positionIds) {
return null;
}
@Override
public List<String> queryUserIdsByPositionIds(List<String> positionIds) {
return null;
}
@Override
public List<String> getUserAccountsByDepCode(String orgCode) {
return null;
}
@Override
public boolean dictTableWhiteListCheckBySql(String selectSql) {
return false;
}
@Override
public boolean dictTableWhiteListCheckByDict(String tableOrDictCode, String... fields) {
return false;
}
@Override
public void announcementAutoRelease(String dataId, String currentUserName) {
}
@Override
public SysDepartModel queryCompByOrgCode(String orgCode) {
return null;
}
@Override
public SysDepartModel queryCompByOrgCodeAndLevel(String orgCode, Integer level) { | return null;
}
@Override
public Object runAiragFlow(AiragFlowDTO airagFlowDTO) {
return null;
}
@Override
public void uniPushMsgToUser(PushMessageDTO pushMessageDTO) {
}
@Override
public String getDepartPathNameByOrgCode(String orgCode, String depId) {
return "";
}
@Override
public List<String> queryUserIdsByCascadeDeptIds(List<String> deptIds) {
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-api\jeecg-system-cloud-api\src\main\java\org\jeecg\common\system\api\fallback\SysBaseAPIFallback.java | 1 |
请完成以下Java代码 | public class GetDeploymentResourceCmd implements Command<InputStream>, Serializable {
private static final long serialVersionUID = 1L;
protected String deploymentId;
protected String resourceName;
public GetDeploymentResourceCmd(String deploymentId, String resourceName) {
this.deploymentId = deploymentId;
this.resourceName = resourceName;
}
@Override
public InputStream execute(CommandContext commandContext) {
if (deploymentId == null) {
throw new FlowableIllegalArgumentException("deploymentId is null");
}
if (resourceName == null) { | throw new FlowableIllegalArgumentException("resourceName is null");
}
DmnResourceEntity resource = CommandContextUtil.getResourceEntityManager().findResourceByDeploymentIdAndResourceName(deploymentId, resourceName);
if (resource == null) {
if (CommandContextUtil.getDeploymentEntityManager(commandContext).findById(deploymentId) == null) {
throw new FlowableObjectNotFoundException("deployment does not exist: " + deploymentId);
} else {
throw new FlowableObjectNotFoundException("no resource found with name '" + resourceName + "' in deployment '" + deploymentId + "'");
}
}
return new ByteArrayInputStream(resource.getBytes());
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\cmd\GetDeploymentResourceCmd.java | 1 |
请完成以下Java代码 | public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Total Quantity.
@param TotalQty
Total Quantity
*/
public void setTotalQty (BigDecimal TotalQty)
{
set_Value (COLUMNNAME_TotalQty, TotalQty);
}
/** Get Total Quantity.
@return Total Quantity
*/
public BigDecimal getTotalQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalQty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionRunLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomUserDetailsService implements UserDetailsService {
Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);
@Autowired
private UserRepository userRepository;
public CustomUserDetailsService() {
super();
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
User user = userRepository.findByUsername(username);
if (user != null) return new CustomUserDetails(user, getAuthorities(user)); | } catch (Exception ex) {
log.error("Exception in CustomUserDetailsService: " + ex);
}
return null;
}
private Collection<GrantedAuthority> getAuthorities(User user) {
Collection<GrantedAuthority> authorities = new HashSet<>();
for (Role role : user.getRoles()) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRole());
authorities.add(grantedAuthority);
}
return authorities;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsecuredsockets\security\CustomUserDetailsService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void updateTask(TaskEntity taskEntity, boolean fireUpdateEvent) {
getTaskEntityManager().update(taskEntity, fireUpdateEvent);
}
@Override
public void updateAllTaskRelatedEntityCountFlags(boolean configProperty) {
getTaskEntityManager().updateAllTaskRelatedEntityCountFlags(configProperty);
}
@Override
public TaskEntity createTask() {
return getTaskEntityManager().create();
}
@Override
public void insertTask(TaskEntity taskEntity, boolean fireCreateEvent) {
getTaskEntityManager().insert(taskEntity, fireCreateEvent);
}
@Override
public void deleteTask(TaskEntity task, boolean fireEvents) { | getTaskEntityManager().delete(task, fireEvents);
}
@Override
public void deleteTasksByExecutionId(String executionId) {
getTaskEntityManager().deleteTasksByExecutionId(executionId);
}
public TaskEntityManager getTaskEntityManager() {
return configuration.getTaskEntityManager();
}
@Override
public TaskEntity createTask(TaskBuilder taskBuilder) {
return getTaskEntityManager().createTask(taskBuilder);
}
protected VariableServiceConfiguration getVariableServiceConfiguration(AbstractEngineConfiguration engineConfiguration) {
return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG);
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskServiceImpl.java | 2 |
请完成以下Java代码 | public HistoryCleanupJobHandlerConfiguration getConfiguration() {
return configuration;
}
public HistoryCleanupHandler setConfiguration(HistoryCleanupJobHandlerConfiguration configuration) {
this.configuration = configuration;
return this;
}
public HistoryCleanupHandler setJobId(String jobId) {
this.jobId = jobId;
return this;
}
public HistoryCleanupHandler setCommandExecutor(CommandExecutor commandExecutor) {
this.commandExecutor = commandExecutor; | return this;
}
protected class HistoryCleanupHandlerCmd implements Command<Void> {
@Override
public Void execute(CommandContext commandContext) {
Map<String, Long> report = reportMetrics();
boolean isRescheduleNow = shouldRescheduleNow();
new HistoryCleanupSchedulerCmd(isRescheduleNow, report, configuration, jobId).execute(commandContext);
return null;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupHandler.java | 1 |
请完成以下Java代码 | public class SocialController {
private final SocialProperties socialProperties;
/**
* 授权完毕跳转
*/
@Operation(summary = "授权完毕跳转")
@RequestMapping("/oauth/render/{source}")
public void renderAuth(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
AuthRequest authRequest = SocialUtil.getAuthRequest(source, socialProperties);
String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
response.sendRedirect(authorizeUrl);
}
/**
* 获取认证信息
*/
@Operation(summary = "获取认证信息")
@RequestMapping("/oauth/callback/{source}")
public Object login(@PathVariable("source") String source, AuthCallback callback) {
AuthRequest authRequest = SocialUtil.getAuthRequest(source, socialProperties);
return authRequest.login(callback);
}
/**
* 撤销授权
*/
@Operation(summary = "撤销授权")
@RequestMapping("/oauth/revoke/{source}/{token}") | public Object revokeAuth(@PathVariable("source") String source, @PathVariable("token") String token) {
AuthRequest authRequest = SocialUtil.getAuthRequest(source, socialProperties);
return authRequest.revoke(AuthToken.builder().accessToken(token).build());
}
/**
* 续期accessToken
*/
@Operation(summary = "续期令牌")
@RequestMapping("/oauth/refresh/{source}")
public Object refreshAuth(@PathVariable("source") String source, String token) {
AuthRequest authRequest = SocialUtil.getAuthRequest(source, socialProperties);
return authRequest.refresh(AuthToken.builder().refreshToken(token).build());
}
} | repos\SpringBlade-master\blade-auth\src\main\java\org\springblade\auth\controller\SocialController.java | 1 |
请完成以下Java代码 | public void onResourceTypeChanged(final I_S_ResourceType resourceTypeRecord)
{
final Set<ResourceId> resourceIds = queryBL
.createQueryBuilder(I_S_Resource.class) // in trx!
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_Resource.COLUMNNAME_S_ResourceType_ID, resourceTypeRecord.getS_ResourceType_ID())
.create()
.idsAsSet(ResourceId::ofRepoId);
if (resourceIds.isEmpty())
{
return;
}
final ResourceType resourceType = toResourceType(resourceTypeRecord);
final IProductDAO productsRepo = Services.get(IProductDAO.class);
productsRepo.updateProductsByResourceIds(resourceIds, product -> updateProductFromResourceType(product, resourceType));
}
private void updateProductFromResourceType(final I_M_Product product, final ResourceType from)
{
product.setProductType(X_M_Product.PRODUCTTYPE_Resource);
product.setC_UOM_ID(from.getDurationUomId().getRepoId());
product.setM_Product_Category_ID(ProductCategoryId.toRepoId(from.getProductCategoryId()));
}
@Override
public ImmutableSet<ResourceId> getResourceIdsByUserId(@NonNull final UserId userId)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
return queryBL.createQueryBuilder(I_S_Resource.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_Resource.COLUMNNAME_AD_User_ID, userId)
.create()
.idsAsSet(ResourceId::ofRepoId);
}
@Override
public ImmutableSet<ResourceId> getResourceIdsByResourceTypeIds(@NonNull final Collection<ResourceTypeId> resourceTypeIds)
{ | if (resourceTypeIds.isEmpty())
{
return ImmutableSet.of();
}
final IQueryBL queryBL = Services.get(IQueryBL.class);
return queryBL.createQueryBuilder(I_S_Resource.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_S_Resource.COLUMNNAME_S_ResourceType_ID, resourceTypeIds)
.create()
.idsAsSet(ResourceId::ofRepoId);
}
@Override
public ImmutableSet<ResourceId> getActivePlantIds()
{
return queryBL.createQueryBuilder(I_S_Resource.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_Resource.COLUMNNAME_ManufacturingResourceType, X_S_Resource.MANUFACTURINGRESOURCETYPE_Plant)
.create()
.idsAsSet(ResourceId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\impl\ResourceDAO.java | 1 |
请完成以下Java代码 | public int calculateDurationDays(final PPRoutingId routingId, @Nullable final ResourceId plantId, final BigDecimal qty)
{
if (plantId == null)
{
return 0;
}
Duration durationTotal = Duration.ZERO;
final PPRouting routing = Services.get(IPPRoutingRepository.class).getById(routingId);
final int intQty = qty.setScale(0, RoundingMode.UP).intValueExact();
for (final PPRoutingActivity activity : routing.getActivities())
{
// Qty independent times:
durationTotal = durationTotal
.plus(activity.getQueuingTime())
.plus(activity.getSetupTime())
.plus(activity.getWaitingTime())
.plus(activity.getMovingTime());
// Get OverlapUnits - number of units that must be completed before they are moved the next activity
final int overlapUnits = Integer.max(activity.getOverlapUnits(), 0);
final int batchUnits = Integer.max(intQty - overlapUnits, 0);
final Duration durationBeforeOverlap = activity.getDurationPerOneUnit().multipliedBy(batchUnits); | durationTotal = durationTotal.plus(durationBeforeOverlap);
}
//
final IResourceProductService resourceProductService = Services.get(IResourceProductService.class);
final ResourceType resourceType = resourceProductService.getResourceTypeByResourceId(plantId);
final BigDecimal availableDayTimeInHours = BigDecimal.valueOf(resourceType.getTimeSlotInHours());
final int availableDays = resourceType.getAvailableDaysPerWeek();
// Weekly Factor
final BigDecimal weeklyFactor = BigDecimal.valueOf(7).divide(BigDecimal.valueOf(availableDays), 8, RoundingMode.UP);
return BigDecimal.valueOf(durationTotal.toHours())
.multiply(weeklyFactor)
.divide(availableDayTimeInHours, 0, RoundingMode.UP)
.intValueExact();
}
@Override
public Duration getResourceBaseValue(@NonNull final PPRoutingActivity activity)
{
return calculateDuration(activity);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\impl\DefaultRoutingServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Cctop140V other = (Cctop140V)obj;
if (cInvoiceID == null)
{
if (other.cInvoiceID != null)
{
return false;
}
}
else if (!cInvoiceID.equals(other.cInvoiceID))
{
return false;
}
if (discount == null)
{
if (other.discount != null)
{
return false;
}
}
else if (!discount.equals(other.discount))
{
return false;
}
if (discountDate == null)
{
if (other.discountDate != null)
{
return false;
}
}
else if (!discountDate.equals(other.discountDate))
{
return false;
}
if (discountDays == null)
{ | if (other.discountDays != null)
{
return false;
}
}
else if (!discountDays.equals(other.discountDays))
{
return false;
}
if (rate == null)
{
if (other.rate != null)
{
return false;
}
}
else if (!rate.equals(other.rate))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "Cctop140V [cInvoiceID=" + cInvoiceID + ", discount=" + discount + ", discountDate=" + discountDate + ", discountDays=" + discountDays + ", rate=" + rate + "]";
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop140V.java | 2 |
请完成以下Java代码 | public Authentication getAuthenticationForProcessEngine(String engineName) {
return authentications.get(engineName);
}
/**
* Adds an authentication to the list of current authentications. If there already
* exists an authentication of the same process engine, it is replaced silently.
*
* @param authentication the authentication to add
*/
public void addOrReplace(UserAuthentication authentication) {
authentications.put(authentication.getProcessEngineName(), authentication);
}
/**
* Removes the authentication for the provided process engine name.
*
* @param engineName the name of the process engine for which the authentication should
* be removed.
* @return the removed user authentication
*/
public UserAuthentication removeByEngineName(String engineName) {
return authentications.remove(engineName);
}
/**
* @return all active {@link Authentication Authentications}.
*/
public List<UserAuthentication> getAuthentications() {
return new ArrayList<>(authentications.values());
}
/**
* Allows checking whether a user is currently authenticated for a given process engine name.
*
* @param engineName the name of the process engine for which we want to check for authentication.
* @return true if a user is authenticated for the provided process engine name.
*/
public boolean hasAuthenticationForProcessEngine(String engineName) {
return getAuthenticationForProcessEngine(engineName) != null;
}
// thread-local ////////////////////////////////////////////////////////// | /**
* sets the {@link Authentications} for the current thread in a thread local.
*
* @param auth the {@link Authentications} to set.
*/
public static void setCurrent(Authentications auth) {
currentAuthentications.set(auth);
}
/**
* clears the {@link Authentications} for the current thread.
*/
public static void clearCurrent() {
currentAuthentications.remove();
}
/**
* Returns the authentications for the current thread.
*
* @return the authentications.
*/
public static Authentications getCurrent() {
return currentAuthentications.get();
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\Authentications.java | 1 |
请完成以下Java代码 | public List<JsonDocument> findTopGradesByCourse(String course, int limit) {
ViewQuery query = queryBuilder.findTopGradesByCourse(course, limit);
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
public Map<String, Long> countStudentsByCourse() {
ViewQuery query = ViewQuery.from("studentGrades", "countStudentsByCourse")
.reduce()
.groupLevel(1);
ViewResult result = bucket.query(query);
Map<String, Long> numStudentsByCourse = new HashMap<>();
for(ViewRow row : result.allRows()) {
JsonArray keyArray = (JsonArray) row.key();
String course = keyArray.getString(0);
long count = Long.valueOf(row.value().toString());
numStudentsByCourse.put(course, count);
}
return numStudentsByCourse;
}
public Map<String, Long> sumCreditHoursByStudent() {
ViewQuery query = ViewQuery.from("studentGrades", "sumHoursByStudent")
.reduce()
.groupLevel(1);
ViewResult result = bucket.query(query);
Map<String, Long> creditHoursByStudent = new HashMap<>();
for(ViewRow row : result.allRows()) {
String course = (String) row.key();
long sum = Long.valueOf(row.value().toString());
creditHoursByStudent.put(course, sum);
}
return creditHoursByStudent;
}
public Map<String, Long> sumGradePointsByStudent() {
ViewQuery query = ViewQuery.from("studentGrades", "sumGradePointsByStudent")
.reduce()
.groupLevel(1);
ViewResult result = bucket.query(query);
Map<String, Long> gradePointsByStudent = new HashMap<>(); | for(ViewRow row : result.allRows()) {
String course = (String) row.key();
long sum = Long.valueOf(row.value().toString());
gradePointsByStudent.put(course, sum);
}
return gradePointsByStudent;
}
public Map<String, Float> calculateGpaByStudent() {
Map<String, Long> creditHoursByStudent = sumCreditHoursByStudent();
Map<String, Long> gradePointsByStudent = sumGradePointsByStudent();
Map<String, Float> result = new HashMap<>();
for(Entry<String, Long> creditHoursEntry : creditHoursByStudent.entrySet()) {
String name = creditHoursEntry.getKey();
long totalHours = creditHoursEntry.getValue();
long totalGradePoints = gradePointsByStudent.get(name);
result.put(name, ((float) totalGradePoints / totalHours));
}
return result;
}
} | repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\mapreduce\StudentGradeService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User extends AbstractPersistable<Long> {
private static final long serialVersionUID = -2952735933715107252L;
@Column(unique = true) private String username;
private String firstname;
private String lastname;
public User() {
this(null);
}
/**
* Creates a new user instance.
*/
private User(Long id) {
this.setId(id);
}
/**
* Returns the username.
*
* @return
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the firstname
*/
public String getFirstname() {
return firstname;
} | /**
* @param firstname the firstname to set
*/
public void setFirstname(String firstname) {
this.firstname = firstname;
}
/**
* @return the lastname
*/
public String getLastname() {
return lastname;
}
/**
* @param lastname the lastname to set
*/
public void setLastname(String lastname) {
this.lastname = lastname;
}
} | repos\spring-data-examples-main\jpa\example\src\main\java\example\springdata\jpa\caching\User.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((comment == null) ? 0 : comment.hashCode());
result = prime * result + ((posted == null) ? 0 : posted.hashCode());
result = prime * result + ((taskId == null) ? 0 : taskId.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CommentDTO other = (CommentDTO) obj;
if (comment == null) {
if (other.comment != null)
return false;
} else if (!comment.equals(other.comment))
return false;
if (posted == null) {
if (other.posted != null)
return false;
} else if (!posted.equals(other.posted))
return false;
if (taskId == null) {
if (other.taskId != null)
return false;
} else if (!taskId.equals(other.taskId))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString() | */
@Override
public String toString() {
return "CommentDTO [taskId=" + taskId + ", comment=" + comment + ", posted=" + posted + "]";
}
}
/**
* Custom date serializer that converts the date to long before sending it out
*
* @author anilallewar
*
*/
class CustomDateToLongSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeNumber(value.getTime());
}
} | repos\spring-boot-microservices-master\comments-webservice\src\main\java\com\rohitghatol\microservices\comments\dtos\CommentDTO.java | 2 |
请完成以下Java代码 | public final Date getLatestDateAcct()
{
Date latestDateAcct = null;
for (final IAllocableDocRow row : getRowsInnerList())
{
if (!row.isSelected())
{
continue;
}
final Date dateAcct = row.getDateAcct();
latestDateAcct = TimeUtil.max(latestDateAcct, dateAcct);
}
return latestDateAcct;
} | public final List<ModelType> getRowsSelected()
{
return FluentIterable.from(getRowsInnerList())
.filter(IAllocableDocRow.PREDICATE_Selected)
.toList();
}
public final List<ModelType> getRowsSelectedNoTaboo()
{
return FluentIterable.from(getRowsInnerList())
.filter(IAllocableDocRow.PREDICATE_Selected)
.filter(IAllocableDocRow.PREDICATE_NoTaboo)
.toList();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\AbstractAllocableDocTableModel.java | 1 |
请完成以下Java代码 | public static final class SimpleElement {
/**
* Element title.
*/
private String title;
/**
* Element description.
*/
private String description;
/**
* Element default value.
*/
private String value;
/**
* Create a new instance with the given value.
* @param value the value
*/
public SimpleElement(String value) {
this.value = value;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getValue() {
return this.value; | }
public void setValue(String value) {
this.value = value;
}
public void apply(TextCapability capability) {
if (StringUtils.hasText(this.title)) {
capability.setTitle(this.title);
}
if (StringUtils.hasText(this.description)) {
capability.setDescription(this.description);
}
if (StringUtils.hasText(this.value)) {
capability.setContent(this.value);
}
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrProperties.java | 1 |
请完成以下Java代码 | public String getRuleName() {
return ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
public String getRuleColumn() {
return ruleColumn;
}
public void setRuleColumn(String ruleColumn) {
this.ruleColumn = ruleColumn;
}
public String getRuleConditions() {
return ruleConditions;
}
public void setRuleConditions(String ruleConditions) {
this.ruleConditions = ruleConditions;
}
public String getRuleValue() {
return ruleValue;
}
public void setRuleValue(String ruleValue) {
this.ruleValue = ruleValue;
}
public Date getCreateTime() { | return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysPermissionDataRuleModel.java | 1 |
请完成以下Java代码 | public class DeleteProcessInstanceCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected String processInstanceId;
protected String deleteReason;
public DeleteProcessInstanceCmd(String processInstanceId, String deleteReason) {
this.processInstanceId = processInstanceId;
this.deleteReason = deleteReason;
}
public Void execute(CommandContext commandContext) {
if (processInstanceId == null) {
throw new ActivitiIllegalArgumentException("processInstanceId is null");
}
ExecutionEntity processInstanceEntity = commandContext.getExecutionEntityManager().findById(processInstanceId);
if (processInstanceEntity == null) { | throw new ActivitiObjectNotFoundException(
"No process instance found for id '" + processInstanceId + "'",
ProcessInstance.class
);
}
executeInternal(commandContext, processInstanceEntity);
return null;
}
protected void executeInternal(CommandContext commandContext, ExecutionEntity processInstanceEntity) {
commandContext
.getExecutionEntityManager()
.deleteProcessInstance(processInstanceEntity.getProcessInstanceId(), deleteReason, false);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteProcessInstanceCmd.java | 1 |
请完成以下Java代码 | public void updateNameIfNotSet(final I_C_PaySelection paySelection)
{
final StringBuilder name = new StringBuilder();
if (paySelection.getPayDate() != null)
{
final DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
final String formattedDate = dateFormat.format(paySelection.getPayDate());
name.append(formattedDate);
}
if (name.length() > 0)
{
name.append("_");
}
final BankAccountId bankAccountId = BankAccountId.ofRepoIdOrNull(paySelection.getC_BP_BankAccount_ID());
if (bankAccountId != null)
{ | final String bankAccountName = bankAccountService.createBankAccountName(bankAccountId);
name.append(bankAccountName);
}
if (name.length() > 0 && !paySelection.getName().startsWith(name.toString()))
{
paySelection.setName(name.toString());
}
}
// TODO: Fix this in the followup https://github.com/metasfresh/metasfresh/issues/2841
// @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
// public void createPayments(final I_C_PaySelection paySelection)
// {
// Services.get(IPaySelectionBL.class).createPayments(paySelection);
// }
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\modelvalidator\C_PaySelection.java | 1 |
请完成以下Java代码 | public void setExternalSystem_Config_ProCareManagement_LocalFile_ID (final int ExternalSystem_Config_ProCareManagement_LocalFile_ID)
{
if (ExternalSystem_Config_ProCareManagement_LocalFile_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ProCareManagement_LocalFile_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ProCareManagement_LocalFile_ID, ExternalSystem_Config_ProCareManagement_LocalFile_ID);
}
@Override
public int getExternalSystem_Config_ProCareManagement_LocalFile_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ProCareManagement_LocalFile_ID);
}
@Override
public void setFrequency (final int Frequency)
{
set_Value (COLUMNNAME_Frequency, Frequency);
}
@Override
public int getFrequency()
{
return get_ValueAsInt(COLUMNNAME_Frequency);
}
@Override
public void setLocalRootLocation (final String LocalRootLocation)
{
set_Value (COLUMNNAME_LocalRootLocation, LocalRootLocation);
}
@Override
public String getLocalRootLocation()
{
return get_ValueAsString(COLUMNNAME_LocalRootLocation);
}
@Override
public void setProcessedDirectory (final String ProcessedDirectory)
{
set_Value (COLUMNNAME_ProcessedDirectory, ProcessedDirectory);
}
@Override
public String getProcessedDirectory()
{
return get_ValueAsString(COLUMNNAME_ProcessedDirectory); | }
@Override
public void setProductFileNamePattern (final @Nullable String ProductFileNamePattern)
{
set_Value (COLUMNNAME_ProductFileNamePattern, ProductFileNamePattern);
}
@Override
public String getProductFileNamePattern()
{
return get_ValueAsString(COLUMNNAME_ProductFileNamePattern);
}
@Override
public void setPurchaseOrderFileNamePattern (final @Nullable String PurchaseOrderFileNamePattern)
{
set_Value (COLUMNNAME_PurchaseOrderFileNamePattern, PurchaseOrderFileNamePattern);
}
@Override
public String getPurchaseOrderFileNamePattern()
{
return get_ValueAsString(COLUMNNAME_PurchaseOrderFileNamePattern);
}
@Override
public void setWarehouseFileNamePattern (final @Nullable String WarehouseFileNamePattern)
{
set_Value (COLUMNNAME_WarehouseFileNamePattern, WarehouseFileNamePattern);
}
@Override
public String getWarehouseFileNamePattern()
{
return get_ValueAsString(COLUMNNAME_WarehouseFileNamePattern);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ProCareManagement_LocalFile.java | 1 |
请完成以下Java代码 | public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU)
{
set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU);
}
@Override
public void setPickFrom_HU_ID (final int PickFrom_HU_ID)
{
if (PickFrom_HU_ID < 1)
set_Value (COLUMNNAME_PickFrom_HU_ID, null);
else
set_Value (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID);
}
@Override
public int getPickFrom_HU_ID() | {
return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID);
}
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step_PickedHU.java | 1 |
请完成以下Java代码 | public void afterReverseCorrect(final I_M_Inventory inventory)
{
if (inventoryService.isMaterialDisposal(inventory))
{
restoreHUsFromSnapshots(inventory);
reverseEmptiesMovements(inventory);
}
}
private void restoreHUsFromSnapshots(final I_M_Inventory inventory)
{
final String snapshotId = inventory.getSnapshot_UUID();
if (Check.isBlank(snapshotId))
{
throw new HUException("@NotFound@ @Snapshot_UUID@ (" + inventory + ")");
}
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
final List<Integer> topLevelHUIds = inventoryDAO.retrieveLinesForInventoryId(inventoryId, I_M_InventoryLine.class)
.stream()
.map(I_M_InventoryLine::getM_HU_ID)
.collect(ImmutableList.toImmutableList());
huSnapshotDAO.restoreHUs()
.setContext(PlainContextAware.newWithThreadInheritedTrx())
.setSnapshotId(snapshotId)
.setDateTrx(inventory.getMovementDate()) | .addModelIds(topLevelHUIds)
.setReferencedModel(inventory)
.restoreFromSnapshot();
}
private void reverseEmptiesMovements(final I_M_Inventory inventory)
{
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
movementDAO.retrieveMovementsForInventoryQuery(inventoryId)
.addEqualsFilter(I_M_Inventory.COLUMNNAME_DocStatus, X_M_Inventory.DOCSTATUS_Completed)
.create()
.stream()
.forEach(emptiesMovement -> documentBL.processEx(emptiesMovement, X_M_Movement.DOCACTION_Reverse_Correct, X_M_Movement.DOCSTATUS_Reversed));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\interceptor\M_Inventory.java | 1 |
请完成以下Java代码 | public class RestrictedFinancialIdentificationSEPA {
@XmlElement(name = "Id", required = true)
@XmlSchemaType(name = "string")
protected RestrictedSMNDACode id;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link RestrictedSMNDACode }
*
*/
public RestrictedSMNDACode getId() { | return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link RestrictedSMNDACode }
*
*/
public void setId(RestrictedSMNDACode value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\RestrictedFinancialIdentificationSEPA.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private OAuthAccessToken fetchNewAccessToken(@NonNull final OAuthAccessTokenRequest request)
{
try
{
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON));
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
final Map<String, String> formData = createFormData(request);
final ResponseEntity<String> response = restTemplate.postForEntity(
request.getIdentity().getTokenUrl(),
new HttpEntity<>(jsonObjectMapper.writeValueAsString(formData), httpHeaders),
String.class);
final JsonNode jsonNode = jsonObjectMapper.readTree(response.getBody());
final String accessToken = jsonNode.get("bearer").asText();
return OAuthAccessToken.of(accessToken, now().plus(EXPIRING_DURATION));
}
catch (final JsonProcessingException e)
{
throw new RuntimeCamelException("Failed to parse OAuth token response", e);
}
}
@NonNull
private static Map<String, String> createFormData(@NonNull final OAuthAccessTokenRequest request)
{
final Map<String, String> formData = new HashMap<>();
if (Check.isNotBlank(request.getIdentity().getClientId()))
{
formData.put("client_id", request.getIdentity().getClientId());
}
if (Check.isNotBlank(request.getClientSecret()))
{
formData.put("client_secret", request.getClientSecret());
} | if (Check.isNotBlank(request.getIdentity().getUsername()))
{
formData.put("email", request.getIdentity().getUsername());
}
if (Check.isNotBlank(request.getPassword()))
{
formData.put("password", request.getPassword());
}
return formData;
}
@Value
@Builder
private static class CacheKey
{
@NonNull String tokenUrl;
@Nullable String clientId;
@Nullable String username;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-scriptedadapter\src\main\java\de\metas\camel\externalsystems\scriptedadapter\oauth\OAuthTokenManager.java | 2 |
请完成以下Java代码 | private void showRecordInfo()
{
if (m_dse == null)
{
return;
}
final int adTableId = m_dse.getAdTableId();
final ComposedRecordId recordId = m_dse.getRecordId();
if (adTableId <= 0 || recordId == null)
{
return;
}
if (!Env.getUserRolePermissions().isShowPreference()) | {
return;
}
//
final RecordInfo info = new RecordInfo(SwingUtils.getFrame(this), adTableId, recordId);
AEnv.showCenterScreen(info);
}
public void removeBorders()
{
statusLine.setBorder(BorderFactory.createEmptyBorder());
statusDB.setBorder(BorderFactory.createEmptyBorder());
infoLine.setBorder(BorderFactory.createEmptyBorder());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\StatusBar.java | 1 |
请完成以下Java代码 | public boolean isInfiniteQtyTUsPerLU()
{
return false;
}
@Override
public BigDecimal getQtyTUsPerLU()
{
final I_M_HU_Item parentHUItem = aggregatedTU.getM_HU_Item_Parent();
if (parentHUItem == null)
{
// note: shall not happen because we assume the aggregatedTU is really an aggregated TU.
new HUException("Invalid aggregated TU. Parent item is null; aggregatedTU=" + aggregatedTU).throwIfDeveloperModeOrLogWarningElse(logger);
return null;
}
return parentHUItem.getQty();
}
@Override
public boolean isInfiniteQtyCUsPerTU()
{
return false;
}
@Override
public BigDecimal getQtyCUsPerTU()
{
final IHUProductStorage huProductStorage = getHUProductStorage();
if (huProductStorage == null)
{
return null;
}
final BigDecimal qtyTUsPerLU = getQtyTUsPerLU();
if (qtyTUsPerLU == null || qtyTUsPerLU.signum() == 0)
{
return null;
} | final BigDecimal qtyCUTotal = huProductStorage.getQty().toBigDecimal();
final BigDecimal qtyCUsPerTU = qtyCUTotal.divide(qtyTUsPerLU, 0, RoundingMode.HALF_UP);
return qtyCUsPerTU;
}
@Override
public I_C_UOM getQtyCUsPerTU_UOM()
{
final IHUProductStorage huProductStorage = getHUProductStorage();
if (huProductStorage == null)
{
return null;
}
return huProductStorage.getC_UOM();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\AggregatedTUPackingInfo.java | 1 |
请完成以下Java代码 | protected JobDefinitionManager getJobDefinitionManager() {
return getCommandContext().getJobDefinitionManager();
}
protected EventSubscriptionManager getEventSubscriptionManager() {
return getCommandContext().getEventSubscriptionManager();
}
protected ProcessDefinitionManager getProcessDefinitionManager() {
return getCommandContext().getProcessDefinitionManager();
}
// getters/setters ///////////////////////////////////////////////////////////////////////////////////
public ExpressionManager getExpressionManager() {
return expressionManager; | }
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
public BpmnParser getBpmnParser() {
return bpmnParser;
}
public void setBpmnParser(BpmnParser bpmnParser) {
this.bpmnParser = bpmnParser;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\deployer\BpmnDeployer.java | 1 |
请完成以下Java代码 | protected List<String> getValueAsList(String name, JsonNode objectNode) {
List<String> resultList = new ArrayList<String>();
JsonNode valuesNode = objectNode.get(name);
if (valuesNode != null) {
for (JsonNode valueNode : valuesNode) {
if (valueNode.get("value") != null && !valueNode.get("value").isNull()) {
resultList.add(valueNode.get("value").asText());
}
}
}
return resultList;
}
protected void addField(String name, JsonNode elementNode, ServiceTask task) {
FieldExtension field = new FieldExtension();
field.setFieldName(name.substring(8));
String value = getPropertyValueAsString(name, elementNode);
if (StringUtils.isNotEmpty(value)) {
if ((value.contains("${") || value.contains("#{")) && value.contains("}")) {
field.setExpression(value);
} else {
field.setStringValue(value);
}
task.getFieldExtensions().add(field);
}
}
protected void addField(String name, String propertyName, JsonNode elementNode, ServiceTask task) {
FieldExtension field = new FieldExtension();
field.setFieldName(name);
String value = getPropertyValueAsString(propertyName, elementNode);
if (StringUtils.isNotEmpty(value)) {
if ((value.contains("${") || value.contains("#{")) && value.contains("}")) {
field.setExpression(value);
} else {
field.setStringValue(value);
}
task.getFieldExtensions().add(field);
}
}
protected String getPropertyValueAsString(String name, JsonNode objectNode) {
return JsonConverterUtil.getPropertyValueAsString(name, objectNode); | }
protected boolean getPropertyValueAsBoolean(String name, JsonNode objectNode) {
return JsonConverterUtil.getPropertyValueAsBoolean(name, objectNode);
}
protected List<String> getPropertyValueAsList(String name, JsonNode objectNode) {
return JsonConverterUtil.getPropertyValueAsList(name, objectNode);
}
protected JsonNode getProperty(String name, JsonNode objectNode) {
return JsonConverterUtil.getProperty(name, objectNode);
}
protected String convertListToCommaSeparatedString(List<String> stringList) {
String resultString = null;
if (stringList != null && stringList.size() > 0) {
StringBuilder expressionBuilder = new StringBuilder();
for (String singleItem : stringList) {
if (expressionBuilder.length() > 0) {
expressionBuilder.append(",");
}
expressionBuilder.append(singleItem);
}
resultString = expressionBuilder.toString();
}
return resultString;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\BaseBpmnJsonConverter.java | 1 |
请完成以下Java代码 | public void deleteC_Invoice_Candidates(final I_M_InOutLine inOutLine)
{
Services.get(IInvoiceCandDAO.class).deleteAllReferencingInvoiceCandidates(inOutLine);
}
/**
* If the given <code>inoutline</code> does not reference an order, then the method does nothing. <br>
* Otherwise, it iterates that orderLine's <code>C_Invoice_Candidate</code>s and creates <code>C_InvoiceCandidate_InOutLine</code> records.
* <p>
* Also, it updates for each <code>C_Invoice_Candidate</code> of the given <code>inOutLine</code>'s order line:
* <ul>
* <li>QualityDiscountPercent
* <li>QualityDiscountPercent_Override to zero if <code>QualityDiscountPercent</code> was changed
* <li>IsInDispute to <code>true</code> if QualityDiscountPercent was changed to a value > 0
* </ul>
* Also invalidates all ICs that have the given IC's header aggregation key.
*
* @param inOutLine
*/
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW })
public void createC_InvoiceCandidate_InOutLines(final I_M_InOutLine inOutLine)
{
final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class);
final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class);
//
// Get Order Line
final OrderLineId orderLineId = OrderLineId.ofRepoIdOrNull(inOutLine.getC_OrderLine_ID());
if (orderLineId == null)
{
return; // nothing to do
}
//
// Iterate all invoice candidates linked to our order line | // * create link between invoice candidate and our inout line
for (final I_C_Invoice_Candidate icRecord : invoiceCandDAO.retrieveInvoiceCandidatesForOrderLineId(orderLineId))
{
try (final MDCCloseable icRecordMDC = TableRecordMDC.putTableRecordReference(icRecord))
{
final I_C_InvoiceCandidate_InOutLine iciol = InterfaceWrapperHelper.newInstance(I_C_InvoiceCandidate_InOutLine.class, inOutLine);
iciol.setC_Invoice_Candidate(icRecord);
invoiceCandBL.updateICIOLAssociationFromIOL(iciol, inOutLine);
// TODO: QtyInvoiced shall be set! It's not so critical, atm is used on on Sales side (check call hierarchy of getQtyInvoiced())
// NOTE: when we will set it, because there can be more then one IC for one inoutLine we need to calculate this Qtys proportionally.
//
// (also) calculate qualityDiscountPercent taken from inoutLines (06502)
Services.get(IInvoiceCandidateHandlerBL.class).setDeliveredData(icRecord);
final InvoiceCandidate invoiceCandidate = invoiceCandidateRecordService.ofRecord(icRecord);
invoiceCandidateRecordService.updateRecord(invoiceCandidate, icRecord);
InterfaceWrapperHelper.saveRecord(icRecord);
}
}
// invalidate the candidates related to the inOutLine's order line..i'm not 100% if it's necessary, but we might need to e.g. update the
// QtyDelivered or QtyPicked or whatever...
// final I_C_OrderLine orderLine = Services.get(IOrderDAO.class).getOrderLineById(orderLineId);
// Services.get(IInvoiceCandidateHandlerBL.class).invalidateCandidatesFor(orderLine);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\M_InOutLine.java | 1 |
请完成以下Java代码 | public static <T> T convert(TbNodeConfiguration configuration, Class<T> clazz) throws TbNodeException {
try {
return JacksonUtil.treeToValue(configuration.getData(), clazz);
} catch (IllegalArgumentException e) {
throw new TbNodeException(e, true);
}
}
public static List<String> processPatterns(List<String> patterns, TbMsg tbMsg) {
if (CollectionsUtil.isEmpty(patterns)) {
return Collections.emptyList();
}
return patterns.stream().map(p -> processPattern(p, tbMsg)).toList();
}
public static String processPattern(String pattern, TbMsg tbMsg) {
try {
String result = processPattern(pattern, tbMsg.getMetaData());
JsonNode json = JacksonUtil.toJsonNode(tbMsg.getData());
result = result.replace(ALL_DATA_TEMPLATE, JacksonUtil.toString(json));
if (json.isObject()) {
Matcher matcher = DATA_PATTERN.matcher(result);
while (matcher.find()) {
String group = matcher.group(2);
String[] keys = group.split("\\.");
JsonNode jsonNode = json;
for (String key : keys) {
if (StringUtils.isNotEmpty(key) && jsonNode != null) {
jsonNode = jsonNode.get(key);
} else {
jsonNode = null;
break;
}
} | if (jsonNode != null && jsonNode.isValueNode()) {
result = result.replace(formatDataVarTemplate(group), jsonNode.asText());
}
}
}
return result;
} catch (Exception e) {
throw new RuntimeException("Failed to process pattern!", e);
}
}
private static String processPattern(String pattern, TbMsgMetaData metaData) {
String replacement = metaData.isEmpty() ? "{}" : JacksonUtil.toString(metaData.getData());
pattern = pattern.replace(ALL_METADATA_TEMPLATE, replacement);
return processTemplate(pattern, metaData.values());
}
public static String processTemplate(String template, Map<String, String> data) {
String result = template;
for (Map.Entry<String, String> kv : data.entrySet()) {
result = processVar(result, kv.getKey(), kv.getValue());
}
return result;
}
private static String processVar(String pattern, String key, String val) {
return pattern.replace(formatMetadataVarTemplate(key), val);
}
static String formatDataVarTemplate(String key) {
return "$[" + key + "]";
}
static String formatMetadataVarTemplate(String key) {
return "${" + key + "}";
}
} | repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\util\TbNodeUtils.java | 1 |
请完成以下Java代码 | public InitializrMetadata update(InitializrMetadata current) {
String url = current.getConfiguration().getEnv().getSpringBootMetadataUrl();
List<DefaultMetadataElement> bootVersions = fetchSpringBootVersions(url);
if (bootVersions != null && !bootVersions.isEmpty()) {
if (bootVersions.stream().noneMatch(DefaultMetadataElement::isDefault)) {
// No default specified
bootVersions.get(0).setDefault(true);
}
current.updateSpringBootVersions(bootVersions);
}
return current;
}
/**
* Fetch the available Spring Boot versions using the specified service url.
* @param url the url to the spring-boot project metadata | * @return the spring boot versions metadata or {@code null} if it could not be
* retrieved
*/
protected List<DefaultMetadataElement> fetchSpringBootVersions(String url) {
if (StringUtils.hasText(url)) {
try {
logger.info("Fetching Spring Boot metadata from " + url);
return new SpringBootMetadataReader(this.objectMapper, this.restTemplate, url).getBootVersions();
}
catch (Exception ex) {
logger.warn("Failed to fetch Spring Boot metadata", ex);
}
}
return null;
}
} | repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\SpringIoInitializrMetadataUpdateStrategy.java | 1 |
请完成以下Java代码 | public JsonObject writeConfiguration(SetJobRetriesBatchConfiguration configuration) {
JsonObject json = JsonUtil.createObject();
JsonUtil.addListField(json, JOB_IDS, configuration.getIds());
JsonUtil.addListField(json, JOB_ID_MAPPINGS, DeploymentMappingJsonConverter.INSTANCE, configuration.getIdMappings());
JsonUtil.addField(json, RETRIES, configuration.getRetries());
if(configuration.isDueDateSet()) {
Date dueDate = configuration.getDueDate();
if (dueDate == null) {
JsonUtil.addNullField(json, DUE_DATE);
} else {
JsonUtil.addDateField(json, DUE_DATE, dueDate);
}
}
return json;
}
@Override
public SetJobRetriesBatchConfiguration readConfiguration(JsonObject json) {
boolean isDueDateSet = json.has(DUE_DATE);
Date dueDate = null;
if (isDueDateSet && !json.get(DUE_DATE).isJsonNull()) {
dueDate = new Date(JsonUtil.getLong(json, DUE_DATE)); | }
SetJobRetriesBatchConfiguration configuration = new SetJobRetriesBatchConfiguration(
readJobIds(json), readIdMappings(json), JsonUtil.getInt(json, RETRIES), dueDate, isDueDateSet);
return configuration;
}
protected List<String> readJobIds(JsonObject jsonObject) {
return JsonUtil.asStringList(JsonUtil.getArray(jsonObject, JOB_IDS));
}
protected DeploymentMappings readIdMappings(JsonObject jsonObject) {
return JsonUtil.asList(JsonUtil.getArray(jsonObject, JOB_ID_MAPPINGS), DeploymentMappingJsonConverter.INSTANCE, DeploymentMappings::new);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\job\SetJobRetriesBatchConfigurationJsonConverter.java | 1 |
请完成以下Java代码 | public final IAllocationRequest removeQty(final IAllocationRequest request)
{
if (!isEligible(request))
{
return AllocationUtils.createZeroQtyRequest(request);
}
final Bucket capacity = getCapacity();
final Quantity qtyToRemove = request.getQuantity();
final Boolean allowNegativeCapacityOverride = getAllowNegativeCapacityOverride(request);
final Quantity qtyToRemoveActual = capacity.removeQty(qtyToRemove, allowNegativeCapacityOverride);
final IAllocationRequest requestActual = AllocationUtils.createQtyRequest(request, qtyToRemoveActual);
return requestActual;
}
protected Boolean getAllowNegativeCapacityOverride(final IAllocationRequest request)
{
if (getCapacity().isInfiniteCapacity()) // 08443: For infinite capacity, disallow negative capacity overrides ()
{
return false;
}
else if (isConsiderForceQtyAllocationFromRequest() && request.isForceQtyAllocation())
{
return true;
}
else
{
return isAllowNegativeStorage();
}
}
private boolean isEligible(final IAllocationRequest request)
{
// NOTE: don't throw exception but just return false,
// because we have the case where are multiple storages in a pool and each of them are asked if they can fullfill a given request
return Objects.equals(request.getProductId(), getProductId());
}
protected final BigDecimal convertToStorageUOM(final BigDecimal qty, final I_C_UOM uom)
{
Check.assumeNotNull(qty, "qty not null");
Check.assumeNotNull(uom, "uom not null");
final ProductId productId = getProductId();
final I_C_UOM storageUOM = getC_UOM();
final BigDecimal qtyConverted = Services.get(IUOMConversionBL.class)
.convertQty(productId, qty, uom, storageUOM);
Check.assumeNotNull(qtyConverted,
"qtyConverted not null (Qty={}, FromUOM={}, ToUOM={}, Product={}",
qty, uom, storageUOM); | return qtyConverted;
}
@Override
public boolean isEmpty()
{
return getQty().isZero();
}
public boolean isFull()
{
final BigDecimal qtyFree = getQtyFree();
return qtyFree.signum() == 0;
}
@Override
public final void markStaled()
{
beforeMarkingStalled();
_capacity = null;
}
/**
* This method is called when {@link #markStaled()} is executed, right before resetting the status.
*
* NOTE: To be implemented by extending classes.
*/
protected void beforeMarkingStalled()
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\AbstractProductStorage.java | 1 |
请完成以下Java代码 | public String getSql()
{
return sql;
}
@Override
public List<Object> getSqlParams(final Properties ctx)
{
final Properties ctxToUse = ctx == null ? this.ctx : ctx;
final ClientId clientId = Env.getClientIdIfSet(ctxToUse).orElse(null);
if (clientId == null)
{
//noinspection ThrowableNotThrown
new AdempiereException("No " + Env.CTXNAME_AD_Client_ID + " found in context")
.throwIfDeveloperModeOrLogWarningElse(logger);
}
return Collections.singletonList(clientId);
}
public void setContext(final Properties ctx)
{
this.ctx = ctx;
}
/**
* Compared the given model's {@code AD_CLient_ID} with the {@code AD_CLient_ID} from
* <ul>
* <li>this instances {@code ctx} member if that member is not null (see {@link #ContextClientQueryFilter(Properties)}) and {@link #setContext(Properties)}</li>
* <li>the given {@code model}'s own {@code ctx} (see {@link InterfaceWrapperHelper#getCtx(Object)})</li>
* </ul>
*/
@Override
public boolean accept(T model)
{
final int adClientId = getAD_Client_ID(model);
final Properties ctxToUse = this.ctx != null ? ctx : InterfaceWrapperHelper.getCtx(model);
final int contextClientId = Env.getAD_Client_ID(ctxToUse);
// Context client | if (adClientId == contextClientId)
{
return true;
}
// System client
if (includeSystemClient && adClientId == IClientDAO.SYSTEM_CLIENT_ID)
{
return true;
}
return false;
}
private int getAD_Client_ID(final T model)
{
final Object adClientId = InterfaceWrapperHelper.getValueOrNull(model, COLUMNNAME_AD_Client_ID);
if (adClientId == null)
{
return -1;
}
else if (adClientId instanceof Number)
{
return ((Number)adClientId).intValue();
}
else
{
throw new IllegalArgumentException("Invalid AD_Client_ID value '" + adClientId + "' for " + model);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ContextClientQueryFilter.java | 1 |
请完成以下Java代码 | public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setPrintServiceName (java.lang.String PrintServiceName)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceName, PrintServiceName);
}
@Override
public java.lang.String getPrintServiceName()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName);
}
@Override
public void setPrintServiceTray (java.lang.String PrintServiceTray)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceTray, PrintServiceTray);
}
@Override
public java.lang.String getPrintServiceTray()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray);
}
@Override
public org.compiere.model.I_S_Resource getS_Resource()
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions));
}
@Override
public boolean isStatus_Print_Job_Instructions()
{ | return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
}
@Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
@Override
public void setWP_IsError (boolean WP_IsError)
{
set_ValueNoCheck (COLUMNNAME_WP_IsError, Boolean.valueOf(WP_IsError));
}
@Override
public boolean isWP_IsError()
{
return get_ValueAsBoolean(COLUMNNAME_WP_IsError);
}
@Override
public void setWP_IsProcessed (boolean WP_IsProcessed)
{
set_ValueNoCheck (COLUMNNAME_WP_IsProcessed, Boolean.valueOf(WP_IsProcessed));
}
@Override
public boolean isWP_IsProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_WP_IsProcessed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Order_MFGWarehouse_Report_PrintInfo_v.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RedisConfiguration {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
// 创建 RedisTemplate 对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 设置开启事务支持
template.setEnableTransactionSupport(true);
// 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。
template.setConnectionFactory(factory);
// 使用 String 序列化方式,序列化 KEY 。
template.setKeySerializer(RedisSerializer.string());
// 使用 JSON 序列化方式(库是 Jackson ),序列化 VALUE 。
template.setValueSerializer(RedisSerializer.json());
return template;
}
// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// ObjectMapper objectMapper = new ObjectMapper();// <1>
//// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//
// jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// template.setValueSerializer(jackson2JsonRedisSerializer);
// @Bean // PUB/SUB 使用的 Bean ,需要时打开。 | public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory factory) {
// 创建 RedisMessageListenerContainer 对象
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
// 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。
container.setConnectionFactory(factory);
// 添加监听器
container.addMessageListener(new TestChannelTopicMessageListener(), new ChannelTopic("TEST"));
// container.addMessageListener(new TestChannelTopicMessageListener(), new ChannelTopic("AOTEMAN"));
// container.addMessageListener(new TestPatternTopicMessageListener(), new PatternTopic("TEST"));
return container;
}
} | repos\SpringBoot-Labs-master\lab-11-spring-data-redis\lab-07-spring-data-redis-with-jedis\src\main\java\cn\iocoder\springboot\labs\lab10\springdatarediswithjedis\config\RedisConfiguration.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
if(ProcessUtil.isFlatFeeContract(context))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Not supported for FlatFee contracts");
}
return ProcessPreconditionsResolution
.acceptIf(I_C_Flatrate_Term.Table_Name.equals(context.getTableName()));
}
@Override
protected String doIt() throws Exception
{
updateFlatrateTermProductAndPrice();
return MSG_OK;
}
private void updateFlatrateTermProductAndPrice()
{
final I_C_Flatrate_Term term = flatrateBL.getById(retrieveSelectedFlatrateTermId());
C_Flatrate_Term_Change_ProcessHelper.throwExceptionIfTermHasInvoices(term);
updateFlatrateTermProductAndPrice(term);
updateNextFlatrateTermProductAndPrice(term);
} | private void updateFlatrateTermProductAndPrice(@NonNull final I_C_Flatrate_Term term)
{
final LocalDate date = TimeUtil.asLocalDate(term.getStartDate(), orgDAO.getTimeZone(OrgId.ofRepoId(term.getAD_Org_ID())));
final FlatrateTermPriceRequest request = FlatrateTermPriceRequest.builder()
.flatrateTerm(term)
.productId(retrieveSelectedProductId())
.priceDate(date)
.build();
flatrateBL.updateFlatrateTermProductAndPrice(request);
}
private void updateNextFlatrateTermProductAndPrice(@NonNull final I_C_Flatrate_Term term)
{
final ImmutableList<I_C_Flatrate_Term> termstoUpdate = flatrateBL.retrieveNextFlatrateTerms(term);
termstoUpdate.forEach(this::updateFlatrateTermProductAndPrice);
}
final FlatrateTermId retrieveSelectedFlatrateTermId()
{
return FlatrateTermId.ofRepoId(getRecord_ID());
}
final ProductId retrieveSelectedProductId()
{
return ProductId.ofRepoId(p_M_Product_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Change_Product.java | 1 |
请完成以下Java代码 | public boolean isReceipt()
{
return getType().canReceive();
}
public boolean isIssue()
{
return getType().canIssue();
}
public boolean isHUStatusActive()
{
return huStatus != null && X_M_HU.HUSTATUS_Active.equals(huStatus.getKey());
}
@Override
public boolean hasAttributes()
{
return attributesSupplier != null;
}
@Override
public IViewRowAttributes getAttributes() throws EntityNotFoundException
{
if (attributesSupplier == null)
{
throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this);
} | final IViewRowAttributes attributes = attributesSupplier.get();
if (attributes == null)
{
throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this);
}
return attributes;
}
@Override
public HuUnitType getHUUnitTypeOrNull() {return huUnitType;}
@Override
public BPartnerId getBpartnerId() {return huBPartnerId;}
@Override
public boolean isTopLevel() {return topLevelHU;}
@Override
public Stream<HUReportAwareViewRow> streamIncludedHUReportAwareRows() {return getIncludedRows().stream().map(PPOrderLineRow::toHUReportAwareViewRow);}
private HUReportAwareViewRow toHUReportAwareViewRow() {return this;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRow.java | 1 |
请完成以下Java代码 | public void executeCopyPasteAction(final CopyPasteActionType actionType)
{
if (actionType == CopyPasteActionType.Cut)
{
doCut();
}
else if (actionType == CopyPasteActionType.Copy)
{
doCopy();
}
else if (actionType == CopyPasteActionType.Paste)
{
doPaste();
}
else if (actionType == CopyPasteActionType.SelectAll)
{
doSelectAll();
}
}
private final boolean isEditable()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return false;
}
return textComponent.isEditable() && textComponent.isEnabled();
}
private final boolean hasTextToCopy()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return false;
}
// Document document = textComponent.getDocument();
// final JComboBox<?> comboBox = getComboBox();
// final ComboBoxEditor editor = comboBox.getEditor();
// comboBox.getClass().getMethod("getDisplay").invoke(comboBox);
final String selectedText = textComponent.getSelectedText();
return selectedText != null && !selectedText.isEmpty();
}
private final boolean isEmpty()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return false;
}
final String text = textComponent.getText();
return Check.isEmpty(text, false);
}
private void doCopy()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null) | {
return;
}
textComponent.copy();
}
private void doCut()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.cut();
}
private void doPaste()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.paste();
}
private void doSelectAll()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
// NOTE: we need to request focus first because it seems in some case the code below is not working when the component does not have the focus.
textComponent.requestFocus();
textComponent.selectAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\JComboBoxCopyPasteSupportEditor.java | 1 |
请完成以下Java代码 | public static Result ok(Object data) {
return new Result(200 , data);
}
public static Result ok() {
return new Result(200 , null);
}
public static Result build(Integer status, String msg) {
return new Result(status, msg, null);
}
public static Result build(Integer status, String msg , Object data) {
return new Result(status,msg,data);
}
public Result(Integer status,String msg) { | this.status = status;
this.msg = msg;
}
public Result(Integer status,Object data) {
this.status = status;
this.data = data;
}
public Result(Integer status, String msg, Object data) {
this.status = status;
this.msg = msg;
this.data = data;
}
} | repos\SpringBootLearning-master (1)\springboot-jsr303\src\main\java\com\itwolfed\utils\Result.java | 1 |
请完成以下Java代码 | public void setQty (final BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public de.metas.handlingunits.model.I_M_HU getVHU()
{
return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU)
{
set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU);
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_ValueNoCheck (COLUMNNAME_VHU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getVHU_Source()
{
return get_ValueAsPO(COLUMNNAME_VHU_Source_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setVHU_Source(final de.metas.handlingunits.model.I_M_HU VHU_Source)
{
set_ValueFromPO(COLUMNNAME_VHU_Source_ID, de.metas.handlingunits.model.I_M_HU.class, VHU_Source);
}
@Override
public void setVHU_Source_ID (final int VHU_Source_ID)
{
if (VHU_Source_ID < 1)
set_Value (COLUMNNAME_VHU_Source_ID, null);
else
set_Value (COLUMNNAME_VHU_Source_ID, VHU_Source_ID); | }
@Override
public int getVHU_Source_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_Source_ID);
}
/**
* VHUStatus AD_Reference_ID=540478
* Reference name: HUStatus
*/
public static final int VHUSTATUS_AD_Reference_ID=540478;
/** Planning = P */
public static final String VHUSTATUS_Planning = "P";
/** Active = A */
public static final String VHUSTATUS_Active = "A";
/** Destroyed = D */
public static final String VHUSTATUS_Destroyed = "D";
/** Picked = S */
public static final String VHUSTATUS_Picked = "S";
/** Shipped = E */
public static final String VHUSTATUS_Shipped = "E";
/** Issued = I */
public static final String VHUSTATUS_Issued = "I";
@Override
public void setVHUStatus (final java.lang.String VHUStatus)
{
set_ValueNoCheck (COLUMNNAME_VHUStatus, VHUStatus);
}
@Override
public java.lang.String getVHUStatus()
{
return get_ValueAsString(COLUMNNAME_VHUStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trace.java | 1 |
请完成以下Java代码 | public void setInvoiceableLine(final IQualityInvoiceLine invoiceableLine)
{
this.invoiceableLine = invoiceableLine;
setThisAsParentIfPossible(invoiceableLine);
}
@Override
public IQualityInvoiceLine getInvoiceableLine()
{
Check.assumeNotNull(invoiceableLine, "invoiceableLine not null");
return invoiceableLine;
}
@Override
public void setInvoiceableLineOverride(final IQualityInvoiceLine invoiceableLineOverride)
{
this.invoiceableLineOverride = invoiceableLineOverride;
setThisAsParentIfPossible(invoiceableLineOverride);
}
private void setThisAsParentIfPossible(IQualityInvoiceLine invoiceableLineOverride)
{
if (invoiceableLineOverride instanceof QualityInvoiceLine)
{
((QualityInvoiceLine)invoiceableLineOverride).setGroup(this);
}
}
@Override
public IQualityInvoiceLine getInvoiceableLineOverride()
{
return invoiceableLineOverride;
}
@Override
public QualityInvoiceLineGroupType getQualityInvoiceLineGroupType() | {
return qualityInvoiceLineGroupType;
}
@Override
public void addDetailBefore(final IQualityInvoiceLine line)
{
Check.assumeNotNull(line, "line not null");
detailsBefore.add(line);
setThisAsParentIfPossible(line);
}
@Override
public List<IQualityInvoiceLine> getDetailsBefore()
{
return detailsBefore;
}
@Override
public void addDetailAfter(final IQualityInvoiceLine line)
{
Check.assumeNotNull(line, "line not null");
detailsAfter.add(line);
setThisAsParentIfPossible(line);
}
@Override
public List<IQualityInvoiceLine> getDetailsAfter()
{
return detailsAfter;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\impl\QualityInvoiceLineGroup.java | 1 |
请完成以下Java代码 | public AttributeBuilder<Boolean> booleanAttribute(String attributeName) {
BooleanAttributeBuilder builder = new BooleanAttributeBuilder(attributeName, modelType);
modelBuildOperations.add(builder);
return builder;
}
public StringAttributeBuilder stringAttribute(String attributeName) {
StringAttributeBuilderImpl builder = new StringAttributeBuilderImpl(attributeName, modelType);
modelBuildOperations.add(builder);
return builder;
}
public AttributeBuilder<Integer> integerAttribute(String attributeName) {
IntegerAttributeBuilder builder = new IntegerAttributeBuilder(attributeName, modelType);
modelBuildOperations.add(builder);
return builder;
}
public AttributeBuilder<Double> doubleAttribute(String attributeName) {
DoubleAttributeBuilder builder = new DoubleAttributeBuilder(attributeName, modelType);
modelBuildOperations.add(builder);
return builder;
}
public <V extends Enum<V>> AttributeBuilder<V> enumAttribute(String attributeName, Class<V> enumType) {
EnumAttributeBuilder<V> builder = new EnumAttributeBuilder<V>(attributeName, modelType, enumType);
modelBuildOperations.add(builder);
return builder;
}
public <V extends Enum<V>> AttributeBuilder<V> namedEnumAttribute(String attributeName, Class<V> enumType) {
NamedEnumAttributeBuilder<V> builder = new NamedEnumAttributeBuilder<V>(attributeName, modelType, enumType);
modelBuildOperations.add(builder);
return builder;
}
public ModelElementType build() {
model.registerType(modelType, instanceType);
return modelType;
}
public ModelElementTypeBuilder abstractType() {
modelType.setAbstract(true);
return this;
} | public SequenceBuilder sequence() {
SequenceBuilderImpl builder = new SequenceBuilderImpl(modelType);
modelBuildOperations.add(builder);
return builder;
}
public void buildTypeHierarchy(Model model) {
// build type hierarchy
if(extendedType != null) {
ModelElementTypeImpl extendedModelElementType = (ModelElementTypeImpl) model.getType(extendedType);
if(extendedModelElementType == null) {
throw new ModelException("Type "+modelType+" is defined to extend "+extendedType+" but no such type is defined.");
} else {
modelType.setBaseType(extendedModelElementType);
extendedModelElementType.registerExtendingType(modelType);
}
}
}
public void performModelBuild(Model model) {
for (ModelBuildOperation operation : modelBuildOperations) {
operation.performModelBuild(model);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\ModelElementTypeBuilderImpl.java | 1 |
请完成以下Java代码 | public double getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = itemPrice;
}
public ItemType getItemType() {
return itemType;
}
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Seller getSeller() {
return seller;
} | public void setSeller(Seller seller) {
this.seller = seller;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return id == item.id &&
Double.compare(item.itemPrice, itemPrice) == 0 &&
Objects.equals(itemName, item.itemName) &&
itemType == item.itemType &&
Objects.equals(createdOn, item.createdOn) &&
Objects.equals(seller, item.seller);
}
@Override
public int hashCode() {
return Objects.hash(id, itemName, itemPrice, itemType, createdOn, seller);
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\mapkeyjoincolumn\Item.java | 1 |
请完成以下Java代码 | /* package */class OrderLinePackingMaterialDocumentLineSource implements IPackingMaterialDocumentLineSource
{
//
// Services
private final transient IHUPackingMaterialDAO packingMaterialDAO = Services.get(IHUPackingMaterialDAO.class);
private final transient IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
private final I_C_OrderLine orderLine;
private final List<I_M_HU_PackingMaterial> packingMaterials;
public OrderLinePackingMaterialDocumentLineSource(@NonNull final org.compiere.model.I_C_OrderLine orderLine)
{
this.orderLine = InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class);
Check.assume(!this.orderLine.isPackagingMaterial(), "Orderline shall have PackingMaterial flag not set: {}", this.orderLine);
final I_M_HU_PI_Item_Product piItemProduct = this.orderLine.getM_HU_PI_Item_Product();
if (piItemProduct != null && piItemProduct.getM_HU_PI_Item_Product_ID() > 0)
{
// do not create a new line if the pip is infinite capacity : task 05316
if (piItemProduct.isInfiniteCapacity())
{
packingMaterials = Collections.emptyList();
}
else
{
packingMaterials = Collections.unmodifiableList(packingMaterialDAO.retrievePackingMaterials(piItemProduct));
}
}
else
{
packingMaterials = Collections.emptyList();
}
}
public I_C_OrderLine getC_OrderLine()
{
return orderLine;
}
@Override
public List<I_M_HU_PackingMaterial> getM_HU_PackingMaterials()
{
return packingMaterials;
}
@Override
public BigDecimal getQty()
{
// TODO: why not using getQtyEnteredTU?
// yes, why not indeed?
final BigDecimal qtyItemCapacity = orderLine.getQtyItemCapacity();
if (qtyItemCapacity.signum() == 0)
{
return BigDecimal.ZERO;
}
final BigDecimal qtyOrdered = orderLine.getQtyOrdered(); | return qtyOrdered.divide(qtyItemCapacity, 0, RoundingMode.UP);
}
@Override
public @Nullable ProductId getLUProductId()
{
final HuPackingInstructionsId luPIId = HuPackingInstructionsId.ofRepoIdOrNull(orderLine.getM_LU_HU_PI_ID());
if (luPIId == null)
{
return null;
}
return packingMaterialDAO.getLUPIItemForHUPI(BPartnerId.ofRepoId(orderLine.getC_BPartner_ID()), luPIId)
.map(HuPackingMaterial::getProductId)
.orElse(null);
}
@Override
public BigDecimal getQtyLU()
{
return orderLine.getQtyLU();
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\OrderLinePackingMaterialDocumentLineSource.java | 1 |
请完成以下Java代码 | private String getArchivePathSnippet(final I_AD_Archive archive)
{
final StringBuilder path = new StringBuilder();
path.append(archive.getAD_Client_ID()).append(File.separator);
path.append(archive.getAD_Org_ID()).append(File.separator);
final int adProcessId = archive.getAD_Process_ID();
if (adProcessId > 0)
{
path.append(adProcessId).append(File.separator);
}
final int adTableId = archive.getAD_Table_ID();
if (adTableId > 0)
{
path.append(adTableId).append(File.separator);
} | final int recordId = archive.getRecord_ID();
if (recordId > 0)
{
path.append(recordId).append(File.separator);
}
return path.toString();
}
@Override
public String toString()
{
return "FilesystemArchiveStorage [RootPath=" + archivePathRoot + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\spi\impl\FilesystemArchiveStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DataExportAudit save(@NonNull final CreateDataExportAuditRequest createDataExportAuditRequest)
{
final I_Data_Export_Audit record = InterfaceWrapperHelper.loadOrNew(createDataExportAuditRequest.getDataExportAuditId(), I_Data_Export_Audit.class);
record.setAD_Table_ID(createDataExportAuditRequest.getTableRecordReference().getAD_Table_ID());
record.setRecord_ID(createDataExportAuditRequest.getTableRecordReference().getRecord_ID());
if (createDataExportAuditRequest.getParentId() != null)
{
record.setData_Export_Audit_Parent_ID(createDataExportAuditRequest.getParentId().getRepoId());
}
saveRecord(record);
return toDataExportAudit(record);
}
@NonNull
public Optional<DataExportAudit> getByTableRecordReference(@NonNull final TableRecordReference tableRecordReference)
{
return queryBL.createQueryBuilder(I_Data_Export_Audit.class) | .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_Data_Export_Audit.COLUMNNAME_AD_Table_ID, tableRecordReference.getAD_Table_ID())
.addEqualsFilter(I_Data_Export_Audit.COLUMNNAME_Record_ID, tableRecordReference.getRecord_ID())
.create()
.firstOnlyOptional(I_Data_Export_Audit.class)
.map(DataExportAuditRepository::toDataExportAudit);
}
@NonNull
private static DataExportAudit toDataExportAudit(@NonNull final I_Data_Export_Audit record)
{
return DataExportAudit.builder()
.id(DataExportAuditId.ofRepoId(record.getData_Export_Audit_ID()))
.tableRecordReference(TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID()))
.parentId(DataExportAuditId.ofRepoIdOrNull(record.getData_Export_Audit_Parent_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\data\repository\DataExportAuditRepository.java | 2 |
请完成以下Java代码 | private CompositeAggregationKeyValueHandler getCompositeKeyValueHandler(@NonNull final String registrationKey)
{
CompositeAggregationKeyValueHandler compositeKeyValueHandler = _valueHandlers.get(registrationKey);
if (compositeKeyValueHandler == null)
{
compositeKeyValueHandler = new CompositeAggregationKeyValueHandler();
_valueHandlers.put(registrationKey, compositeKeyValueHandler);
}
return compositeKeyValueHandler;
}
@Override
public void registerAggregationKeyValueHandler(final String registrationKey, final IAggregationKeyValueHandler<?> aggregationKeyValueHandler)
{
final CompositeAggregationKeyValueHandler compositeKeyValueHandler = getCompositeKeyValueHandler(registrationKey);
@SuppressWarnings("unchecked")
final IAggregationKeyValueHandler<Object> aggregationKeyValueHandlerCast = (IAggregationKeyValueHandler<Object>)aggregationKeyValueHandler;
compositeKeyValueHandler.registerAggregationKeyValueHandler(aggregationKeyValueHandlerCast);
}
@Override | public <T> List<Object> getValuesForModel(final String registrationKey, final T model)
{
final CompositeAggregationKeyValueHandler compositeKeyValueHandler = getCompositeKeyValueHandler(registrationKey);
return compositeKeyValueHandler.getValues(model);
}
@Override
public void clearHandlers(final String registrationKey)
{
_valueHandlers.remove(registrationKey);
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\agg\key\impl\AggregationKeyRegistry.java | 1 |
请完成以下Java代码 | public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("QualityInvoiceLineGroup[");
sb.append("\n\tType: ").append(qualityInvoiceLineGroupType);
sb.append("\n\tinvoiceableLine: ").append(invoiceableLine);
if (!detailsBefore.isEmpty())
{
sb.append("\n\tDetails(before)");
for (final IQualityInvoiceLine detail : detailsBefore)
{
sb.append("\n\t\t").append(detail);
}
}
if (!detailsAfter.isEmpty())
{
sb.append("\n\tDetails(after)");
for (final IQualityInvoiceLine detail : detailsAfter)
{
sb.append("\n\t\t").append(detail);
}
}
sb.append("\n]");
return sb.toString();
}
@Override
public void setInvoiceableLine(final IQualityInvoiceLine invoiceableLine)
{
this.invoiceableLine = invoiceableLine;
setThisAsParentIfPossible(invoiceableLine);
}
@Override
public IQualityInvoiceLine getInvoiceableLine()
{
Check.assumeNotNull(invoiceableLine, "invoiceableLine not null");
return invoiceableLine;
}
@Override
public void setInvoiceableLineOverride(final IQualityInvoiceLine invoiceableLineOverride)
{
this.invoiceableLineOverride = invoiceableLineOverride;
setThisAsParentIfPossible(invoiceableLineOverride);
}
private void setThisAsParentIfPossible(IQualityInvoiceLine invoiceableLineOverride)
{
if (invoiceableLineOverride instanceof QualityInvoiceLine) | {
((QualityInvoiceLine)invoiceableLineOverride).setGroup(this);
}
}
@Override
public IQualityInvoiceLine getInvoiceableLineOverride()
{
return invoiceableLineOverride;
}
@Override
public QualityInvoiceLineGroupType getQualityInvoiceLineGroupType()
{
return qualityInvoiceLineGroupType;
}
@Override
public void addDetailBefore(final IQualityInvoiceLine line)
{
Check.assumeNotNull(line, "line not null");
detailsBefore.add(line);
setThisAsParentIfPossible(line);
}
@Override
public List<IQualityInvoiceLine> getDetailsBefore()
{
return detailsBefore;
}
@Override
public void addDetailAfter(final IQualityInvoiceLine line)
{
Check.assumeNotNull(line, "line not null");
detailsAfter.add(line);
setThisAsParentIfPossible(line);
}
@Override
public List<IQualityInvoiceLine> getDetailsAfter()
{
return detailsAfter;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\impl\QualityInvoiceLineGroup.java | 1 |
请完成以下Java代码 | public static int toRepoId(final HuPackingInstructionsVersionId HuPackingInstructionsVersionId)
{
return HuPackingInstructionsVersionId != null ? HuPackingInstructionsVersionId.getRepoId() : -1;
}
public static final HuPackingInstructionsVersionId TEMPLATE = new HuPackingInstructionsVersionId(100);
public static final HuPackingInstructionsVersionId VIRTUAL = new HuPackingInstructionsVersionId(101);
int repoId;
private HuPackingInstructionsVersionId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Version_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(final HuPackingInstructionsVersionId o1, final HuPackingInstructionsVersionId o2)
{
return Objects.equals(o1, o2);
}
public boolean isTemplate()
{
return isTemplateRepoId(repoId);
}
public static boolean isTemplateRepoId(final int repoId)
{
return repoId == TEMPLATE.repoId;
}
public boolean isVirtual()
{
return isVirtualRepoId(repoId);
}
public static boolean isVirtualRepoId(final int repoId)
{
return repoId == VIRTUAL.repoId;
}
public boolean isRealPackingInstructions()
{ | return isRealPackingInstructionsRepoId(repoId);
}
public static boolean isRealPackingInstructionsRepoId(final int repoId)
{
return repoId > 0
&& !isTemplateRepoId(repoId)
&& !isVirtualRepoId(repoId);
}
public HuPackingInstructionsId getKnownPackingInstructionsIdOrNull()
{
if (isVirtual())
{
return HuPackingInstructionsId.VIRTUAL;
}
if (isTemplate())
{
return HuPackingInstructionsId.TEMPLATE;
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HuPackingInstructionsVersionId.java | 1 |
请完成以下Java代码 | public Mono<CsrfToken> loadToken(ServerWebExchange exchange) {
return Mono.fromCallable(() -> {
HttpCookie csrfCookie = exchange.getRequest().getCookies().getFirst(this.cookieName);
if ((csrfCookie == null) || !StringUtils.hasText(csrfCookie.getValue())) {
return null;
}
return createCsrfToken(csrfCookie.getValue());
});
}
/**
* Sets the cookie name
* @param cookieName The cookie name
*/
public void setCookieName(String cookieName) {
Assert.hasLength(cookieName, "cookieName can't be null");
this.cookieName = cookieName;
}
/**
* Sets the parameter name
* @param parameterName The parameter name
*/
public void setParameterName(String parameterName) {
Assert.hasLength(parameterName, "parameterName can't be null");
this.parameterName = parameterName;
}
/**
* Sets the header name
* @param headerName The header name
*/
public void setHeaderName(String headerName) {
Assert.hasLength(headerName, "headerName can't be null");
this.headerName = headerName;
}
/**
* Sets the cookie path | * @param cookiePath The cookie path
*/
public void setCookiePath(String cookiePath) {
this.cookiePath = cookiePath;
}
private CsrfToken createCsrfToken() {
return createCsrfToken(createNewToken());
}
private CsrfToken createCsrfToken(String tokenValue) {
return new DefaultCsrfToken(this.headerName, this.parameterName, tokenValue);
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
private String getRequestContext(ServerHttpRequest request) {
String contextPath = request.getPath().contextPath().value();
return StringUtils.hasLength(contextPath) ? contextPath : "/";
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\CookieServerCsrfTokenRepository.java | 1 |
请完成以下Java代码 | protected final void onRemoteEvent(
final Event event,
final String senderId,
final String topicName,
final Type topicType)
{
final Topic topic = Topic.of(topicName, topicType);
if (topic.getType() != topicType)
{
logger.debug("onEvent - different local topicType for topicName:[{}], remote type:[{}] local type=[{}]; -> ignoring event", topicName, topicType, topic.getType());
return;
}
final IEventBus localEventBus = eventBusFactory.getEventBus(topic);
if (Type.LOCAL == topic.getType() && !Objects.equals(getSenderId(), senderId))
{
logger.debug("onEvent - type LOCAL but event's senderId={} is not equal to the *local* senderId={}; -> ignoring event", senderId, getSenderId());
return;
}
final boolean monitorIncomingEvents = eventBusMonitoringService.isMonitorIncomingEvents();
final boolean localEventBusAsync = localEventBus.isAsync();
final Topic localEventBusTopic = localEventBus.getTopic();
try
{
if (monitorIncomingEvents && !localEventBusAsync)
{
logger.debug("onEvent - localEventBus is not async and isMonitorIncomingEvents=true; -> monitoring event processing; localEventBus={}", localEventBus);
eventBusMonitoringService.extractInfosAndMonitor(event,
localEventBusTopic,
() -> onRemoteEvent0(localEventBus, event, localEventBusTopic.getName()));
}
else
{
logger.debug("onEvent - localEventBus.isAsync={} and isMonitorIncomingEvents={}; -> cannot monitor event processing; localEventBus={}", localEventBusAsync, monitorIncomingEvents, localEventBus);
onRemoteEvent0(localEventBus, event, localEventBusTopic.getName());
} | }
catch (final Exception ex)
{
logger.warn("onEvent - Failed forwarding event to topic {}: {}", localEventBusTopic.getName(), event, ex);
}
}
private void onRemoteEvent0(
@NonNull final IEventBus localEventBus,
@NonNull final Event event,
@NonNull final String topicName)
{
localEventBus.processEvent(event);
logger.debug("Received and processed event in {}ms, topic={}: {}", computeElapsedDuration(event), topicName, event);
}
private static long computeElapsedDuration(@NonNull final Event event)
{
final Instant eventTime = event.getWhen();
if (eventTime == null)
{
return -1;
}
else
{
return System.currentTimeMillis() - eventTime.toEpochMilli();
}
}
@NonNull
private String getSenderId() {return senderId;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\RabbitMQReceiveFromEndpointTemplate.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_R_GroupUpdates[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_User getAD_User() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); | return "Y".equals(oo);
}
return false;
}
public I_R_Group getR_Group() throws RuntimeException
{
return (I_R_Group)MTable.get(getCtx(), I_R_Group.Table_Name)
.getPO(getR_Group_ID(), get_TrxName()); }
/** Set Group.
@param R_Group_ID
Request Group
*/
public void setR_Group_ID (int R_Group_ID)
{
if (R_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Group_ID, Integer.valueOf(R_Group_ID));
}
/** Get Group.
@return Request Group
*/
public int getR_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_GroupUpdates.java | 1 |
请完成以下Java代码 | private void setCountryAttributeAsActive(final I_C_Country country, final boolean isActive)
{
final AttributeListValue existingAttributeValue = getAttributeValue(country);
if (existingAttributeValue != null)
{
final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder()
.id(existingAttributeValue.getId())
.active(isActive)
.build());
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = { I_C_Country.COLUMNNAME_DisplaySequence, I_C_Country.COLUMNNAME_DisplaySequenceLocal })
public void onChangeCountryDisplaySequence(@NonNull final I_C_Country country)
{
assertValidDisplaySequences(country);
}
public void assertValidDisplaySequences(@NonNull final I_C_Country country)
{
AddressDisplaySequence.ofNullable(country.getDisplaySequence()).assertValid();
AddressDisplaySequence.ofNullable(country.getDisplaySequenceLocal()).assertValid();
}
private void setCountryAttributeName(@NonNull final I_C_Country country) | {
final AttributeListValue existingAttributeValue = getAttributeValue(country);
if (existingAttributeValue != null)
{
final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder()
.id(existingAttributeValue.getId())
.name(country.getName())
.build());
}
}
private AttributeListValue getAttributeValue(final I_C_Country country)
{
return Services.get(ICountryAttributeDAO.class).retrieveAttributeValue(Env.getCtx(), country, true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\location\interceptor\C_Country.java | 1 |
请完成以下Java代码 | class OperationMethodParameter implements OperationParameter {
private static final boolean jsr305Present = ClassUtils.isPresent("jakarta.annotation.Nonnull", null);
private final String name;
private final Parameter parameter;
/**
* Create a new {@link OperationMethodParameter} instance.
* @param name the parameter name
* @param parameter the parameter
*/
OperationMethodParameter(String name, Parameter parameter) {
this.name = name;
this.parameter = parameter;
}
@Override
public String getName() {
return this.name;
}
@Override
public Class<?> getType() {
return this.parameter.getType();
}
@Override
public boolean isMandatory() {
if (!ObjectUtils.isEmpty(this.parameter.getAnnotationsByType(Nullable.class))) {
return false;
}
return (jsr305Present) ? new Jsr305().isMandatory(this.parameter) : true;
}
@Override | public <T extends Annotation> T getAnnotation(Class<T> annotation) {
return this.parameter.getAnnotation(annotation);
}
@Override
public String toString() {
return this.name + " of type " + this.parameter.getType().getName();
}
private static final class Jsr305 {
boolean isMandatory(Parameter parameter) {
MergedAnnotation<Nonnull> annotation = MergedAnnotations.from(parameter).get(Nonnull.class);
return !annotation
.isPresent()/*
* || annotation.getEnum("when", When.class) == When.ALWAYS
*/;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\invoke\reflect\OperationMethodParameter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static PrivateKeyEntry tryGetPrivateKeyEntry(KeyStore keyStore, String alias, char[] pwd) {
PrivateKeyEntry entry = null;
try {
if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
try {
entry = (KeyStore.PrivateKeyEntry) keyStore
.getEntry(alias, new KeyStore.PasswordProtection(pwd));
} catch (UnsupportedOperationException e) {
PrivateKey key = (PrivateKey) keyStore.getKey(alias, pwd);
Certificate[] certs = keyStore.getCertificateChain(alias);
entry = new KeyStore.PrivateKeyEntry(key, certs);
}
}
} catch (KeyStoreException | UnrecoverableEntryException | NoSuchAlgorithmException ignored) {}
return entry;
}
private static Set<X509Certificate> getTrustedCerts(KeyStore ks, boolean trustsOnly) {
Set<X509Certificate> set = new HashSet<>();
try {
for (Enumeration<String> e = ks.aliases(); e.hasMoreElements(); ) {
String alias = e.nextElement();
if (ks.isCertificateEntry(alias)) {
Certificate cert = ks.getCertificate(alias);
if (cert instanceof X509Certificate) {
if (trustsOnly) {
// is CA certificate | if (((X509Certificate) cert).getBasicConstraints()>=0) {
set.add((X509Certificate) cert);
}
} else {
set.add((X509Certificate) cert);
}
}
} else if (ks.isKeyEntry(alias)) {
Certificate[] certs = ks.getCertificateChain(alias);
if ((certs != null) && (certs.length > 0) &&
(certs[0] instanceof X509Certificate)) {
if (trustsOnly) {
for (Certificate cert : certs) {
// is CA certificate
if (((X509Certificate) cert).getBasicConstraints()>=0) {
set.add((X509Certificate) cert);
}
}
} else {
set.add((X509Certificate)certs[0]);
}
}
}
}
} catch (KeyStoreException ignored) {}
return Collections.unmodifiableSet(set);
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\config\ssl\AbstractSslCredentials.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public IncludeAttribute getIncludePath() {
return this.includePath;
}
public void setIncludePath(IncludeAttribute includePath) {
this.includePath = includePath;
}
public Whitelabel getWhitelabel() {
return this.whitelabel;
}
/**
* Include error attributes options.
*/
public enum IncludeAttribute {
/**
* Never add error attribute.
*/
NEVER,
/**
* Always add error attribute.
*/
ALWAYS, | /**
* Add error attribute when the appropriate request parameter is not "false".
*/
ON_PARAM
}
public static class Whitelabel {
/**
* Whether to enable the default error page displayed in browsers in case of a
* server error.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\ErrorProperties.java | 2 |
请完成以下Java代码 | public boolean isOrdered() {
return true;
}
},
READY(2) {
@Override
public boolean isReady() {
return true;
}
},
DELIVERED(0) {
@Override
public boolean isDelivered() {
return true;
}
};
private int timeToDelivery;
public boolean isOrdered() {
return false;
} | public boolean isReady() {
return false;
}
public boolean isDelivered() {
return false;
}
public int getTimeToDelivery() {
return timeToDelivery;
}
PizzaStatusEnum(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
} | repos\tutorials-master\core-java-modules\core-java-string-conversions\src\main\java\com\baeldung\stringtoenum\PizzaStatusEnum.java | 1 |
请完成以下Java代码 | public class GlobalActionReadProcess extends JavaProcess
{
private final GlobalActionsDispatcher globalActionsDispatcher = Adempiere.getBean(GlobalActionsDispatcher.class);
private static final String PARAM_Barcode = "Barcode";
@Param(parameterName = PARAM_Barcode, mandatory = true)
String barcode;
@Override
protected String doIt()
{
if (Check.isEmpty(barcode, true))
{
throw new FillMandatoryException(PARAM_Barcode);
}
final GlobalActionEvent event = GlobalActionEvent.parseQRCode(barcode);
final GlobalActionHandlerResult result = globalActionsDispatcher.dispatchEvent(event);
updateProcessResult(result);
return MSG_OK;
}
private void updateProcessResult(final GlobalActionHandlerResult result)
{
// Tolerate null result but do nothing
if (result == null)
{
return; | }
if (result instanceof OpenViewGlobalActionHandlerResult)
{
final OpenViewGlobalActionHandlerResult openViewResult = (OpenViewGlobalActionHandlerResult)result;
final ViewId viewId = openViewResult.getViewId();
final ViewProfileId viewProfileId = openViewResult.getViewProfileId();
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.toJson())
.profileId(viewProfileId != null ? viewProfileId.toJson() : null)
.target(ViewOpenTarget.ModalOverlay)
.build());
}
else
{
throw new AdempiereException("Unknown result: " + result);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\globalaction\process\GlobalActionReadProcess.java | 1 |
请完成以下Java代码 | private static int iterations(int cost)
{
if ((cost < 0) || (cost > 30))
throw new IllegalArgumentException("cost: " + cost);
return 1 << cost;
}
/**
* Hash a password for storage.
*
* @return a secure authentication token to be stored for later authentication
*/
public String hash(char[] password)
{
byte[] salt = new byte[SIZE / 8];
random.nextBytes(salt);
byte[] dk = pbkdf2(password, salt, 1 << cost);
byte[] hash = new byte[salt.length + dk.length];
System.arraycopy(salt, 0, hash, 0, salt.length);
System.arraycopy(dk, 0, hash, salt.length, dk.length);
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
return ID + cost + '$' + enc.encodeToString(hash);
}
/**
* Authenticate with a password and a stored password token.
*
* @return true if the password and token match
*/
public boolean checkPassword(char[] password, String token)
{
Matcher m = layout.matcher(token);
if (!m.matches())
throw new IllegalArgumentException("Invalid token format");
int iterations = iterations(Integer.parseInt(m.group(1)));
byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
byte[] check = pbkdf2(password, salt, iterations);
int zero = 0;
for (int idx = 0; idx < check.length; ++idx)
zero |= hash[salt.length + idx] ^ check[idx];
return zero == 0;
}
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
{
KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
try {
SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
return f.generateSecret(spec).getEncoded();
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
}
catch (InvalidKeySpecException ex) {
throw new IllegalStateException("Invalid SecretKeyFactory", ex);
}
}
/** | * Hash a password in an immutable {@code String}.
*
* <p>Passwords should be stored in a {@code char[]} so that it can be filled
* with zeros after use instead of lingering on the heap and elsewhere.
*
* @deprecated Use {@link #hash(char[])} instead
*/
@Deprecated
public String hash(String password)
{
return hash(password.toCharArray());
}
/**
* Authenticate with a password in an immutable {@code String} and a stored
* password token.
*
* @deprecated Use {@link #checkPassword(char[],String)} instead.
* @see #hash(String)
*/
@Deprecated
public boolean checkPassword(String password, String token)
{
return checkPassword(password.toCharArray(), token);
}
} | repos\tutorials-master\core-java-modules\core-java-security-2\src\main\java\com\baeldung\passwordhashing\PBKDF2Hasher.java | 1 |
请完成以下Java代码 | public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setQty_Reported (final @Nullable BigDecimal Qty_Reported)
{
set_Value (COLUMNNAME_Qty_Reported, Qty_Reported);
}
@Override
public BigDecimal getQty_Reported() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported);
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.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry_Detail.java | 1 |
请完成以下Java代码 | public class ServicesType {
@XmlElements({
@XmlElement(name = "service_ex", namespace = "http://www.forum-datenaustausch.ch/invoice", type = ServiceExType.class),
@XmlElement(name = "service", namespace = "http://www.forum-datenaustausch.ch/invoice", type = ServiceType.class)
})
protected List<Object> serviceExOrService;
/**
* Gets the value of the serviceExOrService property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the serviceExOrService property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getServiceExOrService().add(newItem);
* </pre>
* | *
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ServiceExType }
* {@link ServiceType }
*
*
*/
public List<Object> getServiceExOrService() {
if (serviceExOrService == null) {
serviceExOrService = new ArrayList<Object>();
}
return this.serviceExOrService;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\ServicesType.java | 1 |
请完成以下Java代码 | public class OrderOpen extends JavaProcess
{
/** The Order */
private int p_C_Order_ID = 0;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("C_Order_ID"))
p_C_Order_ID = para[i].getParameterAsInt();
else
log.error("prepare - Unknown Parameter: " + name);
}
} // prepare | /**
* Perform process.
* @return Message
* @throws Exception if not successful
*/
protected String doIt() throws AdempiereSystemError
{
log.info("doIt - Open C_Order_ID=" + p_C_Order_ID);
if (p_C_Order_ID == 0)
return "";
//
MOrder order = new MOrder (getCtx(), p_C_Order_ID, get_TrxName());
String msg = order.reopenIt();
if ( msg.length() != 0 )
{
throw new AdempiereSystemError(msg);
}
return order.save() ? "@OK@" : "@Error@";
} // doIt
} // OrderOpen | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\OrderOpen.java | 1 |
请完成以下Java代码 | void callEnded(Status status) {
clientCallStopWatch.stop();
this.status = status;
boolean shouldRecordFinishedCall = false;
synchronized (lock) {
if (callEnded) {
return;
}
callEnded = true;
if (activeStreams == 0 && !finishedCallToBeRecorded) {
shouldRecordFinishedCall = true;
finishedCallToBeRecorded = true;
}
}
if (shouldRecordFinishedCall) {
recordFinishedCall();
}
}
void recordFinishedCall() {
if (attemptsPerCall.get() == 0) {
ClientTracer tracer = new ClientTracer(this, tracerModule, null, fullMethodName,
metricsClientMeters);
tracer.attemptNanos = attemptStopwatch.elapsed(TimeUnit.NANOSECONDS);
tracer.statusCode = status.getCode(); | tracer.recordFinishedAttempt();
} else if (inboundMetricTracer != null) {
// activeStreams has been decremented to 0 by attemptEnded(),
// so inboundMetricTracer.statusCode is guaranteed to be assigned already.
inboundMetricTracer.recordFinishedAttempt();
}
callLatencyNanos = clientCallStopWatch.elapsed(TimeUnit.NANOSECONDS);
Tags clientCallMetricTags =
Tags.of("grpc.method", this.fullMethodName,
"grpc.status", status.getCode().toString(),
INSTRUMENTATION_SOURCE_TAG_KEY, Constants.LIBRARY_NAME,
INSTRUMENTATION_VERSION_TAG_KEY, Constants.VERSION);
this.metricsClientMeters.getClientCallDuration()
.withTags(clientCallMetricTags)
.record(callLatencyNanos, TimeUnit.NANOSECONDS);
}
}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\metrics\MetricsClientStreamTracers.java | 1 |
请完成以下Java代码 | public ThrowMessageDelegate createThrowMessageJavaDelegate(String className) {
Class<? extends ThrowMessageDelegate> clazz = ReflectUtil.loadClass(className).asSubclass(
ThrowMessageDelegate.class
);
return new ThrowMessageJavaDelegate(clazz, emptyList());
}
public ThrowMessageDelegate createThrowMessageDelegateExpression(String delegateExpression) {
Expression expression = expressionManager.createExpression(delegateExpression);
return new ThrowMessageDelegateExpression(expression, emptyList());
}
public ThrowMessageDelegate createDefaultThrowMessageDelegate() {
return getThrowMessageDelegateFactory().create();
}
public MessagePayloadMappingProvider createMessagePayloadMappingProvider(
Event bpmnEvent,
MessageEventDefinition messageEventDefinition
) {
return getMessagePayloadMappingProviderFactory().create(
bpmnEvent,
messageEventDefinition,
getExpressionManager()
);
}
protected Optional<String> checkClassDelegate(Map<String, List<ExtensionAttribute>> attributes) {
return getAttributeValue(attributes, "class");
} | protected Optional<String> checkDelegateExpression(Map<String, List<ExtensionAttribute>> attributes) {
return getAttributeValue(attributes, "delegateExpression");
}
protected Optional<String> getAttributeValue(Map<String, List<ExtensionAttribute>> attributes, String name) {
return Optional.ofNullable(attributes)
.filter(it -> it.containsKey("activiti"))
.map(it -> it.get("activiti"))
.flatMap(it ->
it
.stream()
.filter(el -> name.equals(el.getName()))
.findAny()
)
.map(ExtensionAttribute::getValue);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java | 1 |
请完成以下Java代码 | public I_C_Invoice_Candidate retrieveInvoiceCandidate(final I_C_Flatrate_Term term)
{
final AdTableId tableId = tableDAO.retrieveAdTableId(I_C_Flatrate_Term.Table_Name);
final I_C_Invoice_Candidate ic = queryBL.createQueryBuilder(I_C_Invoice_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_AD_Table_ID, tableId)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Record_ID, term.getC_Flatrate_Term_ID())
.create()
.firstOnly(I_C_Invoice_Candidate.class);
return ic;
}
@Cached(cacheName = I_C_Flatrate_Term.Table_Name + "#by#bPartnerId#typeConditions")
public List<I_C_Flatrate_Term> retrieveTerms(
@NonNull final BPartnerId bPartnerId,
@NonNull final OrgId orgId,
@NonNull final TypeConditions typeConditions)
{
return queryBL.createQueryBuilder(I_C_Flatrate_Term.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId.getRepoId())
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Type_Conditions, typeConditions.getCode())
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId.getRepoId())
.create()
.list(I_C_Flatrate_Term.class);
}
@Override
public Set<FlatrateTermId> retrieveAllRunningSubscriptionIds(
@NonNull final BPartnerId bPartnerId,
@NonNull final Instant date,
@NonNull final OrgId orgId)
{
return existingSubscriptionsQueryBuilder(orgId, bPartnerId, date)
.create()
.idsAsSet(FlatrateTermId::ofRepoId);
}
private IQueryBuilder<I_C_Flatrate_Term> existingSubscriptionsQueryBuilder(@NonNull final OrgId orgId, @NonNull final BPartnerId bPartnerId, @NonNull final Instant date)
{
return queryBL.createQueryBuilder(I_C_Flatrate_Term.class)
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId) | .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId)
.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode())
.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode())
.addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, Operator.GREATER, date);
}
@Override
public boolean bpartnerHasExistingRunningTerms(@NonNull final I_C_Flatrate_Term flatrateTerm)
{
if (flatrateTerm.getC_Order_Term_ID() <= 0)
{
return true; // if this term has no C_Order_Term_ID, then it *is* one of those running terms
}
final Instant instant = TimeUtil.asInstant(flatrateTerm.getC_Order_Term().getDateOrdered());
final IQueryBuilder<I_C_Flatrate_Term> queryBuilder = //
existingSubscriptionsQueryBuilder(OrgId.ofRepoId(flatrateTerm.getAD_Org_ID()),
BPartnerId.ofRepoId(flatrateTerm.getBill_BPartner_ID()),
instant);
queryBuilder.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_C_Order_Term_ID, flatrateTerm.getC_Order_Term_ID());
return queryBuilder.create()
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\FlatrateDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setShowSummary(@Nullable ShowSummary showSummary) {
this.showSummary = showSummary;
}
public @Nullable ShowSummaryOutput getShowSummaryOutput() {
return this.showSummaryOutput;
}
public void setShowSummaryOutput(@Nullable ShowSummaryOutput showSummaryOutput) {
this.showSummaryOutput = showSummaryOutput;
}
public @Nullable UiService getUiService() {
return this.uiService;
}
public void setUiService(@Nullable UiService uiService) {
this.uiService = uiService;
}
public @Nullable Boolean getAnalyticsEnabled() {
return this.analyticsEnabled;
}
public void setAnalyticsEnabled(@Nullable Boolean analyticsEnabled) {
this.analyticsEnabled = analyticsEnabled;
}
public @Nullable String getLicenseKey() {
return this.licenseKey;
}
public void setLicenseKey(@Nullable String licenseKey) {
this.licenseKey = licenseKey;
}
/**
* Enumeration of types of summary to show. Values are the same as those on
* {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum
* is not used directly.
*/
public enum ShowSummary {
/**
* Do not show a summary.
*/
OFF,
/**
* Show a summary.
*/
SUMMARY,
/**
* Show a verbose summary.
*/
VERBOSE | }
/**
* Enumeration of destinations to which the summary should be output. Values are the
* same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards
* compatibility, the Liquibase enum is not used directly.
*/
public enum ShowSummaryOutput {
/**
* Log the summary.
*/
LOG,
/**
* Output the summary to the console.
*/
CONSOLE,
/**
* Log the summary and output it to the console.
*/
ALL
}
/**
* Enumeration of types of UIService. Values are the same as those on
* {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is
* not used directly.
*/
public enum UiService {
/**
* Console-based UIService.
*/
CONSOLE,
/**
* Logging-based UIService.
*/
LOGGER
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected void sendCancelEvent(JobEntity jobToDelete) {
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete),
jobServiceConfiguration.getEngineName());
}
}
protected JobEntity getJobToDelete(CommandContext commandContext) {
if (jobId == null) {
throw new FlowableIllegalArgumentException("jobId is null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deleting job {}", jobId);
} | JobEntity job = jobServiceConfiguration.getJobEntityManager().findById(jobId);
if (job == null) {
throw new FlowableObjectNotFoundException("No job found with id '" + jobId + "'", Job.class);
}
// We need to check if the job was locked, ie acquired by the job acquisition thread
// This happens if the job was already acquired, but not yet executed.
// In that case, we can't allow to delete the job.
if (job.getLockOwner() != null) {
throw new FlowableException("Cannot delete " + job + " when the job is being executed. Try again later.");
}
return job;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\DeleteJobCmd.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String token = httpServletRequest.getHeader(CommonConstant.X_ACCESS_TOKEN);
// 代码逻辑说明: JT-355 OA聊天添加token验证,获取token参数
if (oConvertUtils.isEmpty(token)) {
token = httpServletRequest.getParameter("token");
}
JwtToken jwtToken = new JwtToken(token);
// 提交给realm进行登入,如果错误他会抛出异常并被捕获
getSubject(request, response).login(jwtToken);
// 如果没有抛出异常则代表登入成功,返回true
return true;
}
/**
* 对跨域提供支持
*/
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if(allowOrigin){
httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, httpServletRequest.getHeader(HttpHeaders.ORIGIN));
// 允许客户端请求方法
httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS,PUT,DELETE");
// 允许客户端提交的Header
String requestHeaders = httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
if (StringUtils.isNotEmpty(requestHeaders)) {
httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders);
}
// 允许客户端携带凭证信息(是否允许发送Cookie)
httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
}
// 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态
if (RequestMethod.OPTIONS.name().equalsIgnoreCase(httpServletRequest.getMethod())) {
httpServletResponse.setStatus(HttpStatus.OK.value());
return false;
}
// 代码逻辑说明: 多租户用到
String tenantId = httpServletRequest.getHeader(CommonConstant.TENANT_ID); | TenantContext.setTenant(tenantId);
return super.preHandle(request, response);
}
/**
* JwtFilter中ThreadLocal需要及时清除 #3634
*
* @param request
* @param response
* @param exception
* @throws Exception
*/
@Override
public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception) throws Exception {
//log.info("------清空线程中多租户的ID={}------",TenantContext.getTenant());
TenantContext.clear();
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\shiro\filters\JwtFilter.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.