instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public static String desEncrypt(String data) throws Exception {
return decryptLegacyNoPadding(data);
}
/* 加密(若前端不再使用,可忽略;保留旧实现避免影响历史) */
@Deprecated
public static String encrypt(String data) throws Exception {
try{
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength += (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); | SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return Base64.encodeToString(encrypted);
}catch(Exception e){
throw new IllegalStateException("legacy encrypt error", e);
}
}
// public static void main(String[] args) throws Exception {
// // 前端 CBC/Pkcs7 密文测试
// String frontCipher = encrypt("sa"); // 仅验证管道是否可用(旧方式)
// System.out.println(resolvePassword(frontCipher));
// }
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\encryption\AesEncryptUtil.java | 1 |
请完成以下Java代码 | public ResponseEntity<List<AdminUserDTO>> getAllUsers(@org.springdoc.core.annotations.ParameterObject Pageable pageable) {
log.debug("REST request to get all User for an admin");
if (!onlyContainsAllowedProperties(pageable)) {
return ResponseEntity.badRequest().build();
}
final Page<AdminUserDTO> page = userService.getAllManagedUsers(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
private boolean onlyContainsAllowedProperties(Pageable pageable) {
return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains);
}
/**
* {@code GET /admin/users/:login} : get the "login" user.
*
* @param login the login of the user to find.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/users/{login}")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public ResponseEntity<AdminUserDTO> getUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
log.debug("REST request to get User : {}", login);
return ResponseUtil.wrapOrNotFound(userService.getUserWithAuthoritiesByLogin(login).map(AdminUserDTO::new));
}
/** | * {@code DELETE /admin/users/:login} : delete the "login" User.
*
* @param login the login of the user to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/users/{login}")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public ResponseEntity<Void> deleteUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
log.debug("REST request to delete User: {}", login);
userService.deleteUser(login);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, "A user is deleted with identifier " + login, login))
.build();
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-monolithic\src\main\java\com\baeldung\jhipster8\web\rest\UserResource.java | 1 |
请完成以下Java代码 | private CarrierProduct getCachedShipperProductByCode(@NonNull final ShipperId shipperId, @Nullable final String code)
{
if (code == null)
{
return null;
}
return carrierProductsByExternalId.getOrLoad(shipperId + code, () ->
queryBL.createQueryBuilder(I_Carrier_Product.class)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_M_Shipper_ID, shipperId)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_ExternalId, code)
.firstOptional()
.map(CarrierProductRepository::fromProductRecord)
.orElse(null));
}
@Nullable
public CarrierProduct getCachedShipperProductById(@Nullable final CarrierProductId productId)
{
if (productId == null)
{
return null;
}
return carrierProductsById.getOrLoad(productId.toString(), () ->
queryBL.createQueryBuilder(I_Carrier_Product.class)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_Carrier_Product_ID, productId) | .firstOptional()
.map(CarrierProductRepository::fromProductRecord)
.orElse(null));
}
@NonNull
private CarrierProduct createShipperProduct(@NonNull final ShipperId shipperId, @NonNull final String code, @NonNull final String name)
{
final I_Carrier_Product po = InterfaceWrapperHelper.newInstance(I_Carrier_Product.class);
po.setM_Shipper_ID(shipperId.getRepoId());
po.setExternalId(code);
po.setName(name);
InterfaceWrapperHelper.saveRecord(po);
return fromProductRecord(po);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierProductRepository.java | 1 |
请完成以下Java代码 | public void setSubstitute_ID (int Substitute_ID)
{
if (Substitute_ID < 1)
set_Value (COLUMNNAME_Substitute_ID, null);
else
set_Value (COLUMNNAME_Substitute_ID, Integer.valueOf(Substitute_ID));
}
/** Get Ersatz.
@return Entity which can be used in place of this entity
*/
@Override
public int getSubstitute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Substitute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Valid from including this date (first day)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Valid from including this date (first day)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
} | /** Set Gültig bis.
@param ValidTo
Valid to including this date (last day)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Valid to including this date (last day)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Substitute.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
List<ClientConnection> clientConnections = new ArrayList<>();
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
logger.info("Server started on port {}", PORT);
while (!serverSocket.isClosed()) {
acceptNewConnections(serverSocket, clientConnections);
handleRequests(clientConnections);
}
} catch (IOException e) {
logger.error("Server error", e);
} finally {
closeClientConnection(clientConnections);
}
}
private static void acceptNewConnections(ServerSocket serverSocket, List<ClientConnection> clientConnections) throws SocketException {
serverSocket.setSoTimeout(100);
try {
Socket newClient = serverSocket.accept();
ClientConnection clientConnection = new ClientConnection(newClient);
clientConnections.add(clientConnection);
logger.info("New client connected: {}", newClient.getInetAddress());
} catch (IOException ignored) {
// ignore expected socket timeout
}
}
private static void handleRequests(List<ClientConnection> clientConnections) {
Iterator<ClientConnection> iterator = clientConnections.iterator();
while (iterator.hasNext()) {
ClientConnection client = iterator.next(); | if (client.getSocket()
.isClosed()) {
logger.info("Client disconnected: {}", client.getSocket()
.getInetAddress());
iterator.remove();
continue;
}
try {
BufferedReader reader = client.getReader();
if (reader.ready()) {
String request = reader.readLine();
if (request != null) {
new ThreadPerRequest(client.getWriter(), request).start();
}
}
} catch (IOException e) {
logger.error("Error reading from client {}", client.getSocket()
.getInetAddress(), e);
}
}
}
private static void closeClientConnection(List<ClientConnection> clientConnections) {
for (ClientConnection client : clientConnections) {
try {
client.close();
} catch (IOException e) {
logger.error("Error closing client connection", e);
}
}
}
} | repos\tutorials-master\core-java-modules\core-java-sockets\src\main\java\com\baeldung\threading\request\ThreadPerRequestServer.java | 1 |
请完成以下Java代码 | public <T extends RepoIdAware> Stream<T> streamIds(@NonNull final String tableName, @NonNull final IntFunction<T> idMapper)
{
return streamByTableName(tableName)
.mapToInt(TableRecordReference::getRecord_ID)
.mapToObj(idMapper);
}
public <T extends RepoIdAware> ImmutableSet<T> getRecordIdsByTableName(@NonNull final String tableName, @NonNull final IntFunction<T> idMapper)
{
return streamIds(tableName, idMapper).collect(ImmutableSet.toImmutableSet());
}
public String getSingleTableName()
{
final ImmutableSet<String> tableNames = recordRefs.stream()
.map(TableRecordReference::getTableName)
.collect(ImmutableSet.toImmutableSet());
if (tableNames.isEmpty())
{
throw new AdempiereException("No tablename");
}
else if (tableNames.size() == 1)
{
return tableNames.iterator().next();
}
else
{
throw new AdempiereException("More than one tablename found: " + tableNames);
}
}
public Set<TableRecordReference> toSet() {return recordRefs;}
public Set<Integer> toIntSet()
{
// just to make sure that our records are from a single table
getSingleTableName();
return recordRefs.stream()
.map(TableRecordReference::getRecord_ID)
.collect(ImmutableSet.toImmutableSet());
}
public int size()
{
return recordRefs.size();
}
@NonNull
public AdTableId getSingleTableId()
{
final ImmutableSet<AdTableId> tableIds = getTableIds(); | if (tableIds.isEmpty())
{
throw new AdempiereException("No AD_Table_ID");
}
else if (tableIds.size() == 1)
{
return tableIds.iterator().next();
}
else
{
throw new AdempiereException("More than one AD_Table_ID found: " + tableIds);
}
}
public void assertSingleTableName()
{
final ImmutableSet<AdTableId> tableIds = getTableIds();
if (tableIds.isEmpty())
{
throw new AdempiereException("No AD_Table_ID");
}
else if (tableIds.size() != 1)
{
throw new AdempiereException("More than one AD_Table_ID found: " + tableIds);
}
}
public Stream<TableRecordReference> streamReferences()
{
return recordRefs.stream();
}
@NonNull
private ImmutableSet<AdTableId> getTableIds()
{
return recordRefs.stream()
.map(TableRecordReference::getAD_Table_ID)
.map(AdTableId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReferenceSet.java | 1 |
请完成以下Java代码 | public long estimateSize() {
return Long.MAX_VALUE;
}
public int characteristics() {
return Spliterator.ORDERED | Spliterator.NONNULL |
Spliterator.CONCURRENT;
}
}
/**
* Returns a {@link Spliterator} over the elements in this queue.
*
* <p>The returned spliterator is
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
*
* @return a {@code Spliterator} over the elements in this queue
* @implNote The {@code Spliterator} implements {@code trySplit} to permit limited
* parallelism.
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new CLQSpliterator<E>(this);
}
/**
* Throws NullPointerException if argument is null.
*
* @param v the element
*/
private static void checkNotNull(Object v) {
if (v == null)
throw new NullPointerException();
}
private boolean casTail(Node<E> cmp, Node<E> val) {
return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); | }
private boolean casHead(Node<E> cmp, Node<E> val) {
return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long headOffset;
private static final long tailOffset;
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
UNSAFE = (Unsafe) f.get(null);
Class<?> k = ConcurrentLinkedQueue.class;
headOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("head"));
tailOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("tail"));
} catch (Exception e) {
throw new Error(e);
}
}
} | repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\ConcurrentLinkedQueue.java | 1 |
请完成以下Java代码 | protected String getSQLSelect()
{
return m_sqlMain;
}
protected void setKeyColumnIndex(final int keyColumnIndex)
{
m_keyColumnIndex = keyColumnIndex;
}
/**
* @param row
* @return true if given row is a data row (e.g. not a totals row)
*/
public boolean isDataRow(final int row)
{
if (row < 0)
{
return false;
}
final int rows = p_table.getRowCount();
// If this is the Totals row (last row), we need to skip it - teo_sarca [ 2860556 ]
if (p_table.getShowTotals() && row == rows - 1)
{
return false;
}
return row < rows;
}
public static final String PROP_SaveSelection = "SaveSelection";
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
@Override
public void addPropertyChangeListener(final PropertyChangeListener listener)
{
pcs.addPropertyChangeListener(listener);
}
@Override
public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener)
{
pcs.addPropertyChangeListener(propertyName, listener);
}
public IInfoColumnController getInfoColumnController(final int index)
{
return p_layout[index].getColumnController();
} | public boolean isLoading()
{
if (m_worker == null)
{
return false;
}
// Check for override.
if (ignoreLoading)
{
return false;
}
return m_worker.isAlive();
}
// metas: end
public void setIgnoreLoading(final boolean ignoreLoading)
{
this.ignoreLoading = ignoreLoading;
}
private static final Properties getCtx()
{
return Env.getCtx();
}
private static final int getCtxAD_Client_ID()
{
return Env.getAD_Client_ID(getCtx());
}
} // Info | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\Info.java | 1 |
请完成以下Java代码 | private LookupValue extractCatchUOM(@NonNull final I_M_ShipmentSchedule record)
{
final UomId catchUomId = UomId.ofRepoIdOrNull(record.getCatch_UOM_ID());
return catchUomId != null
? catchUOMsLookup.findById(catchUomId)
: null;
}
private LookupValue toLookupValue(@NonNull final AttributeSetInstanceId asiId)
{
return asiId.isRegular()
? asiLookup.findById(asiId)
: IntegerLookupValue.of(asiId.getRepoId(), "");
}
private ZonedDateTime extractPreparationTime(@NonNull final I_M_ShipmentSchedule record)
{
return shipmentScheduleBL.getPreparationDate(record);
}
private Quantity extractQtyCUToDeliver(@NonNull final I_M_ShipmentSchedule record)
{
return shipmentScheduleBL.getQtyToDeliver(record);
}
private BigDecimal extractQtyToDeliverCatchOverride(@NonNull final I_M_ShipmentSchedule record) | {
return shipmentScheduleBL
.getCatchQtyOverride(record)
.map(qty -> qty.toBigDecimal())
.orElse(null);
}
private int extractSalesOrderLineNo(final I_M_ShipmentSchedule record)
{
final OrderAndLineId salesOrderAndLineId = extractSalesOrderAndLineId(record);
if (salesOrderAndLineId == null)
{
return 0;
}
final I_C_OrderLine salesOrderLine = salesOrderLines.get(salesOrderAndLineId);
if (salesOrderLine == null)
{
return 0;
}
return salesOrderLine.getLine();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidateRowsLoader.java | 1 |
请完成以下Java代码 | public class GenericEventListenerExport extends AbstractPlanItemDefinitionExport<GenericEventListener> {
@Override
protected Class<? extends GenericEventListener> getExportablePlanItemDefinitionClass() {
return GenericEventListener.class;
}
@Override
protected String getPlanItemDefinitionXmlElementValue(GenericEventListener planItemDefinition) {
return ELEMENT_GENERIC_EVENT_LISTENER;
}
@Override
protected void writePlanItemDefinitionSpecificAttributes(GenericEventListener genericEventListener, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(genericEventListener, xtw);
if (StringUtils.isNotEmpty(genericEventListener.getAvailableConditionExpression())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, | CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_AVAILABLE_CONDITION,
genericEventListener.getAvailableConditionExpression());
}
if (StringUtils.isNotEmpty(genericEventListener.getEventType()) && genericEventListener.getExtensionElements().get("eventType") == null) {
ExtensionElement extensionElement = new ExtensionElement();
extensionElement.setNamespace(FLOWABLE_EXTENSIONS_NAMESPACE);
extensionElement.setNamespacePrefix(FLOWABLE_EXTENSIONS_PREFIX);
extensionElement.setName("eventType");
extensionElement.setElementText(genericEventListener.getEventType());
genericEventListener.addExtensionElement(extensionElement);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\GenericEventListenerExport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void add(ListenableFuture<Void> future) {
futures.add(future);
}
public TenantId getTenantId() {
return user.getTenantId();
}
protected static EntityExportSettings buildExportSettings(VersionCreateConfig config) {
return EntityExportSettings.builder()
.exportRelations(config.isSaveRelations())
.exportAttributes(config.isSaveAttributes())
.exportCredentials(config.isSaveCredentials())
.exportCalculatedFields(config.isSaveCalculatedFields())
.build();
} | public abstract EntityExportSettings getSettings();
@SuppressWarnings("unchecked")
public <ID extends EntityId> ID getExternalId(ID internalId) {
var result = externalIdMap.get(internalId);
log.debug("[{}][{}] Local cache {} for id", internalId.getEntityType(), internalId.getId(), result != null ? "hit" : "miss");
return (ID) result;
}
public void putExternalId(EntityId internalId, EntityId externalId) {
log.debug("[{}][{}] Local cache put: {}", internalId.getEntityType(), internalId.getId(), externalId);
externalIdMap.put(internalId, externalId != null ? externalId : internalId);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\data\EntitiesExportCtx.java | 2 |
请完成以下Java代码 | public class MetricsClientInterceptor implements ClientInterceptor {
private final MetricsClientMeters metricsClientMeters;
private final Supplier<Stopwatch> stopwatchSupplier;
/**
* Creates a new gRPC client interceptor that collects metrics into the given
* {@link io.micrometer.core.instrument.MeterRegistry}.
*
* @param registry The MeterRegistry to use.
*/
public MetricsClientInterceptor(MeterRegistry registry, Supplier<Stopwatch> stopwatchSupplier) {
this(MetricsClientInstruments.newClientMetricsMeters(registry), stopwatchSupplier);
}
public MetricsClientInterceptor(MetricsClientMeters meters, Supplier<Stopwatch> stopwatchSupplier) {
this.metricsClientMeters = meters;
this.stopwatchSupplier = stopwatchSupplier;
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
/*
* This is a per call ClientStreamTracer.Factory which creates a new stream tracer for each attempt under the
* same call. Each call needs a dedicated factory as they share the same method descriptor.
*/
final MetricsClientStreamTracers.CallAttemptsTracerFactory tracerFactory =
new MetricsClientStreamTracers.CallAttemptsTracerFactory(
new MetricsClientStreamTracers(stopwatchSupplier),
method.getFullMethodName(),
metricsClientMeters);
ClientCall<ReqT, RespT> call =
next.newCall(method, callOptions.withStreamTracerFactory(tracerFactory)); | return new SimpleForwardingClientCall<ReqT, RespT>(call) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
delegate().start(
new SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onClose(Status status, Metadata trailers) {
tracerFactory.callEnded(status);
super.onClose(status, trailers);
}
},
headers);
}
};
}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\metrics\MetricsClientInterceptor.java | 1 |
请完成以下Java代码 | public void setM_AttributeSet_ID (int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_Value (COLUMNNAME_M_AttributeSet_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID));
}
/** Get Merkmals-Satz.
@return Product Attribute Set
*/
@Override
public int getM_AttributeSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausprägung Merkmals-Satz.
@param M_AttributeSetInstance_ID
Product Attribute Set Instance
*/
@Override
public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID));
}
/** Get Ausprägung Merkmals-Satz.
@return Product Attribute Set Instance
*/
@Override
public int getM_AttributeSetInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Lot getM_Lot() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Lot_ID, org.compiere.model.I_M_Lot.class);
}
@Override
public void setM_Lot(org.compiere.model.I_M_Lot M_Lot)
{
set_ValueFromPO(COLUMNNAME_M_Lot_ID, org.compiere.model.I_M_Lot.class, M_Lot);
}
/** Set Los.
@param M_Lot_ID
Product Lot Definition
*/ | @Override
public void setM_Lot_ID (int M_Lot_ID)
{
if (M_Lot_ID < 1)
set_Value (COLUMNNAME_M_Lot_ID, null);
else
set_Value (COLUMNNAME_M_Lot_ID, Integer.valueOf(M_Lot_ID));
}
/** Get Los.
@return Product Lot Definition
*/
@Override
public int getM_Lot_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Lot_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Serien-Nr..
@param SerNo
Product Serial Number
*/
@Override
public void setSerNo (java.lang.String SerNo)
{
set_Value (COLUMNNAME_SerNo, SerNo);
}
/** Get Serien-Nr..
@return Product Serial Number
*/
@Override
public java.lang.String getSerNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_SerNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetInstance.java | 1 |
请完成以下Java代码 | public class CaseInstanceMigrationStatusJobHandler extends AbstractCaseInstanceMigrationJobHandler {
public static final String TYPE = "case-migration-status";
@Override
public String getType() {
return TYPE;
}
@Override
public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
CmmnEngineConfiguration engineConfiguration = CommandContextUtil.getCmmnEngineConfiguration();
BatchService batchService = engineConfiguration.getBatchServiceConfiguration().getBatchService();
String batchId = getBatchIdFromHandlerCfg(configuration);
Batch batch = batchService.getBatch(batchId);
List<BatchPart> batchParts = batchService.findBatchPartsByBatchId(batchId);
int completedBatchParts = 0;
for (BatchPart batchPart : batchParts) {
if (batchPart.getCompleteTime() != null) {
completedBatchParts++; | }
}
if (completedBatchParts == batchParts.size()) {
batchService.completeBatch(batch.getId(), CaseInstanceBatchMigrationResult.STATUS_COMPLETED);
job.setRepeat(null);
} else {
if (batchParts.size() == 0) {
updateBatchStatus(batch, batchService);
job.setRepeat(null);
} else {
updateBatchStatus(batch, batchService);
}
}
}
protected void updateBatchStatus(Batch batch, BatchService batchService) {
((BatchEntity) batch).setStatus(CaseInstanceBatchMigrationResult.STATUS_COMPLETED);
batchService.updateBatch(batch);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\job\CaseInstanceMigrationStatusJobHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getSignatureAlgorithm() {
return getRequired(this.header, "alg", String.class);
}
public String getIssuer() {
return getRequired(this.claims, "iss", String.class);
}
public long getExpiry() {
return getRequired(this.claims, "exp", Integer.class).longValue();
}
@SuppressWarnings("unchecked")
public List<String> getScope() {
return getRequired(this.claims, "scope", List.class);
}
public String getKeyId() {
return getRequired(this.header, "kid", String.class);
}
@SuppressWarnings("unchecked") | private <T> T getRequired(Map<String, Object> map, String key, Class<T> type) {
Object value = map.get(key);
if (value == null) {
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Unable to get value from key " + key);
}
if (!type.isInstance(value)) {
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN,
"Unexpected value type from key " + key + " value " + value);
}
return (T) value;
}
@Override
public String toString() {
return this.encoded;
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\Token.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult update(@PathVariable Long id,
@RequestBody UmsMenu umsMenu) {
int count = menuService.update(id, umsMenu);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("根据ID获取菜单详情")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<UmsMenu> getItem(@PathVariable Long id) {
UmsMenu umsMenu = menuService.getItem(id);
return CommonResult.success(umsMenu);
}
@ApiOperation("根据ID删除后台菜单")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@PathVariable Long id) {
int count = menuService.delete(id);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("分页查询后台菜单")
@RequestMapping(value = "/list/{parentId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<UmsMenu>> list(@PathVariable Long parentId,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { | List<UmsMenu> menuList = menuService.list(parentId, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(menuList));
}
@ApiOperation("树形结构返回所有菜单列表")
@RequestMapping(value = "/treeList", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<UmsMenuNode>> treeList() {
List<UmsMenuNode> list = menuService.treeList();
return CommonResult.success(list);
}
@ApiOperation("修改菜单显示状态")
@RequestMapping(value = "/updateHidden/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateHidden(@PathVariable Long id, @RequestParam("hidden") Integer hidden) {
int count = menuService.updateHidden(id, hidden);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsMenuController.java | 2 |
请完成以下Java代码 | public Object getValue(final String propertyName, final int idx, final Class<?> returnType)
{
return getValue(propertyName, returnType);
}
@Override
public Object getValue(final String propertyName, final Class<?> returnType)
{
return pojoWrapper.getValue(propertyName, returnType);
}
@Override
public boolean setValue(final String propertyName, final Object value)
{
pojoWrapper.setValue(propertyName, value);
return true;
}
@Override
public boolean setValueNoCheck(String columnName, Object value)
{
pojoWrapper.setValue(columnName, value);
return true;
}
@Override
public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception
{
return pojoWrapper.getReferencedObject(propertyName, interfaceMethod);
}
@Override
public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value)
{
final String propertyName;
if (idPropertyName.endsWith("_ID"))
{
propertyName = idPropertyName.substring(0, idPropertyName.length() - 3);
}
else
{
throw new AdempiereException("Invalid idPropertyName: " + idPropertyName);
}
pojoWrapper.setReferencedObject(propertyName, value);
}
@Override
public boolean invokeEquals(final Object[] methodArgs) | {
return pojoWrapper.invokeEquals(methodArgs);
}
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
throw new IllegalStateException("Invoking parent method is not supported");
}
@Override
public boolean isKeyColumnName(final String columnName)
{
return pojoWrapper.isKeyColumnName(columnName);
}
@Override
public boolean isCalculated(final String columnName)
{
return pojoWrapper.isCalculated(columnName);
}
@Override
public boolean hasColumnName(String columnName)
{
return pojoWrapper.hasColumnName(columnName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOModelInternalAccessor.java | 1 |
请完成以下Java代码 | public String nextForkGatewayId(Map<String, FlowElement> flowElementMap) {
return nextId("dynamicForkGateway", flowElementMap);
}
public String nextJoinGatewayId(Map<String, FlowElement> flowElementMap) {
return nextId("dynamicJoinGateway", flowElementMap);
}
public String nextStartEventId(Map<String, FlowElement> flowElementMap) {
return nextId("startEvent", flowElementMap);
}
public String nextEndEventId(Map<String, FlowElement> flowElementMap) {
return nextId("endEvent", flowElementMap);
} | protected String nextId(String prefix, Map<String, FlowElement> flowElementMap) {
String nextId = null;
boolean nextIdNotFound = true;
while (nextIdNotFound) {
if (!flowElementMap.containsKey(prefix + counter)) {
nextId = prefix + counter;
nextIdNotFound = false;
}
counter++;
}
return nextId;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\DynamicEmbeddedSubProcessBuilder.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} | Authority authority = (Authority) o;
return !(name != null ? !name.equals(authority.name) : authority.name != null);
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
@Override
public String toString() {
return "Authority{" +
"name='" + name + '\'' +
"}";
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\Authority.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
BigInteger bigInteger = null;
String textValue = valueFields.getTextValue();
if (textValue != null && !textValue.isEmpty()) {
bigInteger = new BigInteger(textValue);
}
return bigInteger;
}
@Override | public void setValue(Object value, ValueFields valueFields) {
if (value != null) {
valueFields.setTextValue(value.toString());
} else {
valueFields.setTextValue(null);
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return BigInteger.class.isAssignableFrom(value.getClass());
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\BigIntegerType.java | 2 |
请完成以下Java代码 | public void setTimerJobRunnable(AcquireTimerJobsRunnable timerJobRunnable) {
this.timerJobRunnable = timerJobRunnable;
}
public int getDefaultQueueSizeFullWaitTimeInMillis() {
return defaultQueueSizeFullWaitTime;
}
public void setDefaultQueueSizeFullWaitTimeInMillis(int defaultQueueSizeFullWaitTime) {
this.defaultQueueSizeFullWaitTime = defaultQueueSizeFullWaitTime;
}
public void setAsyncJobsDueRunnable(AcquireAsyncJobsDueRunnable asyncJobsDueRunnable) {
this.asyncJobsDueRunnable = asyncJobsDueRunnable;
}
public void setResetExpiredJobsRunnable(ResetExpiredJobsRunnable resetExpiredJobsRunnable) {
this.resetExpiredJobsRunnable = resetExpiredJobsRunnable;
}
public int getRetryWaitTimeInMillis() {
return retryWaitTimeInMillis;
}
public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) {
this.retryWaitTimeInMillis = retryWaitTimeInMillis;
}
public int getResetExpiredJobsInterval() {
return resetExpiredJobsInterval;
} | public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) {
this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public ExecuteAsyncRunnableFactory getExecuteAsyncRunnableFactory() {
return executeAsyncRunnableFactory;
}
public void setExecuteAsyncRunnableFactory(ExecuteAsyncRunnableFactory executeAsyncRunnableFactory) {
this.executeAsyncRunnableFactory = executeAsyncRunnableFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\DefaultAsyncJobExecutor.java | 1 |
请完成以下Java代码 | private boolean authenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return this.trustResolver.isAuthenticated(authentication);
}
/**
* Indicates if the request is elgible to be processed as the proxy receptor.
* @param request
* @return
*/
@SuppressWarnings("NullAway") // Dataflow analysis limitation
private boolean proxyReceptorRequest(HttpServletRequest request) {
final boolean result = proxyReceptorConfigured() && this.proxyReceptorMatcher.matches(request);
this.logger.debug(LogMessage.format("proxyReceptorRequest = %s", result));
return result;
}
/**
* Determines if the {@link CasAuthenticationFilter} is configured to handle the proxy
* receptor requests.
* @return
*/
private boolean proxyReceptorConfigured() {
final boolean result = this.proxyGrantingTicketStorage != null && this.proxyReceptorMatcher != null;
this.logger.debug(LogMessage.format("proxyReceptorConfigured = %s", result));
return result;
}
/**
* A wrapper for the AuthenticationFailureHandler that will flex the
* {@link AuthenticationFailureHandler} that is used. The value
* {@link CasAuthenticationFilter#setProxyAuthenticationFailureHandler(AuthenticationFailureHandler)}
* will be used for proxy requests that fail. The value | * {@link CasAuthenticationFilter#setAuthenticationFailureHandler(AuthenticationFailureHandler)}
* will be used for service tickets that fail.
*/
private class CasAuthenticationFailureHandler implements AuthenticationFailureHandler {
private final AuthenticationFailureHandler serviceTicketFailureHandler;
CasAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler");
this.serviceTicketFailureHandler = failureHandler;
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
if (serviceTicketRequest(request, response)) {
this.serviceTicketFailureHandler.onAuthenticationFailure(request, response, exception);
}
else {
CasAuthenticationFilter.this.proxyFailureHandler.onAuthenticationFailure(request, response, exception);
}
}
}
} | repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\CasAuthenticationFilter.java | 1 |
请完成以下Java代码 | private static String computeShipmentScheduleStatus(
@NonNull final DeliveryLineCandidate deliveryLineCandidate,
@NonNull final IShipmentSchedulesDuringUpdate shipmentCandidates)
{
final CompleteStatus completeStatus = deliveryLineCandidate.getCompleteStatus();
if (!IShipmentSchedulesDuringUpdate.CompleteStatus.OK.equals(completeStatus))
{
final String statusMessage = Services.get(IMsgBL.class).getMsg(Env.getCtx(), completeStatus.toString());
shipmentCandidates.addStatusInfo(deliveryLineCandidate, statusMessage);
}
return shipmentCandidates.getStatusInfos(deliveryLineCandidate);
}
public static BigDecimal computeQtyToDeliver(
@NonNull final BigDecimal qtyRequired,
@NonNull final BigDecimal qtyPickedOrOnDraftShipmentOrShipped)
{
final BigDecimal qtyToDeliver = qtyRequired.subtract(qtyPickedOrOnDraftShipmentOrShipped);
final BigDecimal result = qtyToDeliver.signum() > 0 ? qtyToDeliver : BigDecimal.ZERO;
logger.debug("qtyRequired={}; qtyPicked_Or_OnDraftShipment_Or_Shipped={}; -> qtyToDeliver={}", qtyRequired, qtyPickedOrOnDraftShipmentOrShipped, result);
return result;
}
public static BigDecimal computeQtyToDeliverOverrideFulFilled( | @NonNull final OlAndSched olAndSched,
@NonNull final IShipmentScheduleAllocDAO shipmentScheduleAllocDAO)
{
final I_M_ShipmentSchedule sched = olAndSched.getSched();
final BigDecimal qtyDelivered = shipmentScheduleAllocDAO.retrieveQtyDelivered(sched);
final BigDecimal deliveredDiff = qtyDelivered.subtract(olAndSched.getInitialSchedQtyDelivered());
final BigDecimal newQtyToDeliverOverrideFulfilled = sched.getQtyToDeliver_OverrideFulfilled().add(deliveredDiff);
if (newQtyToDeliverOverrideFulfilled.signum() < 0)
{
return BigDecimal.ZERO;
}
return newQtyToDeliverOverrideFulfilled;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleQtysHelper.java | 1 |
请完成以下Java代码 | public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getUsing() {
return using;
}
public void setUsing(String using) {
this.using = using;
}
public String getUsingdate() {
return usingdate;
}
public void setUsingdate(String usingdate) {
this.usingdate = usingdate;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
} | public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getQrcantonid() {
return qrcantonid;
}
public void setQrcantonid(String qrcantonid) {
this.qrcantonid = qrcantonid;
}
public String getDeclare() {
return declare;
}
public void setDeclare(String declare) {
this.declare = declare;
}
public String getDeclareisend() {
return declareisend;
}
public void setDeclareisend(String declareisend) {
this.declareisend = declareisend;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\Canton.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_AcctSchema getC_AcctSchema()
{
return get_ValueAsPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class);
}
@Override
public void setC_AcctSchema(org.compiere.model.I_C_AcctSchema C_AcctSchema)
{
set_ValueFromPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class, C_AcctSchema);
}
/** Set Buchführungs-Schema.
@param C_AcctSchema_ID
Stammdaten für Buchhaltung
*/
@Override
public void setC_AcctSchema_ID (int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
}
/** Get Buchführungs-Schema.
@return Stammdaten für Buchhaltung
*/
@Override
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Buchungsdatum.
@param DateAcct
Accounting Date
*/
@Override
public void setDateAcct (java.sql.Timestamp DateAcct)
{
set_ValueNoCheck (COLUMNNAME_DateAcct, DateAcct);
}
/** Get Buchungsdatum.
@return Accounting Date
*/
@Override
public java.sql.Timestamp getDateAcct ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateAcct);
}
/** Set Accounting Fact.
@param Fact_Acct_ID Accounting Fact */
@Override
public void setFact_Acct_ID (int Fact_Acct_ID)
{
if (Fact_Acct_ID < 1)
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID));
}
/** Get Accounting Fact.
@return Accounting Fact */
@Override
public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null) | return 0;
return ii.intValue();
}
/**
* PostingType AD_Reference_ID=125
* Reference name: _Posting Type
*/
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Actual Year End = Y */
public static final String POSTINGTYPE_ActualYearEnd = "Y";
/** Set Buchungsart.
@param PostingType
Die Art des gebuchten Betrages dieser Transaktion
*/
@Override
public void setPostingType (java.lang.String PostingType)
{
set_ValueNoCheck (COLUMNNAME_PostingType, PostingType);
}
/** Get Buchungsart.
@return Die Art des gebuchten Betrages dieser Transaktion
*/
@Override
public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_EndingBalance.java | 1 |
请完成以下Java代码 | public static boolean isSetter(Method method) {
return isSetter(method, false);
}
public static String getGetterShorthandName(Method method) {
if (!isGetter(method)) {
return method.getName();
}
String name = method.getName();
if (name.startsWith("get")) {
name = name.substring(3);
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
} else if (name.startsWith("is")) {
name = name.substring(2);
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
} | return name;
}
public static String getSetterShorthandName(Method method) {
if (!isSetter(method)) {
return method.getName();
}
String name = method.getName();
if (name.startsWith("set")) {
name = name.substring(3);
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
}
return name;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\ReflectUtil.java | 1 |
请完成以下Java代码 | public Salary getSalary() {
return salary;
}
public void setSalary(Salary salary) {
this.salary = salary;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public LocalDate getDateOfJoining() {
return dateOfJoining;
}
public void setDateOfJoining(LocalDate dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}
public PhoneNumber getEmployeeNumber() { | return employeeNumber;
}
public void setEmployeeNumber(PhoneNumber employeeNumber) {
this.employeeNumber = employeeNumber;
}
public Address getEmpAddress() {
return empAddress;
}
public void setEmpAddress(Address empAddress) {
this.empAddress = empAddress;
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\OfficeEmployee.java | 1 |
请完成以下Java代码 | public Object getPersistentState() {
return new PersistentState(name, bytes);
}
@Override
public int getRevisionNext() {
return revision + 1;
}
// getters and setters //////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public int getRevision() {
return revision;
}
@Override
public void setRevision(int revision) { | this.revision = revision;
}
@Override
public String toString() {
return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]";
}
// Wrapper for a byte array, needed to do byte array comparisons
// See https://activiti.atlassian.net/browse/ACT-1524
private static class PersistentState {
private final String name;
private final byte[] bytes;
public PersistentState(String name, byte[] bytes) {
this.name = name;
this.bytes = bytes;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PersistentState) {
PersistentState other = (PersistentState) obj;
return Objects.equals(this.name, other.name)
&& Arrays.equals(this.bytes, other.bytes);
}
return false;
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebClientController {
@ResponseStatus(HttpStatus.OK)
@GetMapping("/resource")
public Map<String, String> getResource() {
Map<String, String> response = new HashMap<>();
response.put("field", "value");
return response;
}
@PostMapping("/resource")
public Mono<String> postStringResource(@RequestBody Mono<String> bodyString) {
return bodyString.map(body -> "processed-" + body);
} | @PostMapping("/resource-override")
public Mono<String> postStringResourceOverride(@RequestBody Mono<String> bodyString) {
return bodyString.map(body -> "override-processed-" + body);
}
@PostMapping("/resource-foo")
public Mono<String> postFooResource(@RequestBody Mono<Foo> bodyFoo) {
return bodyFoo.map(foo -> "processedFoo-" + foo.getName());
}
@PostMapping(value = "/resource-multipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String handleFormUpload(@RequestPart("key1") String value1, @RequestPart("key2") String value2) {
return "processed-" + value1 + '-' + value2;
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\webclient\WebClientController.java | 2 |
请完成以下Java代码 | public class RetourenavisAnfrageType {
@XmlElement(name = "Position", required = true)
protected List<RetourePositionType> position;
@XmlAttribute(name = "ID", required = true)
protected String id;
@XmlAttribute(name = "RetoureSupportID", required = true)
protected int retoureSupportID;
/**
* Gets the value of the position 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 position property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPosition().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link RetourePositionType }
*
*
*/
public List<RetourePositionType> getPosition() {
if (position == null) {
position = new ArrayList<RetourePositionType>();
}
return this.position;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setID(String value) {
this.id = value;
}
/**
* Gets the value of the retoureSupportID property.
*
*/
public int getRetoureSupportID() {
return retoureSupportID;
}
/**
* Sets the value of the retoureSupportID property.
*
*/
public void setRetoureSupportID(int value) {
this.retoureSupportID = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnfrageType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JpaOrder extends AbstractEntity
{
@Column(name = "mf_bpartner_id")
@NotNull
private Integer mfBpartnerId;
@Column(name = "mf_bpartnerlocation_id")
@NotNull
private Integer mfBpartnerLocationId;
@NotNull
private String documentNo;
@NotNull
private Integer supportId;
@NotNull
private Boolean nightOperation;
@NotNull
private OrderStatus orderStatus;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "order", cascade = CascadeType.ALL)
private final List<JpaOrderPackage> orderPackages = new ArrayList<>();
//
//
private boolean syncSent;
private Instant syncSentTS;
private boolean mfSyncAck;
private Instant syncAckTS;
private boolean mfSyncError;
private String mfSyncErrorMsg;
private Instant syncErrorTS; | public void addOrderPackages(@NonNull final List<JpaOrderPackage> orderPackages)
{
orderPackages.forEach(orderPackage -> orderPackage.setOrder(this));
this.orderPackages.addAll(orderPackages);
}
public void visitItems(@NonNull final Consumer<JpaOrderPackageItem> consumer)
{
orderPackages.stream()
.flatMap(orderPackage -> orderPackage.getItems().stream())
.forEach(consumer);
}
public void markSyncSent()
{
syncSent = true;
syncSentTS = Instant.now();
}
public void markSyncAck()
{
mfSyncAck = true;
syncAckTS = Instant.now();
}
public void markSyncError(final String errorMsg)
{
mfSyncError = true;
mfSyncErrorMsg = errorMsg;
syncErrorTS = Instant.now();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\order\jpa\JpaOrder.java | 2 |
请完成以下Java代码 | public void showCodeSnippetCommentsFormattingUsingCodeAndLiteralTag() {
// do nothing
}
/**
* This is an example to illustrate a basic jQuery code snippet embedded in documentation comments
* <pre>
* {@code <script>}
* $document.ready(function(){
* console.log("Hello World!);
* })
* {@code </script>}
* </pre>
*/
public void showJSCodeSnippetUsingJavadoc() {
// do nothing
}
/**
* This is an example to illustrate an HTML code snippet embedded in documentation comments
* <pre>{@code
* <html>
* <body>
* <h1>Hello World!</h1>
* </body>
* </html>}
* </pre>
*
*/
public void showHTMLCodeSnippetUsingJavadoc() { | // do nothing
}
/**
* This is an example to illustrate an HTML code snippet embedded in documentation comments
* <pre>
* <html>
* <body>
* <h1>Hello World!</h1>
* </body>
* </html>
* </pre>
*
*/
public void showHTMLCodeSnippetIssueUsingJavadoc() {
// do nothing
}
} | repos\tutorials-master\core-java-modules\core-java-documentation\src\main\java\com\baeldung\javadoc\CodeSnippetFormatting.java | 1 |
请完成以下Java代码 | public BigDecimal getCtrlSum() {
return ctrlSum;
}
/**
* Sets the value of the ctrlSum property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setCtrlSum(BigDecimal value) {
this.ctrlSum = value;
}
/**
* Gets the value of the initgPty property.
*
* @return
* possible object is
* {@link PartyIdentification32CHNameAndId }
*
*/
public PartyIdentification32CHNameAndId getInitgPty() {
return initgPty;
}
/**
* Sets the value of the initgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification32CHNameAndId }
*
*/
public void setInitgPty(PartyIdentification32CHNameAndId value) {
this.initgPty = value;
} | /**
* Gets the value of the fwdgAgt property.
*
* @return
* possible object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public BranchAndFinancialInstitutionIdentification4 getFwdgAgt() {
return fwdgAgt;
}
/**
* Sets the value of the fwdgAgt property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public void setFwdgAgt(BranchAndFinancialInstitutionIdentification4 value) {
this.fwdgAgt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\GroupHeader32CH.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Sequence getAD_Sequence()
{
return get_ValueAsPO(COLUMNNAME_AD_Sequence_ID, org.compiere.model.I_AD_Sequence.class);
}
@Override
public void setAD_Sequence(final org.compiere.model.I_AD_Sequence AD_Sequence)
{
set_ValueFromPO(COLUMNNAME_AD_Sequence_ID, org.compiere.model.I_AD_Sequence.class, AD_Sequence);
}
@Override
public void setAD_Sequence_ID (final int AD_Sequence_ID)
{
if (AD_Sequence_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, AD_Sequence_ID);
}
@Override
public int getAD_Sequence_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Sequence_ID);
}
@Override
public void setCalendarDay (final @Nullable java.lang.String CalendarDay)
{
set_Value (COLUMNNAME_CalendarDay, CalendarDay);
}
@Override
public java.lang.String getCalendarDay()
{
return get_ValueAsString(COLUMNNAME_CalendarDay);
}
@Override
public void setCalendarMonth (final @Nullable java.lang.String CalendarMonth)
{
set_Value (COLUMNNAME_CalendarMonth, CalendarMonth);
}
@Override
public java.lang.String getCalendarMonth()
{
return get_ValueAsString(COLUMNNAME_CalendarMonth);
} | @Override
public void setCalendarYear (final java.lang.String CalendarYear)
{
set_ValueNoCheck (COLUMNNAME_CalendarYear, CalendarYear);
}
@Override
public java.lang.String getCalendarYear()
{
return get_ValueAsString(COLUMNNAME_CalendarYear);
}
@Override
public void setCurrentNext (final int CurrentNext)
{
set_Value (COLUMNNAME_CurrentNext, CurrentNext);
}
@Override
public int getCurrentNext()
{
return get_ValueAsInt(COLUMNNAME_CurrentNext);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_No.java | 1 |
请完成以下Java代码 | public String getClassName() {
return this.className;
}
public void setClassName(String className) {
this.className = className;
}
/**
* Return the init parameters used to configure the JSP servlet.
* @return the init parameters
*/
public Map<String, String> getInitParameters() {
return this.initParameters;
}
public void setInitParameters(Map<String, String> initParameters) { | this.initParameters = initParameters;
}
/**
* Return whether the JSP servlet is registered.
* @return {@code true} to register the JSP servlet
*/
public boolean getRegistered() {
return this.registered;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\Jsp.java | 1 |
请完成以下Java代码 | public class RequestReOpen extends JavaProcess
{
/** Request */
private int p_R_Request_ID = 0;
/**
* Prepare
*/
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("R_Request_ID"))
p_R_Request_ID = para[i].getParameterAsInt();
else
log.error("prepare - Unknown Parameter: " + name);
}
} // prepare
/**
* Process It
* @return message
* @throws Exception | */
protected String doIt () throws Exception
{
MRequest request = new MRequest (getCtx(), p_R_Request_ID, get_TrxName());
log.info(request.toString());
if (request.get_ID() == 0)
throw new AdempiereUserError("@NotFound@ @R_Request_ID@ " + p_R_Request_ID);
request.setR_Status_ID(); // set default status
request.setProcessed(false);
if (request.save() && !request.isProcessed())
return "@OK@";
return "@Error@";
} // doUt
} // RequestReOpen | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\RequestReOpen.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result delete(@RequestParam(name = "id") String id) {
Result result = new Result();
OssFile file = ossFileService.getById(id);
if (file == null) {
result.error500("未找到对应实体");
}else {
boolean ok = ossFileService.delete(file);
result.success("删除成功!");
}
return result;
}
/**
* 通过id查询.
*/ | @ResponseBody
@GetMapping("/queryById")
public Result<OssFile> queryById(@RequestParam(name = "id") String id) {
Result<OssFile> result = new Result<>();
OssFile file = ossFileService.getById(id);
if (file == null) {
result.error500("未找到对应实体");
}
else {
result.setResult(file);
result.setSuccess(true);
}
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\oss\controller\OssFileController.java | 2 |
请完成以下Java代码 | private static <T> T fromObjectTo(
@NonNull final Object valueObj,
@NonNull final Class<T> type,
@NonNull final Function<String, T> fromJsonConverter,
@NonNull final Function<Object, T> fromObjectConverter)
{
if (type.isInstance(valueObj))
{
return type.cast(valueObj);
}
else if (valueObj instanceof CharSequence)
{
final String json = valueObj.toString().trim();
if (json.isEmpty())
{
return null;
}
if (json.length() == 21 && json.charAt(10) == ' ') // json string - possible in JDBC format (`2016-06-11 00:00:00.0`) | {
final Timestamp timestamp = Timestamp.valueOf(json);
return fromObjectConverter.apply(timestamp);
}
else
{
return fromJsonConverter.apply(json);
}
}
else
{
return fromObjectConverter.apply(valueObj);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\converter\DateTimeConverters.java | 1 |
请完成以下Java代码 | protected void registerTabCallouts(final ITabCalloutFactory tabCalloutsRegistry)
{
// nothing on this level
}
/**
* Called onInit to setup module table callouts
*
* @param calloutsRegistry
*/
protected void registerCallouts(@NonNull final IProgramaticCalloutProvider calloutsRegistry)
{
// nothing on this level
}
private void setupEventBus()
{
final List<Topic> userNotificationsTopics = getAvailableUserNotificationsTopics();
if (userNotificationsTopics != null && !userNotificationsTopics.isEmpty())
{
final IEventBusFactory eventBusFactory = Services.get(IEventBusFactory.class);
for (final Topic topic : userNotificationsTopics)
{
eventBusFactory.addAvailableUserNotificationsTopic(topic);
}
}
}
/**
* @return available user notifications topics to listen
*/
protected List<Topic> getAvailableUserNotificationsTopics()
{
return ImmutableList.of();
}
private void setupMigrationScriptsLogger()
{
final Set<String> tableNames = getTableNamesToSkipOnMigrationScriptsLogging();
if (tableNames != null && !tableNames.isEmpty())
{
final IMigrationLogger migrationLogger = Services.get(IMigrationLogger.class);
migrationLogger.addTablesToIgnoreList(tableNames);
}
} | protected Set<String> getTableNamesToSkipOnMigrationScriptsLogging() {return ImmutableSet.of();}
@Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing
}
/**
* Does nothing. Module interceptors are not allowed to intercept models or documents
*/
@Override
public final void onModelChange(final Object model, final ModelChangeType changeType)
{
// nothing
}
/**
* Does nothing. Module interceptors are not allowed to intercept models or documents
*/
@Override
public final void onDocValidate(final Object model, final DocTimingType timing)
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AbstractModuleInterceptor.java | 1 |
请完成以下Java代码 | public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Role name.
@param RoleName Role name */
@Override
public void setRoleName (java.lang.String RoleName)
{
set_Value (COLUMNNAME_RoleName, RoleName); | }
/** Get Role name.
@return Role name */
@Override
public java.lang.String getRoleName ()
{
return (java.lang.String)get_Value(COLUMNNAME_RoleName);
}
/** Set UserValue.
@param UserValue UserValue */
@Override
public void setUserValue (java.lang.String UserValue)
{
set_Value (COLUMNNAME_UserValue, UserValue);
}
/** Get UserValue.
@return UserValue */
@Override
public java.lang.String getUserValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_User.java | 1 |
请完成以下Java代码 | public Map<String, DataObject> getDataObjects(String taskId) {
return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, null));
}
@Override
public Map<String, DataObject> getDataObjects(String taskId, String locale, boolean withLocalizationFallback) {
return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, null, locale, withLocalizationFallback));
}
@Override
public Map<String, DataObject> getDataObjects(String taskId, Collection<String> dataObjectNames) {
return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, dataObjectNames));
}
@Override
public Map<String, DataObject> getDataObjects(
String taskId,
Collection<String> dataObjectNames,
String locale,
boolean withLocalizationFallback
) {
return commandExecutor.execute(
new GetTaskDataObjectsCmd(taskId, dataObjectNames, locale, withLocalizationFallback)
);
} | @Override
public DataObject getDataObject(String taskId, String dataObject) {
return commandExecutor.execute(new GetTaskDataObjectCmd(taskId, dataObject));
}
@Override
public DataObject getDataObject(
String taskId,
String dataObjectName,
String locale,
boolean withLocalizationFallback
) {
return commandExecutor.execute(
new GetTaskDataObjectCmd(taskId, dataObjectName, locale, withLocalizationFallback)
);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Boolean hSetAll(String key, Map<String, Object> map, long time) {
redisTemplate.opsForHash().putAll(key, map);
return expire(key, time);
}
@Override
public void hSetAll(String key, Map<String, ?> map) {
redisTemplate.opsForHash().putAll(key, map);
}
@Override
public void hDel(String key, Object... hashKey) {
redisTemplate.opsForHash().delete(key, hashKey);
}
@Override
public Boolean hHasKey(String key, String hashKey) {
return redisTemplate.opsForHash().hasKey(key, hashKey);
}
@Override
public Long hIncr(String key, String hashKey, Long delta) {
return redisTemplate.opsForHash().increment(key, hashKey, delta);
}
@Override
public Long hDecr(String key, String hashKey, Long delta) {
return redisTemplate.opsForHash().increment(key, hashKey, -delta);
}
@Override
public Set<Object> sMembers(String key) {
return redisTemplate.opsForSet().members(key);
}
@Override
public Long sAdd(String key, Object... values) {
return redisTemplate.opsForSet().add(key, values);
}
@Override
public Long sAdd(String key, long time, Object... values) {
Long count = redisTemplate.opsForSet().add(key, values);
expire(key, time);
return count;
}
@Override
public Boolean sIsMember(String key, Object value) {
return redisTemplate.opsForSet().isMember(key, value);
}
@Override
public Long sSize(String key) {
return redisTemplate.opsForSet().size(key);
}
@Override
public Long sRemove(String key, Object... values) {
return redisTemplate.opsForSet().remove(key, values);
}
@Override
public List<Object> lRange(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
@Override
public Long lSize(String key) {
return redisTemplate.opsForList().size(key);
}
@Override | public Object lIndex(String key, long index) {
return redisTemplate.opsForList().index(key, index);
}
@Override
public Long lPush(String key, Object value) {
return redisTemplate.opsForList().rightPush(key, value);
}
@Override
public Long lPush(String key, Object value, long time) {
Long index = redisTemplate.opsForList().rightPush(key, value);
expire(key, time);
return index;
}
@Override
public Long lPushAll(String key, Object... values) {
return redisTemplate.opsForList().rightPushAll(key, values);
}
@Override
public Long lPushAll(String key, Long time, Object... values) {
Long count = redisTemplate.opsForList().rightPushAll(key, values);
expire(key, time);
return count;
}
@Override
public Long lRemove(String key, long count, Object value) {
return redisTemplate.opsForList().remove(key, count, value);
}
} | repos\mall-master\mall-common\src\main\java\com\macro\mall\common\service\impl\RedisServiceImpl.java | 2 |
请完成以下Java代码 | public boolean isNoRecords()
{
return noRecords || toSqlAndParams() == SQL_ALWAYS_FALSE;
}
public SqlAndParams toSqlAndParams()
{
if (noRecords)
{
return SQL_ALWAYS_FALSE;
}
else
{
SqlAndParams viewSelectionWhereClause;
if (rowsPresentInViewSelection == null || rowsPresentInViewSelection.isEmpty())
{
viewSelectionWhereClause = null;
}
else if (isRowsNotPresentInViewSelection)
{
viewSelectionWhereClause = rowsPresentInViewSelection.negate();
}
else
{
viewSelectionWhereClause = rowsPresentInViewSelection;
}
return SqlAndParams.andNullables(viewSelectionWhereClause, rowsPresentInTable, rowsMatchingFilter)
.orElse(SQL_ALWAYS_FALSE);
}
}
public String toSqlString()
{
return toSqlAndParams().toSqlStringInlineParams();
} | public <T> IQueryFilter<T> toQueryFilter()
{
final SqlAndParams sqlAndParams = toSqlAndParams();
return TypedSqlQueryFilter.of(sqlAndParams.getSql(), sqlAndParams.getSqlParams());
}
public SqlViewRowsWhereClause withRowsNotPresentInViewSelection()
{
return !this.isRowsNotPresentInViewSelection
? toBuilder().isRowsNotPresentInViewSelection(true).build()
: this;
}
public SqlViewRowsWhereClause withRowsMatchingFilter(@Nullable final SqlAndParams rowsMatchingFilter)
{
return !Objects.equals(this.rowsMatchingFilter, rowsMatchingFilter)
? toBuilder().rowsMatchingFilter(rowsMatchingFilter).build()
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewRowsWhereClause.java | 1 |
请完成以下Java代码 | public Collection<Column> getColumns() {
return columnCollection.get(this);
}
public Collection<Row> getRows() {
return rowCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Relation.class, DMN_ELEMENT_RELATION)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<Relation>() {
public Relation newInstance(ModelTypeInstanceContext instanceContext) {
return new RelationImpl(instanceContext); | }
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
columnCollection = sequenceBuilder.elementCollection(Column.class)
.build();
rowCollection = sequenceBuilder.elementCollection(Row.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\RelationImpl.java | 1 |
请完成以下Java代码 | public class Order {
private final String orderId;
private final Map<String, Integer> products;
private OrderStatus orderStatus;
public Order(String orderId) {
this.orderId = orderId;
this.products = new HashMap<>();
orderStatus = OrderStatus.CREATED;
}
public String getOrderId() {
return orderId;
}
public Map<String, Integer> getProducts() {
return products;
}
public OrderStatus getOrderStatus() {
return orderStatus;
}
public void addProduct(String productId) {
products.putIfAbsent(productId, 1);
}
public void incrementProductInstance(String productId) {
products.computeIfPresent(productId, (id, count) -> ++count);
}
public void decrementProductInstance(String productId) {
products.computeIfPresent(productId, (id, count) -> --count);
}
public void removeProduct(String productId) {
products.remove(productId);
}
public void setOrderConfirmed() {
this.orderStatus = OrderStatus.CONFIRMED;
}
public void setOrderShipped() { | this.orderStatus = OrderStatus.SHIPPED;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order that = (Order) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(products, that.products) && orderStatus == that.orderStatus;
}
@Override
public int hashCode() {
return Objects.hash(orderId, products, orderStatus);
}
@Override
public String toString() {
return "Order{" + "orderId='" + orderId + '\'' + ", products=" + products + ", orderStatus=" + orderStatus + '}';
}
} | repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\queries\Order.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Job cantonJob(JobBuilderFactory jobBuilderFactory, @Qualifier("cantonStep1") Step s1) {
return jobBuilderFactory.get("cantonJob")
.incrementer(new RunIdIncrementer())
.flow(s1)//为Job指定Step
.end()
.listener(new MyJobListener())//绑定监听器csvJobListener
.build();
}
/**
* step步骤,包含ItemReader,ItemProcessor和ItemWriter
*
* @param stepBuilderFactory
* @param reader
* @param writer
* @param processor
* @return
*/
@Bean(name = "cantonStep1")
public Step cantonStep1(StepBuilderFactory stepBuilderFactory,
@Qualifier("cantonReader") ItemReader<Canton> reader,
@Qualifier("cantonWriter") ItemWriter<Canton> writer,
@Qualifier("cantonProcessor") ItemProcessor<Canton, Canton> processor) {
return stepBuilderFactory
.get("cantonStep1")
.<Canton, Canton>chunk(5000)//批处理每次提交5000条数据 | .reader(reader)//给step绑定reader
.processor(processor)//给step绑定processor
.writer(writer)//给step绑定writer
.faultTolerant()
.retry(Exception.class) // 重试
.noRetry(ParseException.class)
.retryLimit(1) //每条记录重试一次
.skip(Exception.class)
.skipLimit(200) //一共允许跳过200次异常
// .taskExecutor(new SimpleAsyncTaskExecutor()) //设置每个Job通过并发方式执行,一般来讲一个Job就让它串行完成的好
// .throttleLimit(10) //并发任务数为 10,默认为4
.build();
}
@Bean
public Validator<Canton> csvBeanValidator() {
return new MyBeanValidator<>();
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\CantonConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Action<Chain> download() {
return chain -> chain.get("download", ctx -> {
ctx.getResponse().sendStream(new RandomBytesPublisher(1024,512));
});
}
@Bean
public Action<Chain> downloadChunks() {
return chain -> chain.get("downloadChunks", ctx -> {
ctx.render(ResponseChunks.bufferChunks("application/octetstream",
new RandomBytesPublisher(1024,512)));
});
}
@Bean
public ServerConfig ratpackServerConfig() {
return ServerConfig
.builder()
.findBaseDir("public")
.build();
}
public static void main(String[] args) {
SpringApplication.run(EmbedRatpackStreamsApp.class, args);
}
public static class RandomBytesPublisher implements Publisher<ByteBuf> {
private int bufCount;
private int bufSize;
private Random rnd = new Random();
RandomBytesPublisher(int bufCount, int bufSize) {
this.bufCount = bufCount;
this.bufSize = bufSize;
}
@Override
public void subscribe(Subscriber<? super ByteBuf> s) {
s.onSubscribe(new Subscription() {
private boolean cancelled = false;
private boolean recurse;
private long requested = 0;
@Override
public void request(long n) {
if ( bufCount == 0 ) {
s.onComplete();
return;
}
requested += n;
if ( recurse ) {
return;
} | recurse = true;
try {
while ( requested-- > 0 && !cancelled && bufCount-- > 0 ) {
byte[] data = new byte[bufSize];
rnd.nextBytes(data);
ByteBuf buf = Unpooled.wrappedBuffer(data);
s.onNext(buf);
}
}
finally {
recurse = false;
}
}
@Override
public void cancel() {
cancelled = true;
}
});
}
}
} | repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\spring\EmbedRatpackStreamsApp.java | 2 |
请完成以下Java代码 | public final class ALoginRes_ca extends ListResourceBundle
{
// TODO Run native2ascii to convert to plain ASCII !!
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "Connection", "Connexi\u00f3" },
{ "Defaults", "Valors Predeterminats" },
{ "Login", "Acc\u00e9s ADempiere" },
{ "File", "Fitxer" },
{ "Exit", "Sortir" },
{ "Help", "Ajuda" },
{ "About", "Referent" },
{ "Host", "Servidor" },
{ "Database", "Base de Dades" },
{ "User", "Usuari" },
{ "EnterUser", "Introdu\u00efr Usuari Aplicaci\u00f3" },
{ "Password", "Contrasenya" },
{ "EnterPassword", "Entrar Contrasenya Usuari Aplicaci\u00f3" },
{ "Language", "Idioma" },
{ "SelectLanguage", "Seleccioni Idioma" },
{ "Role", "Rol" },
{ "Client", "Entitat" },
{ "Organization", "Organitzaci\u00f3" },
{ "Date", "Data" },
{ "Warehouse", "Magatzem" },
{ "Printer", "Impressora" },
{ "Connected", "Connectat" },
{ "NotConnected", "No Connectat" },
{ "DatabaseNotFound", "No s'ha trobat la Base de Dades" }, | { "UserPwdError", "No coincideix l'Usuari i la Contrasenya" },
{ "RoleNotFound", "Rol no trobat/completat" },
{ "Authorized", "Autoritzat" },
{ "Ok", "Acceptar" },
{ "Cancel", "Cancel.lar" },
{ "VersionConflict", "Conflicte Versions:" },
{ "VersionInfo", "Servidor <> Client" },
{ "PleaseUpgrade", "Descarregui una nova versi\u00f3 del Programa" }
};
/**
* Get Contents
* @return context
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // ALoginRes_ca | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes_ca.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Dashboard getOrCreateMonitoringDashboard() {
Dashboard existing = findDashboardByTitle(DASHBOARD_TITLE).orElse(null);
if (existing != null) {
log.debug("Found Monitoring dashboard '{}' with id {}", existing.getTitle(), existing.getId());
return existing;
}
Dashboard dashboardFromResource = ResourceUtils.getResource(DASHBOARD_RESOURCE_PATH, Dashboard.class);
dashboardFromResource.setTitle(DASHBOARD_TITLE);
//Optional.ofNullable(existing).map(Dashboard::getId).ifPresent(dashboardFromResource::setId);
Dashboard saved = tbClient.saveDashboard(dashboardFromResource);
log.info("Created Monitoring dashboard '{}' with id {}", saved.getTitle(), saved.getId());
return saved;
}
private Optional<Dashboard> findDashboardByTitle(String title) {
// Use text search first and then filter by exact title
PageData<DashboardInfo> page = tbClient.getTenantDashboards(new PageLink(10, 0, title));
return page.getData().stream()
.filter(info -> title.equals(info.getTitle()))
.findFirst()
.flatMap(info -> tbClient.getDashboardById(info.getId()));
}
private String buildPublicDashboardLink(DashboardId dashboardId, String publicCustomerId) {
String base = getBaseUrl(); | return String.format("%s/dashboard/%s?publicId=%s", base, dashboardId.getId().toString(), publicCustomerId);
}
private String getBaseUrl() {
// TbClient.baseURL contains the root url, without trailing slash
try {
var baseUrlField = tbClient.getClass().getSuperclass().getDeclaredField("baseURL");
baseUrlField.setAccessible(true);
return (String) baseUrlField.get(tbClient);
} catch (Exception e) {
log.warn("Unable to access baseURL from RestClient. Falling back to http://localhost:8080");
return "http://localhost:8080";
}
}
} | repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\service\MonitoringEntityService.java | 2 |
请完成以下Java代码 | public final class AuthenticationObservationConvention
implements ObservationConvention<AuthenticationObservationContext> {
static final String OBSERVATION_NAME = "spring.security.authentications";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return OBSERVATION_NAME;
}
@Override
public String getContextualName(AuthenticationObservationContext context) {
if (context.getAuthenticationRequest() != null) {
String authenticationType = context.getAuthenticationRequest().getClass().getSimpleName();
if (authenticationType.endsWith("Token")) {
authenticationType = authenticationType.substring(0, authenticationType.lastIndexOf("Token"));
}
if (authenticationType.endsWith("Authentication")) {
authenticationType = authenticationType.substring(0, authenticationType.lastIndexOf("Authentication"));
}
return "authenticate " + authenticationType.toLowerCase(Locale.ENGLISH);
}
return "authenticate";
}
/**
* {@inheritDoc}
*/
@Override
public @NonNull KeyValues getLowCardinalityKeyValues(@NonNull AuthenticationObservationContext context) {
return KeyValues.of("authentication.request.type", getAuthenticationType(context))
.and("authentication.method", getAuthenticationMethod(context))
.and("authentication.result.type", getAuthenticationResult(context))
.and("authentication.failure.type", getAuthenticationFailureType(context));
}
private String getAuthenticationType(AuthenticationObservationContext context) {
if (context.getAuthenticationRequest() == null) {
return "unknown";
}
return context.getAuthenticationRequest().getClass().getSimpleName();
}
private String getAuthenticationMethod(AuthenticationObservationContext context) {
if (context.getAuthenticationManagerClass() == null) {
return "unknown"; | }
return context.getAuthenticationManagerClass().getSimpleName();
}
private String getAuthenticationResult(AuthenticationObservationContext context) {
if (context.getAuthenticationResult() == null) {
return "n/a";
}
return context.getAuthenticationResult().getClass().getSimpleName();
}
private String getAuthenticationFailureType(AuthenticationObservationContext context) {
if (context.getError() == null) {
return "n/a";
}
return context.getError().getClass().getSimpleName();
}
/**
* {@inheritDoc}
*/
@Override
public boolean supportsContext(Observation.Context context) {
return context instanceof AuthenticationObservationContext;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\AuthenticationObservationConvention.java | 1 |
请完成以下Java代码 | public void setFinishedBefore(Date finishedBefore) {
this.finishedBefore = finishedBefore;
}
@CamundaQueryParam(value = "processInstanceIdIn", converter = StringArrayConverter.class)
public void setProcessInstanceIdIn(String[] processInstanceIdIn) {
this.processInstanceIdIn = processInstanceIdIn;
}
@Override
protected boolean isValidSortByValue(String value) {
return SORT_ORDER_ACTIVITY_ID.equals(value);
}
@Override
protected HistoricActivityStatisticsQuery createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createHistoricActivityStatisticsQuery(processDefinitionId);
}
@Override
protected void applyFilters(HistoricActivityStatisticsQuery query) {
if (includeCanceled != null && includeCanceled) {
query.includeCanceled();
}
if (includeFinished != null && includeFinished) {
query.includeFinished();
}
if (includeCompleteScope != null && includeCompleteScope) {
query.includeCompleteScope();
}
if (includeIncidents !=null && includeIncidents) { | query.includeIncidents();
}
if (startedAfter != null) {
query.startedAfter(startedAfter);
}
if (startedBefore != null) {
query.startedBefore(startedBefore);
}
if (finishedAfter != null) {
query.finishedAfter(finishedAfter);
}
if (finishedBefore != null) {
query.finishedBefore(finishedBefore);
}
if (processInstanceIdIn != null) {
query.processInstanceIdIn(processInstanceIdIn);
}
}
@Override
protected void applySortBy(HistoricActivityStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (SORT_ORDER_ACTIVITY_ID.equals(sortBy)) {
query.orderByActivityId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricActivityStatisticsQueryDto.java | 1 |
请完成以下Java代码 | public void closeView(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction)
{
getViewsStorageFor(viewId).closeById(viewId, closeAction);
logger.trace("Closed/Removed view {} using close action {}", viewId, closeAction);
}
@Override
public void invalidateView(final ViewId viewId)
{
getViewsStorageFor(viewId).invalidateView(viewId);
logger.trace("Invalided view {}", viewId);
}
@Override
public void invalidateView(final IView view)
{
invalidateView(view.getViewId());
}
@Override
public void notifyRecordsChangedAsync(@NonNull final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
logger.trace("No changed records provided. Skip notifying views.");
return;
}
async.execute(() -> notifyRecordsChangedNow(recordRefs));
}
@Override
public void notifyRecordsChangedNow(@NonNull final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
logger.trace("No changed records provided. Skip notifying views.");
return;
}
try (final IAutoCloseable ignored = ViewChangesCollector.currentOrNewThreadLocalCollector())
{
for (final IViewsIndexStorage viewsIndexStorage : viewsIndexStorages.values())
{
notifyRecordsChangedNow(recordRefs, viewsIndexStorage);
}
notifyRecordsChangedNow(recordRefs, defaultViewsIndexStorage);
}
}
private void notifyRecordsChangedNow(
@NonNull final TableRecordReferenceSet recordRefs,
@NonNull final IViewsIndexStorage viewsIndexStorage)
{
final ImmutableList<IView> views = viewsIndexStorage.getAllViews(); | if (views.isEmpty())
{
return;
}
final MutableInt notifiedCount = MutableInt.zero();
for (final IView view : views)
{
try
{
final boolean watchedByFrontend = isWatchedByFrontend(view.getViewId());
view.notifyRecordsChanged(recordRefs, watchedByFrontend);
notifiedCount.incrementAndGet();
}
catch (final Exception ex)
{
logger.warn("Failed calling notifyRecordsChanged on view={} with recordRefs={}. Ignored.", view, recordRefs, ex);
}
}
logger.debug("Notified {} views in {} about changed records: {}", notifiedCount, viewsIndexStorage, recordRefs);
}
@lombok.Value(staticConstructor = "of")
private static class ViewFactoryKey
{
WindowId windowId;
JSONViewDataType viewType;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewsRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Duration getTimeout() {
return this.timeout;
}
public void setTimeout(@Nullable Duration timeout) {
this.timeout = timeout;
}
public Servlet getServlet() {
return this.servlet;
}
public void setServlet(Servlet servlet) {
this.servlet = servlet;
}
/**
* Determine the session timeout. If no timeout is configured, the
* {@code fallbackTimeout} is used.
* @param fallbackTimeout a fallback timeout value if the timeout isn't configured
* @return the session timeout
* @deprecated since 4.0.1 for removal in 4.2.0 in favor of {@link SessionTimeout}
*/
@Deprecated(since = "4.0.1", forRemoval = true)
public Duration determineTimeout(Supplier<Duration> fallbackTimeout) {
return (this.timeout != null) ? this.timeout : fallbackTimeout.get();
}
/**
* Servlet-related properties.
*/
public static class Servlet {
/**
* Session repository filter order.
*/
private int filterOrder = SessionRepositoryFilter.DEFAULT_ORDER;
/**
* Session repository filter dispatcher types.
*/
private Set<DispatcherType> filterDispatcherTypes = new HashSet<>(
Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST)); | public int getFilterOrder() {
return this.filterOrder;
}
public void setFilterOrder(int filterOrder) {
this.filterOrder = filterOrder;
}
public Set<DispatcherType> getFilterDispatcherTypes() {
return this.filterDispatcherTypes;
}
public void setFilterDispatcherTypes(Set<DispatcherType> filterDispatcherTypes) {
this.filterDispatcherTypes = filterDispatcherTypes;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\autoconfigure\SessionProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void createEngineProperty(@RequestBody PropertyRequestBody propertyRequestBody) {
validateAccessToProperties();
Map<String, String> properties = managementService.getProperties();
String propertyName = propertyRequestBody.getName();
if (properties.containsKey(propertyName)) {
throw new FlowableConflictException("Engine property " + propertyName + " already exists");
}
managementService.executeCommand(commandContext -> {
PropertyEntityManager propertyEntityManager = CommandContextUtil.getPropertyEntityManager(commandContext);
PropertyEntity propertyEntity = propertyEntityManager.create();
propertyEntity.setName(propertyName);
propertyEntity.setValue(propertyRequestBody.getValue());
propertyEntityManager.insert(propertyEntity);
return null;
});
}
@ApiOperation(value = "Update an engine property", tags = { "EngineProperties" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the property is updated"),
@ApiResponse(code = 404, message = "Indicates the property is not found")
})
@PutMapping(value = "/management/engine-properties/{engineProperty}", produces = "application/json")
public void updateEngineProperty(@ApiParam(name = "engineProperty") @PathVariable String engineProperty, @RequestBody PropertyRequestBody propertyRequestBody) {
validateAccessToProperties();
validatePropertyExists(engineProperty);
managementService.executeCommand(commandContext -> {
PropertyEntityManager propertyEntityManager = CommandContextUtil.getPropertyEntityManager(commandContext);
PropertyEntity propertyEntity = propertyEntityManager.findById(engineProperty);
propertyEntity.setValue(propertyRequestBody.getValue());
propertyEntityManager.update(propertyEntity);
return null;
});
}
public static class PropertyRequestBody { | protected String name;
protected String value;
public PropertyRequestBody() {
}
public PropertyRequestBody(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\EnginePropertiesResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (contractValue == null ? 0 : contractValue.hashCode());
result = prime * result + (messageNo == null ? 0 : messageNo.hashCode());
result = prime * result + (partner == null ? 0 : partner.hashCode());
result = prime * result + (record == null ? 0 : record.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final T100 other = (T100)obj;
if (contractValue == null)
{
if (other.contractValue != null)
{
return false;
}
}
else if (!contractValue.equals(other.contractValue))
{
return false;
}
if (messageNo == null)
{
if (other.messageNo != null)
{
return false;
}
}
else if (!messageNo.equals(other.messageNo))
{
return false;
}
if (partner == null)
{
if (other.partner != null) | {
return false;
}
}
else if (!partner.equals(other.partner))
{
return false;
}
if (record == null)
{
if (other.record != null)
{
return false;
}
}
else if (!record.equals(other.record))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "T100 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", contractValue=" + contractValue + "]";
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\compudata\T100.java | 2 |
请完成以下Java代码 | public void setEMailCount (final int EMailCount)
{
throw new IllegalArgumentException ("EMailCount is virtual column"); }
@Override
public int getEMailCount()
{
return get_ValueAsInt(COLUMNNAME_EMailCount);
}
@Override
public void setFileName (final @Nullable String FileName)
{
set_Value (COLUMNNAME_FileName, FileName);
}
@Override
public String getFileName()
{
return get_ValueAsString(COLUMNNAME_FileName);
}
@Override
public void setIsEdiEnabled (final boolean IsEdiEnabled)
{
throw new IllegalArgumentException ("IsEdiEnabled is virtual column"); }
@Override
public boolean isEdiEnabled()
{
return get_ValueAsBoolean(COLUMNNAME_IsEdiEnabled);
}
@Override
public void setIsInvoiceEmailEnabled (final boolean IsInvoiceEmailEnabled)
{
set_Value (COLUMNNAME_IsInvoiceEmailEnabled, IsInvoiceEmailEnabled);
}
@Override
public boolean isInvoiceEmailEnabled()
{
return get_ValueAsBoolean(COLUMNNAME_IsInvoiceEmailEnabled);
}
@Override
public void setPDFCount (final int PDFCount)
{
throw new IllegalArgumentException ("PDFCount is virtual column"); }
@Override
public int getPDFCount()
{
return get_ValueAsInt(COLUMNNAME_PDFCount);
}
@Override
public void setPOReference (final @Nullable String POReference)
{
set_ValueNoCheck (COLUMNNAME_POReference, POReference);
}
@Override
public String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference); | }
@Override
public void setPrintCount (final int PrintCount)
{
throw new IllegalArgumentException ("PrintCount is virtual column"); }
@Override
public int getPrintCount()
{
return get_ValueAsInt(COLUMNNAME_PrintCount);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setStoreCount (final int StoreCount)
{
throw new IllegalArgumentException ("StoreCount is virtual column"); }
@Override
public int getStoreCount()
{
return get_ValueAsInt(COLUMNNAME_StoreCount);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java-gen\de\metas\document\archive\model\X_C_Doc_Outbound_Log.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class POSTerminalId implements RepoIdAware
{
int repoId;
private POSTerminalId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_POS_ID");
}
public static POSTerminalId ofRepoId(final int repoId)
{
return new POSTerminalId(repoId);
}
@JsonCreator
public static POSTerminalId ofString(@NonNull final String str)
{
return RepoIdAwares.ofObject(str, POSTerminalId.class, POSTerminalId::ofRepoId);
}
@Nullable
public static POSTerminalId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new POSTerminalId(repoId) : null; | }
public static int toRepoId(@Nullable final OrderId id)
{
return id != null ? id.getRepoId() : -1;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final POSTerminalId id1, @Nullable final POSTerminalId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSTerminalId.java | 2 |
请完成以下Java代码 | public boolean isPostalValidated()
{
return get_ValueAsBoolean(COLUMNNAME_IsPostalValidated);
}
@Override
public void setLatitude (final @Nullable BigDecimal Latitude)
{
set_Value (COLUMNNAME_Latitude, Latitude);
}
@Override
public BigDecimal getLatitude()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Latitude);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setLongitude (final @Nullable BigDecimal Longitude)
{
set_Value (COLUMNNAME_Longitude, Longitude);
}
@Override
public BigDecimal getLongitude()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Longitude);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPOBox (final @Nullable java.lang.String POBox)
{
set_ValueNoCheck (COLUMNNAME_POBox, POBox);
}
@Override
public java.lang.String getPOBox()
{
return get_ValueAsString(COLUMNNAME_POBox);
}
@Override
public void setPostal (final @Nullable java.lang.String Postal)
{ | set_ValueNoCheck (COLUMNNAME_Postal, Postal);
}
@Override
public java.lang.String getPostal()
{
return get_ValueAsString(COLUMNNAME_Postal);
}
@Override
public void setPostal_Add (final @Nullable java.lang.String Postal_Add)
{
set_ValueNoCheck (COLUMNNAME_Postal_Add, Postal_Add);
}
@Override
public java.lang.String getPostal_Add()
{
return get_ValueAsString(COLUMNNAME_Postal_Add);
}
@Override
public void setRegionName (final @Nullable java.lang.String RegionName)
{
set_ValueNoCheck (COLUMNNAME_RegionName, RegionName);
}
@Override
public java.lang.String getRegionName()
{
return get_ValueAsString(COLUMNNAME_RegionName);
}
@Override
public void setStreet (final @Nullable java.lang.String Street)
{
set_Value (COLUMNNAME_Street, Street);
}
@Override
public java.lang.String getStreet()
{
return get_ValueAsString(COLUMNNAME_Street);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Location.java | 1 |
请完成以下Java代码 | private void processCURow(final HUEditorRow selectedCuRow)
{
final ArrayList<String> availableSerialNumbers = getSerialNumbers();
if (availableSerialNumbers.isEmpty())
{
return;
}
final HUEditorRow parentRow = getParentHURowOrNull(selectedCuRow);
final HUEditorRow topLevelRow = parentRow == null ? null : getParentHURowOrNull(parentRow);
final HUEditorRow.HUEditorRowHierarchy huEditorRowHierarchy = HUEditorRow.HUEditorRowHierarchy.builder()
.cuRow(selectedCuRow)
.parentRow(parentRow)
.topLevelRow(topLevelRow)
.build();
final WebuiHUTransformCommandResult result = WEBUIHUCreationWithSerialNumberService.builder()
.documentCollections(documentsCollection)
.view(getView())
.build()
.action_CreateCUs_With_SerialNumbers(huEditorRowHierarchy, availableSerialNumbers);
updateViewFromResult(result);
}
private HUEditorRow getParentHURowOrNull(final HUEditorRow cuRow)
{
if (cuRow == null)
{
return null;
}
return getView().getParentRowByChildIdOrNull(cuRow.getId());
}
private boolean isAggregateHU(final HUEditorRow huRow)
{
final I_M_HU hu = huRow.getM_HU();
return handlingUnitsBL.isAggregateHU(hu);
}
private final void updateViewFromResult(final WebuiHUTransformCommandResult result)
{
final HUEditorView view = getView();
view.addHUIds(result.getHuIdsToAddToView());
view.removeHUIds(result.getHuIdsToRemoveFromView());
if (!result.getHuIdsChanged().isEmpty())
{
removeHUsIfDestroyed(result.getHuIdsChanged());
} | }
/** @return true if view was changed and needs invalidation */
private final boolean removeSelectedRowsIfHUDestoyed()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty())
{
return false;
}
else if (selectedRowIds.isAll())
{
return false;
}
final HUEditorView view = getView();
final ImmutableSet<HuId> selectedHUIds = view.streamByIds(selectedRowIds)
.map(HUEditorRow::getHuId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
return removeHUsIfDestroyed(selectedHUIds);
}
/**
* @return true if at least one HU was removed
*/
private boolean removeHUsIfDestroyed(final Collection<HuId> huIds)
{
final ImmutableSet<HuId> destroyedHUIds = huIds.stream()
.distinct()
.map(huId -> load(huId, I_M_HU.class))
.filter(Services.get(IHandlingUnitsBL.class)::isDestroyed)
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
if (destroyedHUIds.isEmpty())
{
return false;
}
final HUEditorView view = getView();
final boolean changes = view.removeHUIds(destroyedHUIds);
return changes;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_Add_Batch_SerialNo_To_CUs.java | 1 |
请完成以下Java代码 | public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Summary Level.
@param IsSummary
This is a summary entity
*/
public void setIsSummary (boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary));
}
/** Get Summary Level.
@return This is a summary entity
*/
public boolean isSummary ()
{
Object oo = get_Value(COLUMNNAME_IsSummary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName | @return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SalesRegion.java | 1 |
请完成以下Java代码 | public class CompensationEventSubscriptionWalker extends ReferenceWalker<EventSubscriptionEntity> {
public CompensationEventSubscriptionWalker(Collection<MigratingActivityInstance> collection) {
super(collectCompensationEventSubscriptions(collection));
}
protected static List<EventSubscriptionEntity> collectCompensationEventSubscriptions(Collection<MigratingActivityInstance> activityInstances) {
List<EventSubscriptionEntity> eventSubscriptions = new ArrayList<EventSubscriptionEntity>();
for (MigratingActivityInstance activityInstance : activityInstances) {
if (activityInstance.getSourceScope().isScope()) {
ExecutionEntity scopeExecution = activityInstance.resolveRepresentativeExecution();
eventSubscriptions.addAll(scopeExecution.getCompensateEventSubscriptions());
}
}
return eventSubscriptions; | }
@Override
protected Collection<EventSubscriptionEntity> nextElements() {
EventSubscriptionEntity eventSubscriptionEntity = getCurrentElement();
ExecutionEntity compensatingExecution = CompensationUtil.getCompensatingExecution(eventSubscriptionEntity);
if (compensatingExecution != null) {
return compensatingExecution.getCompensateEventSubscriptions();
}
else {
return Collections.emptyList();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\CompensationEventSubscriptionWalker.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode() {
int result = nullSafeHashCode(this.itemType);
result = 31 * result + nullSafeHashCode(this.name);
result = 31 * result + nullSafeHashCode(this.type);
result = 31 * result + nullSafeHashCode(this.description);
result = 31 * result + nullSafeHashCode(this.sourceType);
result = 31 * result + nullSafeHashCode(this.sourceMethod);
result = 31 * result + nullSafeHashCode(this.defaultValue);
result = 31 * result + nullSafeHashCode(this.deprecation);
return result;
}
private boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
return o1.equals(o2);
}
private int nullSafeHashCode(Object o) {
return (o != null) ? o.hashCode() : 0;
}
@Override
public String toString() {
StringBuilder string = new StringBuilder(this.name);
buildToStringProperty(string, "type", this.type);
buildToStringProperty(string, "sourceType", this.sourceType);
buildToStringProperty(string, "description", this.description);
buildToStringProperty(string, "defaultValue", this.defaultValue);
buildToStringProperty(string, "deprecation", this.deprecation);
return string.toString();
}
private void buildToStringProperty(StringBuilder string, String property, Object value) {
if (value != null) {
string.append(" ").append(property).append(":").append(value);
}
}
@Override
public int compareTo(ItemMetadata o) {
return getName().compareTo(o.getName());
}
public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) {
return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null);
} | public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType,
String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) {
return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description,
defaultValue, deprecation);
}
public static String newItemMetadataPrefix(String prefix, String suffix) {
return prefix.toLowerCase(Locale.ENGLISH) + ConventionUtils.toDashedCase(suffix);
}
/**
* The item type.
*/
public enum ItemType {
/**
* Group item type.
*/
GROUP,
/**
* Property item type.
*/
PROPERTY
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemMetadata.java | 2 |
请完成以下Java代码 | public AssignableInvoiceCandidate withoutRefundInvoiceCandidates()
{
return toBuilder()
.clearAssignmentsToRefundCandidates()
.build();
}
public boolean isAssigned()
{
return !assignmentsToRefundCandidates.isEmpty();
}
public SplitResult splitQuantity(@NonNull final BigDecimal qtyToSplit)
{
Check.errorIf(qtyToSplit.compareTo(quantity.toBigDecimal()) >= 0,
"The given qtyToSplit={} needs to be less than this instance's quantity; this={}",
qtyToSplit, this);
final Quantity newQuantity = Quantity.of(qtyToSplit, quantity.getUOM());
final Quantity remainderQuantity = quantity.subtract(qtyToSplit);
final BigDecimal newFraction = qtyToSplit
.setScale(precision * 2, RoundingMode.HALF_UP)
.divide(quantity.toBigDecimal(), RoundingMode.HALF_UP);
final BigDecimal newMoneyValue = money
.toBigDecimal()
.setScale(precision, RoundingMode.HALF_UP)
.multiply(newFraction)
.setScale(precision, RoundingMode.HALF_UP);
final Money newMoney = Money.of(newMoneyValue, money.getCurrencyId()); | final Money remainderMoney = money.subtract(newMoney);
final AssignableInvoiceCandidate remainderCandidate = toBuilder()
.quantity(remainderQuantity)
.money(remainderMoney)
.build();
final AssignableInvoiceCandidate newCandidate = toBuilder()
.id(id)
.quantity(newQuantity)
.money(newMoney)
.build();
return new SplitResult(remainderCandidate, newCandidate);
}
@Value
public static final class SplitResult
{
AssignableInvoiceCandidate remainder;
AssignableInvoiceCandidate newCandidate;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignableInvoiceCandidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Employee {
@Id
private int id;
private String name;
@ElementCollection
@CollectionTable(name = "employee_phone", joinColumns = @JoinColumn(name = "employee_id"))
private List<Phone> phones;
public Employee() {
}
public Employee(int id) {
this.id = id;
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
} | public void setName(String name) {
this.name = name;
}
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Employee)) {
return false;
}
Employee user = (Employee) o;
return getId() == user.getId();
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise-2\src\main\java\com\baeldung\elementcollection\model\Employee.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public V get(Object key) {
if (!this.loaders.containsKey(key)) {
throw new IllegalArgumentException(
"This map only supports the following keys: " + this.loaders.keySet());
}
return this.loaded.computeIfAbsent((K) key, (k) -> this.loaders.get(k).get());
}
@Override
public V put(K key, V value) {
if (!this.loaders.containsKey(key)) {
throw new IllegalArgumentException(
"This map only supports the following keys: " + this.loaders.keySet());
}
return this.loaded.put(key, value);
}
@Override
public V remove(Object key) {
if (!this.loaders.containsKey(key)) {
throw new IllegalArgumentException(
"This map only supports the following keys: " + this.loaders.keySet());
}
return this.loaded.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
this.loaded.clear();
}
@Override
public boolean containsValue(Object value) {
return this.loaded.containsValue(value);
}
@Override
public Collection<V> values() {
return this.loaded.values();
} | @Override
public Set<Entry<K, V>> entrySet() {
return this.loaded.entrySet();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoadingMap<?, ?> that = (LoadingMap<?, ?>) o;
return this.loaded.equals(that.loaded);
}
@Override
public int hashCode() {
return this.loaded.hashCode();
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\SecurityReactorContextConfiguration.java | 2 |
请完成以下Java代码 | public String buildStorageInvoiceHistorySQL(final boolean showDetail, final int warehouseId, final int asiId)
{
final StringBuilder sql;
if (showDetail)
{
sql = new StringBuilder("SELECT s.QtyOnHand, s.QtyReserved, s.QtyOrdered, asi.description, s.M_AttributeSetInstance_ID, ");
}
else
{
sql = new StringBuilder("SELECT SUM(s.QtyOnHand), SUM(s.QtyReserved), SUM(s.QtyOrdered), asi.description, 0,");
}
sql.append(" w.Name, l.Value ")
.append("FROM " + I_M_Storage.Table_Name + " s")
.append(" INNER JOIN M_Locator l ON (s.M_Locator_ID=l.M_Locator_ID)")
.append(" INNER JOIN M_Warehouse w ON (l.M_Warehouse_ID=w.M_Warehouse_ID) ")
.append(" INNER JOIN M_AttributeSetInstance asi ON (asi.M_AttributeSetInstance_ID = s.M_AttributeSetInstance_ID) ")
.append("WHERE M_Product_ID=?");
if (warehouseId != 0)
{
sql.append(" AND l.M_Warehouse_ID=?");
}
if (asiId > 0)
{ | sql.append(" AND s.M_AttributeSetInstance_ID=?");
}
sql.append(" AND (s.QtyOnHand<>0 OR s.QtyReserved<>0 OR s.QtyOrdered<>0)");
if (!showDetail)
{
sql.append(" GROUP BY asi.description, w.Name, l.Value");
}
sql.append(" ORDER BY l.Value");
return sql.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\dao\impl\InvoiceHistoryDAO.java | 1 |
请完成以下Java代码 | public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return !locked;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
} | public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
// public Boolean getEnabled() {
// return enabled;
// }
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
} | repos\springboot-demo-master\security\src\main\java\com\et\security\entity\User.java | 1 |
请完成以下Java代码 | public PageData<QueueStats> findByTenantId(TenantId tenantId, PageLink pageLink) {
log.trace("Executing findByTenantId, tenantId: [{}]", tenantId);
Validator.validatePageLink(pageLink);
return queueStatsDao.findAllByTenantId(tenantId, pageLink);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
log.trace("Executing deleteByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
queueStatsDao.deleteByTenantId(tenantId);
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
queueStatsDao.removeById(tenantId, id.getId());
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build());
} | @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findQueueStatsById(tenantId, new QueueStatsId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(queueStatsDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.QUEUE_STATS;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\queue\BaseQueueStatsService.java | 1 |
请完成以下Java代码 | protected boolean isCreateMessageIds() {
return this.createMessageIds;
}
@Override
public final Message toMessage(Object object, MessageProperties messageProperties)
throws MessageConversionException {
return toMessage(object, messageProperties, null);
}
@Override
public final Message toMessage(Object object, @Nullable MessageProperties messagePropertiesArg,
@Nullable Type genericType)
throws MessageConversionException {
MessageProperties messageProperties = messagePropertiesArg;
if (messageProperties == null) {
messageProperties = new MessageProperties();
}
Message message = createMessage(object, messageProperties, genericType);
messageProperties = message.getMessageProperties();
if (this.createMessageIds && messageProperties.getMessageId() == null) {
messageProperties.setMessageId(UUID.randomUUID().toString());
}
return message;
}
/**
* Crate a message from the payload object and message properties provided. The message id will be added to the
* properties if necessary later.
* @param object the payload | * @param messageProperties the message properties (headers)
* @param genericType the type to convert from - used to populate type headers.
* @return a message
* @since 2.1
*/
protected Message createMessage(Object object, MessageProperties messageProperties, @Nullable Type genericType) {
return createMessage(object, messageProperties);
}
/**
* Crate a message from the payload object and message properties provided. The message id will be added to the
* properties if necessary later.
* @param object the payload.
* @param messageProperties the message properties (headers).
* @return a message.
*/
protected abstract Message createMessage(Object object, MessageProperties messageProperties);
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\AbstractMessageConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DistributionNetworkAndLineId
{
@NonNull DistributionNetworkId networkId;
@NonNull DistributionNetworkLineId lineId;
public static DistributionNetworkAndLineId of(final DistributionNetworkId ddNetworkDistributionId, final DistributionNetworkLineId ddNetworkDistributionLineId)
{
return new DistributionNetworkAndLineId(ddNetworkDistributionId, ddNetworkDistributionLineId);
}
public static DistributionNetworkAndLineId ofRepoIds(final int ddNetworkDistributionId, final int ddNetworkDistributionLineId)
{
return of(DistributionNetworkId.ofRepoId(ddNetworkDistributionId), DistributionNetworkLineId.ofRepoId(ddNetworkDistributionLineId));
}
@Nullable
public static DistributionNetworkAndLineId ofRepoIdsOrNull(final int ddNetworkDistributionRepoId, final int ddNetworkDistributionLineRepoId)
{
final DistributionNetworkId networkId = DistributionNetworkId.ofRepoIdOrNull(ddNetworkDistributionRepoId);
if (networkId == null)
{
return null;
} | final DistributionNetworkLineId lineId = DistributionNetworkLineId.ofRepoIdOrNull(ddNetworkDistributionLineRepoId);
if (lineId == null)
{
return null;
}
return of(networkId, lineId);
}
public static Optional<DistributionNetworkAndLineId> optionalOfRepoIds(final int ddNetworkDistributionRepoId, final int ddNetworkDistributionLineRepoId)
{
return Optional.ofNullable(ofRepoIdsOrNull(ddNetworkDistributionRepoId, ddNetworkDistributionLineRepoId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\material\planning\ddorder\DistributionNetworkAndLineId.java | 2 |
请完成以下Spring Boot application配置 | dubbo:
application:
# 应用名称
name: dubbo-provider
protocol:
# 协议名称
name: dubbo
# 协议端口
port: 20880
registry:
# 注册中心地址
address: zookeeper://127.0.0.1:2181
ser | ver:
# 修改端口号,避免端口冲突
port: 8081
logging:
config: classpath:logback-spring.xml | repos\springboot-demo-master\dubbo\dubbo-samples-spring-boot-provider\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public class OAuth2GrantedAuthoritiesMapper implements GrantedAuthoritiesMapper {
private static final Logger logger = LoggerFactory.getLogger(OAuth2GrantedAuthoritiesMapper.class);
private final OAuth2Properties oAuth2Properties;
public OAuth2GrantedAuthoritiesMapper(OAuth2Properties oAuth2Properties) {
this.oAuth2Properties = oAuth2Properties;
}
@Override
public Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) {
var identityProviderProperties = oAuth2Properties.getIdentityProvider();
var groupNameAttribute = identityProviderProperties.getGroupNameAttribute();
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
authorities.forEach(authority -> {
if (authority instanceof OAuth2UserAuthority) {
var oauth2UserAuthority = (OAuth2UserAuthority) authority;
Object groupAttribute = oauth2UserAuthority.getAttributes().get(groupNameAttribute);
if (groupAttribute == null) {
logger.debug("Attribute {} is not available", groupNameAttribute);
return;
}
if (groupAttribute instanceof Collection) {
//noinspection unchecked
Collection<String> groupsAttribute = (Collection<String>) groupAttribute;
var grantedAuthorities = groupsAttribute.stream() | .map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
mappedAuthorities.addAll(grantedAuthorities);
} else if (groupAttribute instanceof String) {
String groupNameDelimiter = identityProviderProperties.getGroupNameDelimiter();
String groupsAttribute = (String) groupAttribute;
var grantedAuthorities = Arrays.stream(groupsAttribute.split(groupNameDelimiter))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
mappedAuthorities.addAll(grantedAuthorities);
} else {
logger.error("Could not map granted authorities, unsupported group attribute type: {}", groupAttribute.getClass());
}
}
});
logger.debug("Authorities mapped from {} to {}", authorities, mappedAuthorities);
return mappedAuthorities;
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\impl\OAuth2GrantedAuthoritiesMapper.java | 1 |
请完成以下Java代码 | private void fireAllEventsProcessedCheck(@NonNull final EventDescriptor eventDescriptor)
{
Check.assumeNotNull(eventDescriptor.getTraceId(), "eventDescriptor.getTraceId() is not null; eventDescriptor={}", eventDescriptor);
trxManager
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(ITrxListenerManager.TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(innerTrx -> notifyIfAllEventsProcessed(eventDescriptor));
}
private void notifyIfAllEventsProcessed(@NonNull final EventDescriptor eventDescriptor)
{
final String traceId = Check.assumeNotNull(eventDescriptor.getTraceId(),
"eventDescriptor.getTraceId() is not null; eventDescriptor={}", eventDescriptor);
final EventProgress eventProgress = traceId2EventProgress.get(traceId);
if (eventProgress == null)
{
return;
} | if (eventProgress.areAllEventsProcessed())
{
notifyLocalAndRemoteObserver(eventDescriptor);
}
}
private void notifyLocalAndRemoteObserver(@NonNull final EventDescriptor eventDescriptor)
{
final AllEventsProcessedEvent allEventsProcessedEvent = AllEventsProcessedEvent.builder()
.eventDescriptor(eventDescriptor.withClientAndOrg(ClientAndOrgId.ofClientAndOrg(Env.getClientId(), OrgId.ANY)))
.build();
// make sure the message gets out *after* the processing results were committed to DB
SpringContextHolder.instance.getBean(PostMaterialEventService.class)
.enqueueEventAfterNextCommit(allEventsProcessedEvent);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\MaterialEventObserver.java | 1 |
请完成以下Java代码 | public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Included Role.
@param AD_Role_Included_ID Included Role */
@Override
public void setAD_Role_Included_ID (int AD_Role_Included_ID)
{
if (AD_Role_Included_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Role_Included_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_Included_ID, Integer.valueOf(AD_Role_Included_ID));
}
/** Get Included Role.
@return Included Role */
@Override
public int getAD_Role_Included_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_Included_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Role getIncluded_Role() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Included_Role_ID, org.compiere.model.I_AD_Role.class);
}
@Override
public void setIncluded_Role(org.compiere.model.I_AD_Role Included_Role)
{
set_ValueFromPO(COLUMNNAME_Included_Role_ID, org.compiere.model.I_AD_Role.class, Included_Role);
}
/** Set Included Role.
@param Included_Role_ID Included Role */
@Override
public void setIncluded_Role_ID (int Included_Role_ID)
{
if (Included_Role_ID < 1)
set_ValueNoCheck (COLUMNNAME_Included_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Included_Role_ID, Integer.valueOf(Included_Role_ID));
}
/** Get Included Role.
@return Included Role */
@Override
public int getIncluded_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Included_Role_ID);
if (ii == null) | return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_Included.java | 1 |
请完成以下Java代码 | public ExecutionInfo getExecutionInfo() {
return delegate.getExecutionInfo();
}
@Override
public int remaining() {
return delegate.remaining();
}
@NonNull
@Override
public Iterable<Row> currentPage() {
return delegate.currentPage();
}
@Override
public boolean hasMorePages() {
return delegate.hasMorePages();
}
@NonNull
@Override
public CompletionStage<AsyncResultSet> fetchNextPage() throws IllegalStateException {
return delegate.fetchNextPage();
}
@Override
public boolean wasApplied() {
return delegate.wasApplied();
}
public ListenableFuture<List<Row>> allRows(Executor executor) {
List<Row> allRows = new ArrayList<>();
SettableFuture<List<Row>> resultFuture = SettableFuture.create();
this.processRows(originalStatement, delegate, allRows, resultFuture, executor);
return resultFuture;
}
private void processRows(Statement statement,
AsyncResultSet resultSet, | List<Row> allRows,
SettableFuture<List<Row>> resultFuture,
Executor executor) {
allRows.addAll(loadRows(resultSet));
if (resultSet.hasMorePages()) {
ByteBuffer nextPagingState = resultSet.getExecutionInfo().getPagingState();
Statement<?> nextStatement = statement.setPagingState(nextPagingState);
TbResultSetFuture resultSetFuture = executeAsyncFunction.apply(nextStatement);
Futures.addCallback(resultSetFuture,
new FutureCallback<TbResultSet>() {
@Override
public void onSuccess(@Nullable TbResultSet result) {
processRows(nextStatement, result,
allRows, resultFuture, executor);
}
@Override
public void onFailure(Throwable t) {
resultFuture.setException(t);
}
}, executor != null ? executor : MoreExecutors.directExecutor()
);
} else {
resultFuture.set(allRows);
}
}
List<Row> loadRows(AsyncResultSet resultSet) {
return Lists.newArrayList(resultSet.currentPage());
}
} | repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\nosql\TbResultSet.java | 1 |
请完成以下Java代码 | public static class UpdateASIAttributeFromModelCommandBuilder
{
public void execute()
{
build().execute();
}
}
public void execute()
{
final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(sourceModel);
if (asiAware == null)
{
return;
}
final ProductId productId = ProductId.ofRepoIdOrNull(asiAware.getM_Product_ID());
if (productId == null)
{
return;
} | final AttributeId attributeId = attributeDAO.retrieveActiveAttributeIdByValueOrNull(attributeCode);
if (attributeId == null)
{
return;
}
attributeSetInstanceBL.getCreateASI(asiAware);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNull(asiAware.getM_AttributeSetInstance_ID());
final I_M_AttributeInstance ai = attributeSetInstanceBL.getAttributeInstance(asiId, attributeId);
if (ai != null)
{
// If it was set, just leave it as it is
return;
}
attributeSetInstanceBL.getCreateAttributeInstance(asiId, attributeId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\UpdateASIAttributeFromModelCommand.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public ZonedDateTime getLastTrade() {
return lastTrade;
}
public void setLastTrade(ZonedDateTime lastTrade) {
this.lastTrade = lastTrade;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} | QuoteDTO quoteDTO = (QuoteDTO) o;
if (quoteDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), quoteDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "QuoteDTO{" +
"id=" + getId() +
", symbol='" + getSymbol() + "'" +
", price=" + getPrice() +
", lastTrade='" + getLastTrade() + "'" +
"}";
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\dto\QuoteDTO.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ScannableCodeFormatRepository
{
@NotNull private final IQueryBL queryBL = Services.get(IQueryBL.class);
@NotNull private final CCache<Integer, ScannableCodeFormatsCollection> cache = CCache.<Integer, ScannableCodeFormatsCollection>builder()
.tableName(I_C_ScannableCode_Format.Table_Name)
.additionalTableNameToResetFor(I_C_ScannableCode_Format_Part.Table_Name)
.build();
public ScannableCodeFormatsCollection getAll()
{
return cache.getOrLoad(0, this::retrieveAll);
}
private ScannableCodeFormatsCollection retrieveAll()
{
return newLoaderAndSaver().loadAll();
}
private ScannableCodeFormatLoaderAndSaver newLoaderAndSaver()
{
return ScannableCodeFormatLoaderAndSaver.builder().queryBL(queryBL).build();
}
public ScannableCodeFormat create(@NotNull final ScannableCodeFormatCreateRequest request)
{
return newLoaderAndSaver().create(request);
}
public int delete(@NotNull final ScannableCodeFormatQuery query)
{
final ImmutableSet<ScannableCodeFormatId> formatIds = toSqlQuery(query).create().idsAsSet(ScannableCodeFormatId::ofRepoId);
if (formatIds.isEmpty())
{
return 0;
}
queryBL.createQueryBuilder(I_C_ScannableCode_Format_Part.class) | .addInArrayFilter(I_C_ScannableCode_Format_Part.COLUMNNAME_C_ScannableCode_Format_ID, formatIds)
.create()
.delete();
return queryBL.createQueryBuilder(I_C_ScannableCode_Format.class)
.addInArrayFilter(I_C_ScannableCode_Format.COLUMNNAME_C_ScannableCode_Format_ID, formatIds)
.create()
.delete();
}
private IQueryBuilder<I_C_ScannableCode_Format> toSqlQuery(final ScannableCodeFormatQuery query)
{
final IQueryBuilder<I_C_ScannableCode_Format> sqlQuery = queryBL.createQueryBuilder(I_C_ScannableCode_Format.class)
.orderBy(I_C_ScannableCode_Format.COLUMNNAME_C_ScannableCode_Format_ID)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_ScannableCode_Format.COLUMNNAME_AD_Client_ID, ClientId.METASFRESH);
if (query.getDescription() != null)
{
sqlQuery.addEqualsFilter(I_C_ScannableCode_Format.COLUMNNAME_Description, query.getDescription());
}
return sqlQuery;
}
public void deleteParts(@NotNull final ScannableCodeFormatId formatId)
{
queryBL.createQueryBuilder(I_C_ScannableCode_Format_Part.class)
.addEqualsFilter(I_C_ScannableCode_Format_Part.COLUMNNAME_C_ScannableCode_Format_ID, formatId)
.create()
.delete();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\repository\ScannableCodeFormatRepository.java | 2 |
请完成以下Java代码 | boolean isAssignable(Class<?> clazz, Object value) {
return ClassUtils.isAssignableValue(clazz, value);
}
private void refreshCachedProperties() {
PropertySources propertySources = environment.getPropertySources();
propertySources.forEach(this::refreshPropertySource);
}
@SuppressWarnings("rawtypes")
private void refreshPropertySource(PropertySource<?> propertySource) {
if (propertySource instanceof CompositePropertySource) {
CompositePropertySource cps = (CompositePropertySource) propertySource;
cps.getPropertySources().forEach(this::refreshPropertySource);
} else if (propertySource instanceof EncryptablePropertySource) {
EncryptablePropertySource eps = (EncryptablePropertySource) propertySource;
eps.refresh();
}
} | private Class<?> getClassSafe(String className) {
try {
return ClassUtils.forName(className, null);
} catch (ClassNotFoundException e) {
return null;
}
}
/** {@inheritDoc} */
@Override
public void afterPropertiesSet() throws Exception {
Stream
.concat(EVENT_CLASS_NAMES.stream(), this.config.getRefreshedEventClasses().stream())
.map(this::getClassSafe).filter(Objects::nonNull)
.collect(Collectors.toCollection(() -> this.eventClasses));
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\RefreshScopeRefreshedEventListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected DeploymentWithDefinitions tryToRedeploy(RedeploymentDto redeployment) {
RepositoryService repositoryService = getProcessEngine().getRepositoryService();
DeploymentBuilder builder = repositoryService.createDeployment();
builder.nameFromDeployment(deploymentId);
String tenantId = getDeployment().getTenantId();
if (tenantId != null) {
builder.tenantId(tenantId);
}
if (redeployment != null) {
builder = addRedeploymentResources(builder, redeployment);
} else {
builder.addDeploymentResources(deploymentId);
}
return builder.deployWithResult();
}
protected DeploymentBuilder addRedeploymentResources(DeploymentBuilder builder, RedeploymentDto redeployment) {
builder.source(redeployment.getSource());
List<String> resourceIds = redeployment.getResourceIds();
List<String> resourceNames = redeployment.getResourceNames();
boolean isResourceIdListEmpty = resourceIds == null || resourceIds.isEmpty();
boolean isResourceNameListEmpty = resourceNames == null || resourceNames.isEmpty();
if (isResourceIdListEmpty && isResourceNameListEmpty) {
builder.addDeploymentResources(deploymentId);
} else {
if (!isResourceIdListEmpty) {
builder.addDeploymentResourcesById(deploymentId, resourceIds);
}
if (!isResourceNameListEmpty) {
builder.addDeploymentResourcesByName(deploymentId, resourceNames);
}
}
return builder;
}
@Override
public void deleteDeployment(String deploymentId, UriInfo uriInfo) {
RepositoryService repositoryService = getProcessEngine().getRepositoryService();
Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
if (deployment == null) { | throw new InvalidRequestException(Status.NOT_FOUND, "Deployment with id '" + deploymentId + "' do not exist");
}
boolean cascade = isQueryPropertyEnabled(uriInfo, CASCADE);
boolean skipCustomListeners = isQueryPropertyEnabled(uriInfo, "skipCustomListeners");
boolean skipIoMappings = isQueryPropertyEnabled(uriInfo, "skipIoMappings");
repositoryService.deleteDeployment(deploymentId, cascade, skipCustomListeners, skipIoMappings);
}
protected boolean isQueryPropertyEnabled(UriInfo uriInfo, String property) {
MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
return queryParams.containsKey(property)
&& queryParams.get(property).size() > 0
&& "true".equals(queryParams.get(property).get(0));
}
protected InvalidRequestException createInvalidRequestException(String action, Status status, ProcessEngineException cause) {
String errorMessage = String.format("Cannot %s deployment '%s': %s", action, deploymentId, cause.getMessage());
return new InvalidRequestException(status, cause, errorMessage);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\repository\impl\DeploymentResourceImpl.java | 2 |
请完成以下Java代码 | public void setIsAutoProcess (final boolean IsAutoProcess)
{
set_Value (COLUMNNAME_IsAutoProcess, IsAutoProcess);
}
@Override
public boolean isAutoProcess()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoProcess);
}
@Override
public void setIsForbidAggCUsForDifferentOrders (final boolean IsForbidAggCUsForDifferentOrders)
{
set_Value (COLUMNNAME_IsForbidAggCUsForDifferentOrders, IsForbidAggCUsForDifferentOrders);
}
@Override
public boolean isForbidAggCUsForDifferentOrders()
{
return get_ValueAsBoolean(COLUMNNAME_IsForbidAggCUsForDifferentOrders);
}
@Override
public void setM_Picking_Config_ID (final int M_Picking_Config_ID)
{
if (M_Picking_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, M_Picking_Config_ID);
}
@Override
public int getM_Picking_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Config_ID);
}
/** | * WEBUI_PickingTerminal_ViewProfile AD_Reference_ID=540772
* Reference name: WEBUI_PickingTerminal_ViewProfile
*/
public static final int WEBUI_PICKINGTERMINAL_VIEWPROFILE_AD_Reference_ID=540772;
/** groupByProduct = groupByProduct */
public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByProduct = "groupByProduct";
/** Group by Order = groupByOrder */
public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByOrder = "groupByOrder";
@Override
public void setWEBUI_PickingTerminal_ViewProfile (final java.lang.String WEBUI_PickingTerminal_ViewProfile)
{
set_Value (COLUMNNAME_WEBUI_PickingTerminal_ViewProfile, WEBUI_PickingTerminal_ViewProfile);
}
@Override
public java.lang.String getWEBUI_PickingTerminal_ViewProfile()
{
return get_ValueAsString(COLUMNNAME_WEBUI_PickingTerminal_ViewProfile);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_Picking_Config.java | 1 |
请完成以下Java代码 | public AuthorRecord value1(Integer value) {
setId(value);
return this;
}
@Override
public AuthorRecord value2(String value) {
setFirstName(value);
return this;
}
@Override
public AuthorRecord value3(String value) {
setLastName(value);
return this;
}
@Override
public AuthorRecord value4(Integer value) {
setAge(value);
return this;
}
@Override
public AuthorRecord values(Integer value1, String value2, String value3, Integer value4) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this; | }
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached AuthorRecord
*/
public AuthorRecord() {
super(Author.AUTHOR);
}
/**
* Create a detached, initialised AuthorRecord
*/
public AuthorRecord(Integer id, String firstName, String lastName, Integer age) {
super(Author.AUTHOR);
set(0, id);
set(1, firstName);
set(2, lastName);
set(3, age);
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\AuthorRecord.java | 1 |
请完成以下Java代码 | public class TemplateDefinition {
public enum TemplateType {
VARIABLE,
FILE,
}
private String from;
private String subject;
private TemplateType type;
private String value;
TemplateDefinition() {}
public TemplateDefinition(TemplateType type, String value) {
this.type = type;
this.value = value;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
} | public TemplateType getType() {
return type;
}
public void setType(TemplateType type) {
this.type = type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TemplateDefinition that = (TemplateDefinition) o;
return (
Objects.equals(from, that.from) &&
Objects.equals(subject, that.subject) &&
type == that.type &&
Objects.equals(value, that.value)
);
}
@Override
public int hashCode() {
return Objects.hash(from, subject, type, value);
}
@Override
public String toString() {
return (
"TemplateDefinition{" +
"from='" +
from +
'\'' +
", subject='" +
subject +
'\'' +
", type=" +
type +
", value='" +
value +
'\'' +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TemplateDefinition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserApi {
@Autowired
UserService userService;
@Autowired
TokenService tokenService;
//登录
@PostMapping("/login")
public Object login( User user){
JSONObject jsonObject=new JSONObject();
User userForBase=userService.findByUsername(user);
if(userForBase==null){
jsonObject.put("message","login fail,user is not exist");
return jsonObject;
}else {
if (!userForBase.getPassword().equals(user.getPassword())){
jsonObject.put("message","login fail,password wrong");
return jsonObject;
}else { | String token = tokenService.getToken(userForBase);
jsonObject.put("token", token);
jsonObject.put("user", userForBase);
return jsonObject;
}
}
}
@UserLoginToken
@GetMapping("/getMessage")
//登录注解,说明该接口必须登录获取token后,在请求头中加上token并通过验证才可以访问
public String getMessage(){
return "verify pass";
}
} | repos\springboot-demo-master\jwt\src\main\java\com\et\jwt\api\UserApi.java | 2 |
请完成以下Java代码 | private IDunnableDoc createDunnableDoc(
@NonNull final IDunningContext context,
@NonNull final I_C_Dunning_Candidate_Invoice_v1 candidate)
{
final int invoiceId = candidate.getC_Invoice_ID();
final int invoicePayScheduleId = candidate.getC_InvoicePaySchedule_ID();
final int adClientId = candidate.getAD_Client_ID();
final int adOrgId = candidate.getAD_Org_ID();
final int bpartnerId = candidate.getC_BPartner_ID();
final int bpartnerLocationId = candidate.getC_BPartner_Location_ID();
final int contactId = candidate.getAD_User_ID();
final int currencyId = candidate.getC_Currency_ID();
final BigDecimal grandTotal = candidate.getGrandTotal();
final BigDecimal openAmt = candidate.getOpenAmt();
final Date dateInvoiced = candidate.getDateInvoiced();
final Date dueDate = candidate.getDueDate();
final Date dunningGrace = candidate.getDunningGrace();
final int paymentTermId = candidate.getC_PaymentTerm_ID();
final boolean isInDispute = candidate.isInDispute();
final String documentNo; // FRESH-504
final String tableName;
final int recordId;
if (invoicePayScheduleId > 0)
{
tableName = I_C_InvoicePaySchedule.Table_Name;
recordId = invoicePayScheduleId;
// The table C_InvoicePaySchedule does not have the column DocumentNo. In this case, the documentNo is null
documentNo = null;
}
else
// if (C_Invoice_ID > 0)
{
tableName = I_C_Invoice.Table_Name;
recordId = invoiceId;
final I_C_Invoice invoice = InterfaceWrapperHelper.create(
context.getCtx(),
invoiceId,
I_C_Invoice.class,
ITrx.TRXNAME_ThreadInherited);
if (invoice == null)
{
// shall not happen
// in case of no referenced record the documentNo is null.
documentNo = null;
}
else
{
documentNo = invoice.getDocumentNo();
}
}
final int daysDue;
if (invoicePayScheduleId > 0)
{
daysDue = TimeUtil.getDaysBetween(dueDate, context.getDunningDate());
}
else
{
final IInvoiceSourceDAO invoiceSourceDAO = Services.get(IInvoiceSourceDAO.class);
daysDue = invoiceSourceDAO.retrieveDueDays( | PaymentTermId.ofRepoId(paymentTermId),
dateInvoiced,
context.getDunningDate());
}
final IDunnableDoc dunnableDoc = new DunnableDoc(tableName,
recordId,
documentNo, // FRESH-504 DocumentNo is also needed
adClientId,
adOrgId,
bpartnerId,
bpartnerLocationId,
contactId,
currencyId,
grandTotal,
openAmt,
dueDate,
dunningGrace,
daysDue,
isInDispute);
return dunnableDoc;
}
@Override
public String getSourceTableName()
{
return I_C_Invoice.Table_Name;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\spi\impl\InvoiceSource.java | 1 |
请完成以下Java代码 | private static AdTabId extractTabId(final I_AD_UI_Section from) {return AdTabId.ofRepoId(from.getAD_Tab_ID());}
private static ImmutableSet<AdUISectionId> extractUISectionIds(final Collection<I_AD_UI_Section> uiSections)
{
return uiSections.stream().map(DAOWindowUIElementsProvider::extractUISectionId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUISectionId extractUISectionId(final I_AD_UI_Section from) {return AdUISectionId.ofRepoId(from.getAD_UI_Section_ID());}
private ImmutableSet<AdUIColumnId> extractUIColumnIds(final Collection<I_AD_UI_Column> uiColumns)
{
return uiColumns.stream().map(DAOWindowUIElementsProvider::extractUIColumnId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUIColumnId extractUIColumnId(final I_AD_UI_Column from) {return AdUIColumnId.ofRepoId(from.getAD_UI_Column_ID());}
private static AdUISectionId extractUISectionId(final I_AD_UI_Column from) {return AdUISectionId.ofRepoId(from.getAD_UI_Section_ID());}
private static AdUIColumnId extractUIColumnId(final I_AD_UI_ElementGroup from) {return AdUIColumnId.ofRepoId(from.getAD_UI_Column_ID());}
private ImmutableSet<AdUIElementGroupId> extractUIElementGroupIds(final Collection<I_AD_UI_ElementGroup> froms)
{
return froms.stream().map(DAOWindowUIElementsProvider::extractUIElementGroupId).distinct().collect(ImmutableSet.toImmutableSet());
} | private static AdUIElementGroupId extractUIElementGroupId(final I_AD_UI_ElementGroup from) {return AdUIElementGroupId.ofRepoId(from.getAD_UI_ElementGroup_ID());}
private static AdUIElementGroupId extractUIElementGroupId(final I_AD_UI_Element from) {return AdUIElementGroupId.ofRepoId(from.getAD_UI_ElementGroup_ID());}
private static AdTabId extractTabId(final I_AD_UI_Element from) {return AdTabId.ofRepoId(from.getAD_Tab_ID());}
private ImmutableSet<AdUIElementId> extractUIElementIds(final Collection<I_AD_UI_Element> froms)
{
return froms.stream().map(DAOWindowUIElementsProvider::extractUIElementId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUIElementId extractUIElementId(final I_AD_UI_Element from) {return AdUIElementId.ofRepoId(from.getAD_UI_Element_ID());}
private static AdUIElementId extractUIElementId(final I_AD_UI_ElementField from) {return AdUIElementId.ofRepoId(from.getAD_UI_Element_ID());}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\DAOWindowUIElementsProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CostClassificationId implements RepoIdAware
{
@JsonCreator
public static CostClassificationId ofRepoId(final int repoId)
{
return new CostClassificationId(repoId);
}
@Nullable
public static CostClassificationId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new CostClassificationId(repoId) : null;
}
public static int toRepoId(@Nullable final CostClassificationId costClassificationId)
{
return costClassificationId != null ? costClassificationId.getRepoId() : -1;
} | int repoId;
private CostClassificationId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final CostClassificationId id1, @Nullable final CostClassificationId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\cost\classification\CostClassificationId.java | 2 |
请完成以下Java代码 | public BigDecimal getESR_Control_Amount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Control_Amount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setESR_Control_Trx_Qty (final @Nullable BigDecimal ESR_Control_Trx_Qty)
{
set_Value (COLUMNNAME_ESR_Control_Trx_Qty, ESR_Control_Trx_Qty);
}
@Override
public BigDecimal getESR_Control_Trx_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Control_Trx_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setESR_Import_ID (final int ESR_Import_ID)
{
if (ESR_Import_ID < 1)
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, ESR_Import_ID);
}
@Override
public int getESR_Import_ID()
{
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID);
}
@Override
public void setESR_Trx_Qty (final @Nullable BigDecimal ESR_Trx_Qty)
{
throw new IllegalArgumentException ("ESR_Trx_Qty is virtual column"); }
@Override
public BigDecimal getESR_Trx_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Trx_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setHash (final @Nullable java.lang.String Hash)
{
set_Value (COLUMNNAME_Hash, Hash);
}
@Override
public java.lang.String getHash()
{
return get_ValueAsString(COLUMNNAME_Hash);
}
@Override
public void setIsArchiveFile (final boolean IsArchiveFile)
{
set_Value (COLUMNNAME_IsArchiveFile, IsArchiveFile);
}
@Override
public boolean isArchiveFile()
{
return get_ValueAsBoolean(COLUMNNAME_IsArchiveFile);
}
@Override | public void setIsReceipt (final boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, IsReceipt);
}
@Override
public boolean isReceipt()
{
return get_ValueAsBoolean(COLUMNNAME_IsReceipt);
}
@Override
public void setIsReconciled (final boolean IsReconciled)
{
set_Value (COLUMNNAME_IsReconciled, IsReconciled);
}
@Override
public boolean isReconciled()
{
return get_ValueAsBoolean(COLUMNNAME_IsReconciled);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
throw new IllegalArgumentException ("Processing is virtual column"); }
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class QueueProcessorService
{
private final ITrxManager trxManager = Services.get(ITrxManager.class);
private final IAsyncBatchBL asyncBatchBL = Services.get(IAsyncBatchBL.class);
@NonNull
private final AsyncBatchObserver asyncBatchObserver;
public QueueProcessorService(final @NonNull AsyncBatchObserver asyncBatchObserver)
{
this.asyncBatchObserver = asyncBatchObserver;
}
public void runAndWait(@NonNull final IQueueProcessor queueProcessor)
{
final AsyncBatchId asyncBatchId = trxManager.callInNewTrx(() -> {
final AsyncBatchId batchId = asyncBatchBL.newAsyncBatch(C_Async_Batch_InternalName_Default);
final int nrOfWorkPackages = queueProcessor.getQueue().assignAsyncBatchForProcessing(batchId);
if (nrOfWorkPackages > 0)
{
return batchId;
}
return null;
});
if (asyncBatchId == null)
{ | return;
}
final AsyncProcessorPlanner asyncProcessorPlanner = new AsyncProcessorPlanner();
try
{
asyncProcessorPlanner.addQueueProcessor(queueProcessor);
asyncProcessorPlanner.start();
asyncBatchObserver.observeOn(asyncBatchId);
asyncBatchObserver.waitToBeProcessed(asyncBatchId);
}
finally
{
asyncProcessorPlanner.shutdown();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorService.java | 2 |
请完成以下Java代码 | public class InMemoryReactiveSessionRegistry implements ReactiveSessionRegistry {
private final ConcurrentMap<Object, Set<String>> sessionIdsByPrincipal;
private final Map<String, ReactiveSessionInformation> sessionById;
public InMemoryReactiveSessionRegistry() {
this.sessionIdsByPrincipal = new ConcurrentHashMap<>();
this.sessionById = new ConcurrentHashMap<>();
}
public InMemoryReactiveSessionRegistry(ConcurrentMap<Object, Set<String>> sessionIdsByPrincipal,
Map<String, ReactiveSessionInformation> sessionById) {
this.sessionIdsByPrincipal = sessionIdsByPrincipal;
this.sessionById = sessionById;
}
@Override
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
public Flux<ReactiveSessionInformation> getAllSessions(Object principal) {
return Flux.fromIterable(this.sessionIdsByPrincipal.getOrDefault(principal, Collections.emptySet()))
.mapNotNull(this.sessionById::get);
}
@Override
public Mono<Void> saveSessionInformation(ReactiveSessionInformation information) {
this.sessionById.put(information.getSessionId(), information);
this.sessionIdsByPrincipal.computeIfAbsent(information.getPrincipal(), (key) -> new CopyOnWriteArraySet<>())
.add(information.getSessionId());
return Mono.empty();
}
@Override
public Mono<ReactiveSessionInformation> getSessionInformation(String sessionId) { | return Mono.justOrEmpty(this.sessionById.get(sessionId));
}
@Override
public Mono<ReactiveSessionInformation> removeSessionInformation(String sessionId) {
return getSessionInformation(sessionId).doOnNext((sessionInformation) -> {
this.sessionById.remove(sessionId);
Set<String> sessionsUsedByPrincipal = this.sessionIdsByPrincipal.get(sessionInformation.getPrincipal());
if (sessionsUsedByPrincipal != null) {
sessionsUsedByPrincipal.remove(sessionId);
if (sessionsUsedByPrincipal.isEmpty()) {
this.sessionIdsByPrincipal.remove(sessionInformation.getPrincipal());
}
}
});
}
@Override
public Mono<ReactiveSessionInformation> updateLastAccessTime(String sessionId) {
ReactiveSessionInformation session = this.sessionById.get(sessionId);
if (session != null) {
return session.refreshLastRequest().thenReturn(session);
}
return Mono.empty();
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\session\InMemoryReactiveSessionRegistry.java | 1 |
请完成以下Java代码 | public void setR_Status_Value (String R_Status_Value)
{
set_Value (COLUMNNAME_R_Status_Value, R_Status_Value);
}
/** Get Request Status.
@return Request Status */
public String getR_Status_Value ()
{
return (String)get_Value(COLUMNNAME_R_Status_Value);
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent | */
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_RV_R_Group_Prospect.java | 1 |
请完成以下Java代码 | private static SessionFactory buildSessionFactory(Strategy strategy) {
try {
ServiceRegistry serviceRegistry = configureServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
for (Class<?> entityClass : strategy.getEntityClasses()) {
metadataSources.addAnnotatedClass(entityClass);
}
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
} catch (IOException ex) {
throw new ExceptionInInitializerError(ex);
}
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Animal.class);
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(Laptop.class);
metadataSources.addAnnotatedClass(Book.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(MyEmployee.class);
metadataSources.addAnnotatedClass(MyProduct.class);
metadataSources.addAnnotatedClass(Pen.class);
metadataSources.addAnnotatedClass(Pet.class);
metadataSources.addAnnotatedClass(Vehicle.class);
metadataSources.addAnnotatedClass(TemporalValues.class); | Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\HibernateUtil.java | 1 |
请完成以下Java代码 | private static <T> HashSet<T> collectValueIfNotNull(@Nullable HashSet<T> collector, @Nullable T value)
{
if (value == null)
{
return collector;
}
if (collector == null)
{
collector = new HashSet<>();
}
collector.add(value);
return collector;
}
private static HashSet<Integer> collectValueIfPositive(@Nullable HashSet<Integer> collector, int value)
{
if (value <= 0)
{
return collector;
}
if (collector == null)
{
collector = new HashSet<>();
}
collector.add(value);
return collector;
} | private static int singleElementOrZero(@Nullable HashSet<Integer> collection)
{
if (collection == null)
{
return 0;
}
if (collection.size() != 1)
{
return 0;
}
final Integer element = collection.iterator().next();
return element != null ? element : 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\dimension\Dimension.java | 1 |
请完成以下Java代码 | public boolean isApiReady() {
return toBooleanDefaultIfNull(edqsReady, false) && syncStatus == EdqsSyncStatus.FINISHED;
}
@JsonIgnore
public boolean isApiEnabled() {
return apiMode != null && (apiMode == EdqsApiMode.ENABLED || apiMode == EdqsApiMode.AUTO_ENABLED);
}
@Override
public String toString() {
return '[' +
"EDQS ready: " + edqsReady +
", sync status: " + syncStatus +
", API mode: " + apiMode +
']';
} | public enum EdqsSyncStatus {
REQUESTED,
STARTED,
FINISHED,
FAILED
}
public enum EdqsApiMode {
ENABLED,
AUTO_ENABLED,
DISABLED,
AUTO_DISABLED
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\edqs\EdqsState.java | 1 |
请完成以下Java代码 | public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
String scheme = requestUrl.getScheme();
if (isAlreadyRouted(exchange) || !"stream".equals(scheme)) {
return chain.filter(exchange);
}
setAlreadyRouted(exchange);
ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
return serverRequest.bodyToMono(byte[].class).flatMap(requestBody -> {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
Message<?> inputMessage = null;
MessageBuilder<?> builder = MessageBuilder.withPayload(requestBody);
if (!CollectionUtils.isEmpty(request.getQueryParams())) {
// TODO: move HeaderUtils
builder = builder.setHeader(MessageHeaderUtils.HTTP_REQUEST_PARAM, | request.getQueryParams().toSingleValueMap());
// TODO: sanitize?
}
inputMessage = builder.copyHeaders(headers.toSingleValueMap()).build();
// TODO: output content type
boolean send = streamBridge.send(requestUrl.getHost(), inputMessage);
HttpStatus responseStatus = (send) ? HttpStatus.OK : HttpStatus.BAD_REQUEST;
SetStatusGatewayFilterFactory.Config config = new SetStatusGatewayFilterFactory.Config();
config.setStatus(responseStatus.name());
return setStatusFilter.apply(config).filter(exchange, chain);
});
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\StreamRoutingFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | SqlServerTimelyExecutor sqlServerTimelyExecutor(io.debezium.config.Configuration configuration) {
SqlServerTimelyExecutor sqlServerTimelyExecutor = new SqlServerTimelyExecutor();
DebeziumEngine<RecordChangeEvent<SourceRecord>> debeziumEngine = DebeziumEngine
.create(ChangeEventFormat.of(Connect.class))
.using(configuration.asProperties())
.notifying(changeEventHandler::handlePayload)
.build();
sqlServerTimelyExecutor.setDebeziumEngine(debeziumEngine);
return sqlServerTimelyExecutor;
}
/**
* @author lei
* @version 1.0
* @date 2021-06-22 15:39
* @desc 同步执行服务类
*/
@Data
@Log4j2
public static class SqlServerTimelyExecutor implements InitializingBean, SmartLifecycle {
private final ExecutorService executor = ThreadPoolEnum.INSTANCE.getInstance();
private DebeziumEngine<?> debeziumEngine;
@Override
public void start() {
log.warn(ThreadPoolEnum.SQL_SERVER_LISTENER_POOL + "线程池开始执行 debeziumEngine 实时监听任务!");
executor.execute(debeziumEngine);
}
@SneakyThrows
@Override
public void stop() {
log.warn("debeziumEngine 监听实例关闭!");
debeziumEngine.close();
Thread.sleep(2000);
log.warn(ThreadPoolEnum.SQL_SERVER_LISTENER_POOL + "线程池关闭!");
executor.shutdown();
}
@Override
public boolean isRunning() {
return false;
}
@Override | public void afterPropertiesSet() {
Assert.notNull(debeziumEngine, "DebeZiumEngine 不能为空!");
}
public enum ThreadPoolEnum {
/**
* 实例
*/
INSTANCE;
public static final String SQL_SERVER_LISTENER_POOL = "sql-server-listener-pool";
/**
* 线程池单例
*/
private final ExecutorService es;
/**
* 枚举 (构造器默认为私有)
*/
ThreadPoolEnum() {
final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(SQL_SERVER_LISTENER_POOL + "-%d").build();
es = new ThreadPoolExecutor(8, 16, 60,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(256),
threadFactory, new ThreadPoolExecutor.DiscardPolicy());
}
/**
* 公有方法
*
* @return ExecutorService
*/
public ExecutorService getInstance() {
return es;
}
}
}
} | repos\springboot-demo-master\debezium\src\main\java\com\et\debezium\config\ChangeEventConfig.java | 2 |
请完成以下Java代码 | public int getPP_Cost_Collector_ImportAudit_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAudit_ID);
}
@Override
public void setPP_Cost_Collector_ImportAuditItem_ID (int PP_Cost_Collector_ImportAuditItem_ID)
{
if (PP_Cost_Collector_ImportAuditItem_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAuditItem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAuditItem_ID, Integer.valueOf(PP_Cost_Collector_ImportAuditItem_ID));
}
@Override
public int getPP_Cost_Collector_ImportAuditItem_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAuditItem_ID);
}
@Override
public org.eevolution.model.I_PP_Order getPP_Order()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
}
@Override
public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order)
{
set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); | }
@Override
public void setPP_Order_ID (int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_Value (COLUMNNAME_PP_Order_ID, null);
else
set_Value (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID));
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_ImportAuditItem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public enum QueryVariableOperation {
EQUALS("equals"), NOT_EQUALS("notEquals"), EQUALS_IGNORE_CASE("equalsIgnoreCase"), NOT_EQUALS_IGNORE_CASE("notEqualsIgnoreCase"), LIKE("like"), LIKE_IGNORE_CASE("likeIgnoreCase"), GREATER_THAN("greaterThan"), GREATER_THAN_OR_EQUALS(
"greaterThanOrEquals"), LESS_THAN("lessThan"), LESS_THAN_OR_EQUALS("lessThanOrEquals");
private final String friendlyName;
private QueryVariableOperation(String friendlyName) {
this.friendlyName = friendlyName; | }
public String getFriendlyName() {
return friendlyName;
}
public static QueryVariableOperation forFriendlyName(String friendlyName) {
for (QueryVariableOperation type : values()) {
if (type.friendlyName.equals(friendlyName)) {
return type;
}
}
throw new FlowableIllegalArgumentException("Unsupported variable query operation: " + friendlyName);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\engine\variable\QueryVariable.java | 2 |
请完成以下Java代码 | public Object execute(CommandContext commandContext) {
commandContext.getAuthorizationManager().checkCamundaAdminOrPermission(CommandChecker::checkDeleteLicenseKey);
final ResourceManager resourceManager = commandContext.getResourceManager();
final PropertyManager propertyManager = commandContext.getPropertyManager();
// lock the property
@SuppressWarnings("unused")
PropertyEntity licenseProperty = propertyManager.findPropertyById(LICENSE_KEY_BYTE_ARRAY_ID);
// delete license key BLOB
ResourceEntity licenseKey = resourceManager.findLicenseKeyResource();
if(licenseKey != null) {
resourceManager.delete(licenseKey);
} | // always delete license key legacy property if it still exists
new DeletePropertyCmd(LICENSE_KEY_PROPERTY_NAME).execute(commandContext);
if(deleteProperty) {
// delete license key byte array id
new DeletePropertyCmd(LICENSE_KEY_BYTE_ARRAY_ID).execute(commandContext);
}
if (updateDiagnostics) {
((ManagementServiceImpl) commandContext.getProcessEngineConfiguration().getManagementService()).setLicenseKeyForDiagnostics(null);
}
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteLicenseKeyCmd.java | 1 |
请完成以下Java代码 | static StockQtyAndUOMQty getMaxQtyCUsPerLU(final @NonNull StockQtyAndUOMQty qty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM, final ProductId productId)
{
final StockQtyAndUOMQty maxQtyCUsPerLU;
if (lutuConfigurationInStockUOM.isInfiniteQtyTU() || lutuConfigurationInStockUOM.isInfiniteQtyCU())
{
maxQtyCUsPerLU = StockQtyAndUOMQtys.createConvert(
qty.getStockQty(),
productId,
qty.getUOMQtyNotNull().getUomId());
}
else
{
maxQtyCUsPerLU = StockQtyAndUOMQtys.createConvert(
lutuConfigurationInStockUOM.getQtyCUsPerTU().multiply(lutuConfigurationInStockUOM.getQtyTU()),
productId,
qty.getUOMQtyNotNull().getUomId());
}
return maxQtyCUsPerLU;
}
static Quantity getQtyCUsPerTUInStockUOM(final @NonNull I_C_OrderLine orderLineRecord, final @NonNull Quantity stockQty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM)
{ | final Quantity qtyCUsPerTUInStockUOM;
if (orderLineRecord.getQtyItemCapacity().signum() > 0)
{
// we use the capacity which the goods were ordered in
qtyCUsPerTUInStockUOM = Quantitys.of(orderLineRecord.getQtyItemCapacity(), stockQty.getUomId());
}
else if (!lutuConfigurationInStockUOM.isInfiniteQtyCU())
{
// we make an educated guess, based on the packing-instruction's information
qtyCUsPerTUInStockUOM = Quantitys.of(lutuConfigurationInStockUOM.getQtyCUsPerTU(), stockQty.getUomId());
}
else
{
// we just don't have the info. So we assume that everything was put into one TU
qtyCUsPerTUInStockUOM = stockQty;
}
return qtyCUsPerTUInStockUOM;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHUPIItemProductBL.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.