instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class TransitionInstantiationCmd extends AbstractInstantiationCmd {
protected String transitionId;
public TransitionInstantiationCmd(String transitionId) {
this(null, transitionId);
}
public TransitionInstantiationCmd(String processInstanceId, String transitionId) {
this(processInstanceId, transitionId, null);
}
public TransitionInstantiationCmd(String processInstanceId, String transitionId,
String ancestorActivityInstanceId) {
super(processInstanceId, ancestorActivityInstanceId);
this.transitionId = transitionId;
}
@Override
protected ScopeImpl getTargetFlowScope(ProcessDefinitionImpl processDefinition) {
TransitionImpl transition = processDefinition.findTransition(transitionId);
return transition.getSource().getFlowScope();
}
@Override
protected CoreModelElement getTargetElement(ProcessDefinitionImpl processDefinition) {
TransitionImpl transition = processDefinition.findTransition(transitionId);
return transition; | }
@Override
public String getTargetElementId() {
return transitionId;
}
@Override
protected String describe() {
StringBuilder sb = new StringBuilder();
sb.append("Start transition '");
sb.append(transitionId);
sb.append("'");
if (ancestorActivityInstanceId != null) {
sb.append(" with ancestor activity instance '");
sb.append(ancestorActivityInstanceId);
sb.append("'");
}
return sb.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\TransitionInstantiationCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Map<String, Integer> getPdfImageCaches() {
Map<String, Integer> map = new HashMap<>();
try {
map = (Map<String, Integer>) toObject(db.get(FILE_PREVIEW_PDF_IMGS_KEY.getBytes()));
} catch (RocksDBException | IOException | ClassNotFoundException e) {
LOGGER.error("Get from RocksDB Exception" + e);
}
return map;
}
private byte[] toByteArray(Object obj) throws IOException {
byte[] bytes;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
return bytes;
}
private Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
Object obj;
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
return obj;
}
private void cleanPdfCache() throws IOException, RocksDBException {
Map<String, String> initPDFCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(initPDFCache));
} | private void cleanImgCache() throws IOException, RocksDBException {
Map<String, List<String>> initIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(initIMGCache));
}
private void cleanPdfImgCache() throws IOException, RocksDBException {
Map<String, Integer> initPDFIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(initPDFIMGCache));
}
private void cleanMediaConvertCache() throws IOException, RocksDBException {
Map<String, String> initMediaConvertCache = new HashMap<>();
db.put(FILE_PREVIEW_MEDIA_CONVERT_KEY.getBytes(), toByteArray(initMediaConvertCache));
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceRocksDBImpl.java | 2 |
请完成以下Java代码 | public final int getLoadCount()
{
return m_loadCount;
}
// metas: end
public boolean isCopying() {return isDynAttributeTrue(DYNATTR_IsCopyWithDetailsInProgress);}
public void setCopying(final boolean copying) {setDynAttribute(DYNATTR_IsCopyWithDetailsInProgress, copying ? Boolean.TRUE : null);}
public boolean isCopiedFromOtherRecord() {return getDynAttribute(DYNATTR_CopiedFromRecordId) != null;}
public void setCopiedFromRecordId(final int fromRecordId) {setDynAttribute(DYNATTR_CopiedFromRecordId, fromRecordId);}
private class POReturningAfterInsertLoader implements ISqlUpdateReturnProcessor
{
private final List<String> columnNames;
private final StringBuilder sqlReturning;
public POReturningAfterInsertLoader()
{
this.columnNames = new ArrayList<>();
this.sqlReturning = new StringBuilder();
}
public void addColumnName(final String columnName)
{
// Make sure column was not already added
if (columnNames.contains(columnName))
{
return;
}
columnNames.add(columnName);
if (sqlReturning.length() > 0)
{ | sqlReturning.append(", ");
}
sqlReturning.append(columnName);
}
public String getSqlReturning()
{
return sqlReturning.toString();
}
public boolean hasColumnNames()
{
return !columnNames.isEmpty();
}
@Override
public void process(final ResultSet rs) throws SQLException
{
for (final String columnName : columnNames)
{
final Object value = rs.getObject(columnName);
// NOTE: it is also setting the ID if applies
set_ValueNoCheck(columnName, value);
}
}
@Override
public String toString()
{
return "POReturningAfterInsertLoader [columnNames=" + columnNames + "]";
}
}
} // PO | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\PO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<TemplateAvailabilityProvider> getProviders() {
return this.providers;
}
/**
* Get the provider that can be used to render the given view.
* @param view the view to render
* @param applicationContext the application context
* @return a {@link TemplateAvailabilityProvider} or null
*/
public @Nullable TemplateAvailabilityProvider getProvider(String view, ApplicationContext applicationContext) {
Assert.notNull(applicationContext, "'applicationContext' must not be null");
ClassLoader classLoader = applicationContext.getClassLoader();
Assert.state(classLoader != null, "'classLoader' must not be null");
return getProvider(view, applicationContext.getEnvironment(), classLoader, applicationContext);
}
/**
* Get the provider that can be used to render the given view.
* @param view the view to render
* @param environment the environment
* @param classLoader the class loader
* @param resourceLoader the resource loader
* @return a {@link TemplateAvailabilityProvider} or null
*/
public @Nullable TemplateAvailabilityProvider getProvider(String view, Environment environment,
ClassLoader classLoader, ResourceLoader resourceLoader) {
Assert.notNull(view, "'view' must not be null");
Assert.notNull(environment, "'environment' must not be null");
Assert.notNull(classLoader, "'classLoader' must not be null");
Assert.notNull(resourceLoader, "'resourceLoader' must not be null");
Boolean useCache = environment.getProperty("spring.template.provider.cache", Boolean.class, true);
if (!useCache) {
return findProvider(view, environment, classLoader, resourceLoader);
}
TemplateAvailabilityProvider provider = this.resolved.get(view);
if (provider == null) {
synchronized (this.cache) {
provider = findProvider(view, environment, classLoader, resourceLoader);
provider = (provider != null) ? provider : NONE;
this.resolved.put(view, provider);
this.cache.put(view, provider);
} | }
return (provider != NONE) ? provider : null;
}
private @Nullable TemplateAvailabilityProvider findProvider(String view, Environment environment,
ClassLoader classLoader, ResourceLoader resourceLoader) {
for (TemplateAvailabilityProvider candidate : this.providers) {
if (candidate.isTemplateAvailable(view, environment, classLoader, resourceLoader)) {
return candidate;
}
}
return null;
}
private static final class NoTemplateAvailabilityProvider implements TemplateAvailabilityProvider {
@Override
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader,
ResourceLoader resourceLoader) {
return false;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\template\TemplateAvailabilityProviders.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ApplicationListener<SessionDisconnectEvent> sessionDisconnectListener() {return this::onSessionDisconnectEvent;}
private void onSessionSubscribeEvent(final SessionSubscribeEvent event)
{
final WebsocketSubscriptionId subscriptionId = extractUniqueSubscriptionId(event);
final WebsocketTopicName topicName = extractTopicName(event);
final WebsocketHeaders headers = WebsocketHeaders.of(extractNativeHeaders(event));
activeSubscriptionsIndex.addSubscription(subscriptionId, topicName);
websocketProducersRegistry.onTopicSubscribed(subscriptionId, topicName, headers);
logger.debug("Subscribed to topicName={} [ subscriptionId={} ]", topicName, subscriptionId);
}
private void onSessionUnsubribeEvent(final SessionUnsubscribeEvent event)
{
final WebsocketSubscriptionId subscriptionId = extractUniqueSubscriptionId(event);
final WebsocketTopicName topicName = activeSubscriptionsIndex.removeSubscriptionAndGetTopicName(subscriptionId);
websocketProducersRegistry.onTopicUnsubscribed(subscriptionId, topicName);
logger.debug("Unsubscribed from topicName={} [ subscriptionId={} ]", topicName, subscriptionId);
}
private void onSessionDisconnectEvent(final SessionDisconnectEvent event)
{
final WebsocketSessionId sessionId = WebsocketSessionId.ofString(event.getSessionId());
final Set<WebsocketTopicName> topicNames = activeSubscriptionsIndex.removeSessionAndGetTopicNames(sessionId);
websocketProducersRegistry.onSessionDisconnect(sessionId, topicNames);
logger.debug("Disconnected from topicName={} [ sessionId={} ]", topicNames, sessionId);
}
private static WebsocketTopicName extractTopicName(final AbstractSubProtocolEvent event)
{
return WebsocketTopicName.ofString(SimpMessageHeaderAccessor.getDestination(event.getMessage().getHeaders()));
}
private static WebsocketSubscriptionId extractUniqueSubscriptionId(final AbstractSubProtocolEvent event)
{ | final MessageHeaders headers = event.getMessage().getHeaders();
final WebsocketSessionId sessionId = WebsocketSessionId.ofString(SimpMessageHeaderAccessor.getSessionId(headers));
final String simpSubscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
return WebsocketSubscriptionId.of(sessionId, Objects.requireNonNull(simpSubscriptionId, "simpSubscriptionId"));
}
@NonNull
private static Map<String, List<String>> extractNativeHeaders(@NonNull final AbstractSubProtocolEvent event)
{
final Object nativeHeaders = event.getMessage().getHeaders().get("nativeHeaders");
return Optional.ofNullable(nativeHeaders)
.filter(headers -> headers instanceof Map)
.filter(headers -> !((Map<?, ?>)headers).isEmpty())
.map(headers -> (Map<String, List<String>>)headers)
.map(ImmutableMap::copyOf)
.orElseGet(ImmutableMap::of);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducerConfiguration.java | 2 |
请完成以下Java代码 | public T getTypedValue(boolean deserializeValue) {
if (cachedValue != null && cachedValue instanceof SerializableValue) {
SerializableValue serializableValue = (SerializableValue) cachedValue;
if(deserializeValue && !serializableValue.isDeserialized()) {
cachedValue = null;
}
}
if (cachedValue == null) {
cachedValue = getSerializer().readValue(typedValueField, deserializeValue);
if (cachedValue instanceof DeferredFileValueImpl) {
DeferredFileValueImpl fileValue = (DeferredFileValueImpl) cachedValue;
fileValue.setExecutionId(executionId);
fileValue.setVariableName(variableName);
}
}
return cachedValue;
}
@SuppressWarnings("unchecked")
public ValueMapper<T> getSerializer() { | if (serializer == null) {
serializer = mappers.findMapperForTypedValueField(typedValueField);
}
return serializer;
}
@Override
public String toString() {
return "VariableValue ["
+ "cachedValue=" + cachedValue + ", "
+ "executionId=" + executionId + ", "
+ "variableName=" + variableName + ", "
+ "typedValueField=" + typedValueField + "]";
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\VariableValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private PPOrderIssuePlan createIssuePlan()
{
return PPOrderIssuePlanCreateCommand.builder()
.huReservationService(huReservationService)
.ppOrderSourceHUService(ppOrderSourceHUService)
.ppOrderId(ppOrderId)
.build()
.execute();
}
private void createIssueSchedules(@NonNull final PPOrderIssuePlan plan)
{
final ArrayListMultimap<PPOrderBOMLineId, PPOrderIssueSchedule> allExistingSchedules = ppOrderIssueScheduleService.getByOrderId(plan.getOrderId())
.stream()
.collect(GuavaCollectors.toArrayListMultimapByKey(PPOrderIssueSchedule::getPpOrderBOMLineId));
final ArrayList<PPOrderIssueSchedule> schedules = new ArrayList<>();
final SeqNoProvider seqNoProvider = SeqNoProvider.ofInt(10);
for (final PPOrderIssuePlanStep planStep : plan.getSteps())
{
final PPOrderBOMLineId orderBOMLineId = planStep.getOrderBOMLineId();
final ArrayList<PPOrderIssueSchedule> bomLineExistingSchedules = new ArrayList<>(allExistingSchedules.removeAll(orderBOMLineId));
bomLineExistingSchedules.sort(Comparator.comparing(PPOrderIssueSchedule::getSeqNo));
for (final PPOrderIssueSchedule existingSchedule : bomLineExistingSchedules)
{
if (existingSchedule.isIssued())
{
final PPOrderIssueSchedule existingScheduleChanged = ppOrderIssueScheduleService.changeSeqNo(existingSchedule, seqNoProvider.getAndIncrement());
schedules.add(existingScheduleChanged);
}
else
{
ppOrderIssueScheduleService.delete(existingSchedule);
} | }
final PPOrderIssueSchedule schedule = ppOrderIssueScheduleService.createSchedule(
PPOrderIssueScheduleCreateRequest.builder()
.ppOrderId(ppOrderId)
.ppOrderBOMLineId(orderBOMLineId)
.seqNo(seqNoProvider.getAndIncrement())
.productId(planStep.getProductId())
.qtyToIssue(planStep.getQtyToIssue())
.issueFromHUId(planStep.getPickFromTopLevelHUId())
.issueFromLocatorId(planStep.getPickFromLocatorId())
.isAlternativeIssue(planStep.isAlternative())
.build());
schedules.add(schedule);
}
loader.addToCache(schedules);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\create_job\ManufacturingJobCreateCommand.java | 2 |
请完成以下Java代码 | static String extractName(final @NonNull DocumentEntityDescriptor entityDescriptor)
{
final String tableName = entityDescriptor.getTableNameOrNull();
return tableName != null ? tableName : entityDescriptor.getInternalName();
}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson()
{
String json = this._json;
if (json == null)
{
json = this._json = computeJson();
}
return json;
}
private String computeJson()
{
return elements.stream()
.map(ContextPathElement::toJson)
.collect(Collectors.joining("."));
}
public ContextPath newChild(@NonNull final String name)
{
return newChild(ContextPathElement.ofName(name));
}
public ContextPath newChild(@NonNull final DocumentEntityDescriptor entityDescriptor)
{
return newChild(ContextPathElement.ofNameAndId(
extractName(entityDescriptor),
AdTabId.toRepoId(entityDescriptor.getAdTabIdOrNull())
));
}
private ContextPath newChild(@NonNull final ContextPathElement element)
{
return new ContextPath(ImmutableList.<ContextPathElement>builder()
.addAll(elements)
.add(element)
.build());
}
public AdWindowId getAdWindowId()
{
return AdWindowId.ofRepoId(elements.get(0).getId());
}
@Override
public int compareTo(@NonNull final ContextPath other)
{
return toJson().compareTo(other.toJson());
}
}
@Value
class ContextPathElement
{
@NonNull String name;
int id; | @JsonCreator
public static ContextPathElement ofJson(@NonNull final String json)
{
try
{
final int idx = json.indexOf("/");
if (idx > 0)
{
String name = json.substring(0, idx);
int id = Integer.parseInt(json.substring(idx + 1));
return new ContextPathElement(name, id);
}
else
{
return new ContextPathElement(json, -1);
}
}
catch (final Exception ex)
{
throw new AdempiereException("Failed parsing: " + json, ex);
}
}
public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);}
public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson() {return id > 0 ? name + "/" + id : name;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java | 1 |
请完成以下Java代码 | private static class JwtClaimIssuerConverter implements Converter<BearerTokenAuthenticationToken, Mono<String>> {
@Override
public Mono<String> convert(@NonNull BearerTokenAuthenticationToken token) {
try {
String issuer = JWTParser.parse(token.getToken()).getJWTClaimsSet().getIssuer();
if (issuer == null) {
AuthenticationException ex = new InvalidBearerTokenException("Missing issuer");
ex.setAuthenticationRequest(token);
throw ex;
}
return Mono.just(issuer);
}
catch (Exception cause) {
return Mono.error(() -> {
AuthenticationException ex = new InvalidBearerTokenException(cause.getMessage(), cause);
ex.setAuthenticationRequest(token);
return ex;
});
}
}
}
static class TrustedIssuerJwtAuthenticationManagerResolver
implements ReactiveAuthenticationManagerResolver<String> {
private final Log logger = LogFactory.getLog(getClass());
private final Map<String, Mono<ReactiveAuthenticationManager>> authenticationManagers = new ConcurrentHashMap<>();
private final Predicate<String> trustedIssuer;
TrustedIssuerJwtAuthenticationManagerResolver(Predicate<String> trustedIssuer) {
this.trustedIssuer = trustedIssuer;
} | @Override
public Mono<ReactiveAuthenticationManager> resolve(String issuer) {
if (!this.trustedIssuer.test(issuer)) {
this.logger.debug("Did not resolve AuthenticationManager since issuer is not trusted");
return Mono.empty();
}
// @formatter:off
return this.authenticationManagers.computeIfAbsent(issuer,
(k) -> Mono.<ReactiveAuthenticationManager>fromCallable(() -> new JwtReactiveAuthenticationManager(ReactiveJwtDecoders.fromIssuerLocation(k)))
.doOnNext((manager) -> this.logger.debug(LogMessage.format("Resolved AuthenticationManager for issuer '%s'", issuer)))
.subscribeOn(Schedulers.boundedElastic())
.cache((manager) -> Duration.ofMillis(Long.MAX_VALUE), (ex) -> Duration.ZERO, () -> Duration.ZERO)
);
// @formatter:on
}
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtIssuerReactiveAuthenticationManagerResolver.java | 1 |
请完成以下Java代码 | public String sendCmd(final String cmd)
{
// System.out.println("Waiting " + delayMillis + "ms before returning the " + this + " result for command '" + cmd + "'");
try
{
if (delayMillis > 0)
{
Thread.sleep(delayMillis);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
// final String returnString = generateConstantResult();
// final String returnString = generateRandomResult();
final String returnString = generateSequenceResult();
// System.out.println("Returning: " + returnString);
return returnString;
}
@SuppressWarnings("unused")
private String generateConstantResult()
{
// return string for the busch
// return "<000002.07.1413:25 111 0.0 90.0 -90.0kgPT2 1 11540>";
// return string for the mettler
final String returnString = "S S 561.348 kg";
return returnString;
}
@SuppressWarnings("unused")
private String generateRandomResult()
{
//
// Randomly throw exception
if (throwRandomException && random.nextInt(10) == 0)
{
throw new RuntimeException("Randomly generated exception");
}
//
// Generate and return a random weight | final BigDecimal weight = BigDecimal.valueOf(random.nextInt(1000000)).divide(new BigDecimal("1000"), 3, RoundingMode.HALF_UP);
final String resultString = createWeightString(weight);
return resultString;
}
/**
* Returns a number of predefined results in a round-robin fashion.
* The result will be one of <code>450, 460, ... , 490, 450, ...</code> <b>plus</b> an instance-specific offset (e.g. for the 2nd instance, it will be <code>451, 461, ...</code>)
*
* @return
*/
private String generateSequenceResult()
{
synchronized (MockedEndpoint.class)
{
weightSequenceIdx++;
if (weightSequenceIdx >= weightSequence.length)
{
weightSequenceIdx = 0;
}
final BigDecimal weighFromArray = weightSequence[weightSequenceIdx];
final BigDecimal weightToUse = weighFromArray.add(new BigDecimal(mockedEndpointInstanceNumber));
final String returnString = createWeightString(weightToUse);
return returnString;
}
}
public static String createWeightString(final BigDecimal weight)
{
final DecimalFormat weightFormat = new DecimalFormat("#########.000");
String weightStr = weightFormat.format(weight);
while (weightStr.length() < 11)
{
weightStr = " " + weightStr;
}
final String resultString = "S S " + weightStr + " kg";
return resultString;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\endpoint\MockedEndpoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ExtendedPeriodType getMaterialAuthorization() {
return materialAuthorization;
}
/**
* Sets the value of the materialAuthorization property.
*
* @param value
* allowed object is
* {@link ExtendedPeriodType }
*
*/
public void setMaterialAuthorization(ExtendedPeriodType value) {
this.materialAuthorization = value;
}
/**
* Gets the value of the productionAuthorization property.
*
* @return
* possible object is
* {@link ExtendedPeriodType } | *
*/
public ExtendedPeriodType getProductionAuthorization() {
return productionAuthorization;
}
/**
* Sets the value of the productionAuthorization property.
*
* @param value
* allowed object is
* {@link ExtendedPeriodType }
*
*/
public void setProductionAuthorization(ExtendedPeriodType value) {
this.productionAuthorization = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AdditionalForecastInformationType.java | 2 |
请完成以下Java代码 | public int getQueryLimit()
{
return -1;
}
@Override
public boolean isQueryLimitHit()
{
return false;
}
@Override
public ViewResult getPage(
final int firstRow,
final int pageLength,
@NonNull final ViewRowsOrderBy orderBys)
{
final List<PickingSlotRow> pageRows = rows.getPage(firstRow, pageLength);
return ViewResult.ofViewAndPage(this, firstRow, pageLength, orderBys.toDocumentQueryOrderByList(), pageRows);
}
@Override
public PickingSlotRow getById(@NonNull final DocumentId id) throws EntityNotFoundException
{
return rows.getById(id);
}
@Override
public LookupValuesPage getFilterParameterDropdown(final String filterId, final String filterParameterName, final ViewFilterParameterLookupEvaluationCtx ctx)
{
throw new UnsupportedOperationException();
}
@Override
public LookupValuesPage getFilterParameterTypeahead(final String filterId, final String filterParameterName, final String query, final ViewFilterParameterLookupEvaluationCtx ctx)
{
throw new UnsupportedOperationException();
}
@Override
public DocumentFilterList getStickyFilters()
{
return DocumentFilterList.EMPTY;
}
@Override
public DocumentFilterList getFilters()
{
return filters;
}
@Override
public DocumentQueryOrderByList getDefaultOrderBys()
{
return DocumentQueryOrderByList.EMPTY;
}
@Override
public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts)
{
// TODO Auto-generated method stub
return null;
}
@Override | public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass)
{
throw new UnsupportedOperationException();
}
@Override
public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds)
{
return rows.streamByIds(rowIds);
}
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
// TODO Auto-generated method stub
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return additionalRelatedProcessDescriptors;
}
/**
* @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}.
*/
@NonNull
public ShipmentScheduleId getCurrentShipmentScheduleId()
{
return currentShipmentScheduleId;
}
@Override
public void invalidateAll()
{
rows.invalidateAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void enableRoute(@NonNull final Exchange exchange) throws Exception
{
final StartOnDemandRouteRequest request = exchange.getIn().getBody(StartOnDemandRouteRequest.class);
final IdAwareRouteBuilder idAwareRouteBuilder = request.getOnDemandRouteBuilder();
final boolean routeWasAlreadyCreated = exchange.getContext().getRoute(idAwareRouteBuilder.getRouteId()) != null;
if (!routeWasAlreadyCreated)
{
exchange.getContext().addRoutes(idAwareRouteBuilder);
exchange.getContext().getRouteController().startRoute(idAwareRouteBuilder.getRouteId());
}
else
{
exchange.getContext().getRouteController().resumeRoute(idAwareRouteBuilder.getRouteId());
}
}
public void prepareExternalStatusCreateRequest(@NonNull final Exchange exchange, @NonNull final JsonExternalStatus externalStatus)
{
final OnDemandRequest onDemandRouteRequest = exchange.getIn().getBody(OnDemandRequest.class);
final JsonExternalSystemRequest externalSystemRequest = onDemandRouteRequest.getExternalSystemRequest();
final IExternalSystemService externalSystemService = onDemandRouteRequest.getExternalSystemService();
final JsonStatusRequest jsonStatusRequest = JsonStatusRequest.builder()
.status(externalStatus)
.pInstanceId(externalSystemRequest.getAdPInstanceId())
.build();
final ExternalStatusCreateCamelRequest camelRequest = ExternalStatusCreateCamelRequest.builder()
.jsonStatusRequest(jsonStatusRequest)
.externalSystemChildConfigValue(externalSystemRequest.getExternalSystemChildConfigValue())
.externalSystemConfigType(externalSystemService.getExternalSystemTypeCode())
.serviceValue(externalSystemService.getServiceValue()) | .build();
exchange.getIn().setBody(camelRequest);
}
private void disableRoute(@NonNull final Exchange exchange) throws Exception
{
final StopOnDemandRouteRequest request = exchange.getIn().getBody(StopOnDemandRouteRequest.class);
if (exchange.getContext().getRoute(request.getRouteId()) == null)
{
return;
}
exchange.getContext().getRouteController().stopRoute(request.getRouteId());
exchange.getContext().removeRoute(request.getRouteId());
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\service\OnDemandRoutesPCMController.java | 2 |
请完成以下Java代码 | public Object getValueInitial()
{
return null;
}
@Override
public BigDecimal getValueAsBigDecimal()
{
return null;
}
@Override
public int getValueAsInt()
{
return 0;
}
@Override
public String getValueAsString()
{
return null;
}
@Override
public BigDecimal getValueInitialAsBigDecimal()
{
return null;
}
@Override
public String getValueInitialAsString()
{
return null;
}
@Override
public Date getValueAsDate()
{
return null;
}
@Override
public Date getValueInitialAsDate()
{
return null;
}
@Override
public boolean isNumericValue()
{
return false;
}
@Override
public boolean isStringValue()
{
return false;
}
@Override
public boolean isList()
{
return false;
}
@Override
public boolean isDateValue()
{
return false;
}
@Override
public boolean isEmpty()
{
return true;
}
@Override
public Object getEmptyValue()
{
return null;
}
@Override
public String getPropagationType()
{
return NullHUAttributePropagator.instance.getPropagationType();
}
@Override
public IAttributeAggregationStrategy retrieveAggregationStrategy()
{
return NullAggregationStrategy.instance;
}
@Override
public IAttributeSplitterStrategy retrieveSplitterStrategy()
{
return NullSplitterStrategy.instance;
}
@Override
public IHUAttributeTransferStrategy retrieveTransferStrategy()
{
return SkipHUAttributeTransferStrategy.instance;
}
@Override
public boolean isUseInASI()
{
return false;
}
@Override
public boolean isDefinedByTemplate()
{
return false;
}
@Override
public void addAttributeValueListener(final IAttributeValueListener listener)
{
// nothing
}
@Override
public List<ValueNamePair> getAvailableValues()
{
throw new InvalidAttributeValueException("method not supported for " + this);
}
@Override
public IAttributeValuesProvider getAttributeValuesProvider() | {
throw new InvalidAttributeValueException("method not supported for " + this);
}
@Override
public I_C_UOM getC_UOM()
{
return null;
}
@Override
public IAttributeValueCallout getAttributeValueCallout()
{
return NullAttributeValueCallout.instance;
}
@Override
public IAttributeValueGenerator getAttributeValueGeneratorOrNull()
{
return null;
}
@Override
public void removeAttributeValueListener(final IAttributeValueListener listener)
{
// nothing
}
@Override
public boolean isReadonlyUI()
{
return true;
}
@Override
public boolean isDisplayedUI()
{
return false;
}
@Override
public boolean isMandatory()
{
return false;
}
@Override
public int getDisplaySeqNo()
{
return 0;
}
@Override
public NamePair getNullAttributeValue()
{
return null;
}
/**
* @return true; we consider Null attributes as always generated
*/
@Override
public boolean isNew()
{
return true;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\NullAttributeValue.java | 1 |
请完成以下Java代码 | private void dbUpdateBPartners(@NonNull final ImportRecordsSelection selection)
{
StringBuilder sql = new StringBuilder("UPDATE I_Datev_Payment i ")
.append("SET C_BPartner_ID=(SELECT MAX(C_BPartner_ID) FROM C_BPartner bp ")
.append(" WHERE (i.BPartnerValue=bp.Debtorid OR i.BPartnerValue=bp.CreditorId) AND i.AD_Client_ID=bp.AD_Client_ID AND i.AD_Org_ID=bp.AD_Org_ID ) ")
.append("WHERE C_BPartner_ID IS NULL AND BPartnerValue IS NOT NULL ")
.append("AND I_IsImported<>'Y' ")
.append(selection.toSqlWhereClause("i"));
DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
}
private void dbUpdateInvoices(@NonNull final ImportRecordsSelection selection)
{
StringBuilder sql = new StringBuilder("UPDATE I_Datev_Payment i ")
.append("SET C_Invoice_ID = (SELECT C_Invoice_ID FROM C_Invoice inv ")
.append("WHERE i.InvoiceDocumentNo = inv.DocumentNo ")
.append("AND round((i.PayAmt+i.DiscountAmt),2) = round(inv.GrandTotal,2) AND i.DateTrx = inv.DateInvoiced ")
.append("AND i.AD_Client_ID=inv.AD_Client_ID AND i.AD_Org_ID=inv.AD_Org_ID ) ")
.append("WHERE C_Invoice_ID IS NULL AND InvoiceDocumentNo IS NOT NULL ")
.append("AND I_IsImported<>'Y' ")
.append(selection.toSqlWhereClause("i"));
DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
}
private void dbUpdateIsReceipt(@NonNull final ImportRecordsSelection selection)
{
StringBuilder sql = new StringBuilder("UPDATE I_Datev_Payment i ")
.append("SET IsReceipt = (CASE WHEN TransactionCode='H' THEN 'N' ELSE 'Y' END) ")
.append("WHERE I_IsImported<>'Y' ")
.append(selection.toSqlWhereClause("i"));
DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
}
private void dbUpdateErrorMessages(@NonNull final ImportRecordsSelection selection)
{
StringBuilder sql;
int no;
sql = new StringBuilder("UPDATE I_Datev_Payment ")
.append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No BPartner, ' ")
.append("WHERE C_BPartner_ID IS NULL ")
.append("AND I_IsImported<>'Y' ") | .append(selection.toSqlWhereClause());
no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
if (no != 0)
{
logger.warn("No BPartner = {}", no);
}
sql = new StringBuilder("UPDATE I_Datev_Payment ")
.append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Invoice, ' ")
.append("WHERE C_Invoice_ID IS NULL ")
.append("AND I_IsImported<>'Y' ")
.append(selection.toSqlWhereClause("i"));
no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
if (no != 0)
{
logger.warn("No Invoice = {}", no);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impexp\CPaymentImportTableSqlUpdater.java | 1 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setEndNo (final int EndNo)
{
set_Value (COLUMNNAME_EndNo, EndNo);
}
@Override
public int getEndNo()
{ | return get_ValueAsInt(COLUMNNAME_EndNo);
}
@Override
public void setStartNo (final int StartNo)
{
set_Value (COLUMNNAME_StartNo, StartNo);
}
@Override
public int getStartNo()
{
return get_ValueAsInt(COLUMNNAME_StartNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ScannableCode_Format_Part.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExecuteJobCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteJobCmd.class);
protected String jobId;
protected JobServiceConfiguration jobServiceConfiguration;
public ExecuteJobCmd(String jobId, JobServiceConfiguration jobServiceConfiguration) {
this.jobId = jobId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Object execute(CommandContext commandContext) {
if (jobId == null) {
throw new FlowableIllegalArgumentException("JobId is null");
}
Job job = jobServiceConfiguration.getJobEntityManager().findById(jobId);
if (job == null) {
throw new JobNotFoundException(jobId);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Executing job {}", job.getId());
} | InternalJobCompatibilityManager internalJobCompatibilityManager = jobServiceConfiguration.getInternalJobCompatibilityManager();
if (internalJobCompatibilityManager != null && internalJobCompatibilityManager.isFlowable5Job(job)) {
internalJobCompatibilityManager.executeV5Job(job);
return null;
}
commandContext.addCloseListener(new FailedJobListener(jobServiceConfiguration.getCommandExecutor(), job, jobServiceConfiguration));
jobServiceConfiguration.getJobManager().execute(job);
return null;
}
public String getJobId() {
return jobId;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\ExecuteJobCmd.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MaterialEventHandlerRegistry
{
private static final Logger logger = LogManager.getLogger(MaterialEventHandlerRegistry.class);
private final ImmutableListMultimap<Class, MaterialEventHandler> eventType2Handler;
private final EventLogUserService eventLogUserService;
private final MaterialEventObserver materialEventObserver;
public MaterialEventHandlerRegistry(
@NonNull final Optional<Collection<MaterialEventHandler>> handlers,
@NonNull final EventLogUserService eventLogUserService,
@NonNull final MaterialEventObserver materialEventObserver)
{
this.eventLogUserService = eventLogUserService;
this.materialEventObserver = materialEventObserver;
eventType2Handler = createEventHandlerMapping(handlers);
logger.info("Registered {}", eventType2Handler);
}
private static ImmutableListMultimap<Class, MaterialEventHandler> createEventHandlerMapping(
@NonNull final Optional<Collection<MaterialEventHandler>> handlers)
{
final ImmutableListMultimap.Builder<Class, MaterialEventHandler> builder = ImmutableListMultimap.builder();
for (final MaterialEventHandler handler : handlers.orElse(ImmutableList.of()))
{
@SuppressWarnings("unchecked")
final Collection<Class<? extends MaterialEventHandler>> handeledEventTypes = handler.getHandledEventType();
for (final Class<? extends MaterialEventHandler> handeledEventType : handeledEventTypes)
{
builder.put(handeledEventType, handler); | }
}
return builder.build();
}
public final void onEvent(@NonNull final MaterialEvent event)
{
final ImmutableList<MaterialEventHandler> handlersForEventClass = eventType2Handler.get(event.getClass());
for (final MaterialEventHandler handler : handlersForEventClass)
{
try (final MDCCloseable ignored = MDC.putCloseable("MaterialEventHandlerClass", handler.getClass().getName()))
{
@SuppressWarnings("unchecked")
final InvokeHandlerAndLogRequest request = InvokeHandlerAndLogRequest.builder()
.handlerClass(handler.getClass())
.invokaction(() -> handler.handleEvent(event))
.build();
eventLogUserService.invokeHandlerAndLog(request);
}
}
if (!handlersForEventClass.isEmpty())
{
materialEventObserver.reportEventProcessed(event);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\MaterialEventHandlerRegistry.java | 2 |
请完成以下Java代码 | public class VOvrCaret extends DefaultCaret
{
/**
*
*/
private static final long serialVersionUID = 1513269384035685427L;
/**
* Constructor
*/
public VOvrCaret()
{
super();
} // VOvrCaret
/**
* Renders the caret as a top and button bracket.
*
* @param g the graphics context
* @see #damage
*/
public void paint(Graphics g)
{
boolean dotLTR = true; // left-to-right
Position.Bias dotBias = Position.Bias.Forward;
//
if (isVisible())
{
try
{
TextUI mapper = getComponent().getUI();
Rectangle r = mapper.modelToView(getComponent(), getDot(), dotBias);
Rectangle e = mapper.modelToView(getComponent(), getDot()+1, dotBias);
// g.setColor(getComponent().getCaretColor());
g.setColor(Color.blue);
//
int cWidth = e.x-r.x;
int cHeight = 4;
int cThick = 2;
//
g.fillRect(r.x-1, r.y, cWidth, cThick); // top
g.fillRect(r.x-1, r.y, cThick, cHeight); // |
g.fillRect(r.x-1+cWidth, r.y, cThick, cHeight); // |
//
int yStart = r.y+r.height;
g.fillRect(r.x-1, yStart-cThick, cWidth, cThick); // button
g.fillRect(r.x-1, yStart-cHeight, cThick, cHeight); // |
g.fillRect(r.x-1+cWidth, yStart-cHeight, cThick, cHeight); // |
}
catch (BadLocationException e)
{
// can't render
// System.err.println("Can't render cursor");
} | } // isVisible
} // paint
/**
* Damages the area surrounding the caret to cause
* it to be repainted in a new location.
* This method should update the caret bounds (x, y, width, and height).
*
* @param r the current location of the caret
* @see #paint
*/
protected synchronized void damage(Rectangle r)
{
if (r != null)
{
x = r.x - 4; // start 4 pixles before (one required)
y = r.y;
width = 18; // sufficent for standard font (18-4=14)
height = r.height;
repaint();
}
} // damage
} // VOvrCaret | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VOvrCaret.java | 1 |
请完成以下Java代码 | 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 mimeType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMimeType() {
return mimeType;
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
} | /**
* Gets the value of the encoding property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncoding() {
return encoding;
}
/**
* Sets the value of the encoding property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncoding(String value) {
this.encoding = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ObjectType.java | 1 |
请完成以下Java代码 | public void delete(User entity) throws Exception {
userRepo.delete(entity);
}
@Override
public User findById(Long id) {
return userRepo.findOne(id);
}
@Override
public User findBySample(User sample) {
return userRepo.findOne(whereSpec(sample));
}
@Override
public List<User> findAll() {
return userRepo.findAll();
}
@Override
public List<User> findAll(User sample) {
return userRepo.findAll(whereSpec(sample));
}
@Override
public Page<User> findAll(PageRequest pageRequest) {
return userRepo.findAll(pageRequest);
}
@Override
public Page<User> findAll(User sample, PageRequest pageRequest) {
return userRepo.findAll(whereSpec(sample), pageRequest); | }
private Specification<User> whereSpec(final User sample){
return (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
if (sample.getId()!=null){
predicates.add(cb.equal(root.<Long>get("id"), sample.getId()));
}
if (StringUtils.hasLength(sample.getUsername())){
predicates.add(cb.equal(root.<String>get("username"),sample.getUsername()));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
};
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User sample = new User();
sample.setUsername(username);
User user = findBySample(sample);
if( user == null ){
throw new UsernameNotFoundException(String.format("User with username=%s was not found", username));
}
return user;
}
} | repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\user\UserService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (isDirectPrint ? 1231 : 1237);
result = prime * result + ((printerName == null) ? 0 : printerName.hashCode());
result = prime * result + ((printerType == null) ? 0 : printerType.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrintingServiceImpl other = (PrintingServiceImpl)obj;
if (isDirectPrint != other.isDirectPrint)
return false;
if (printerName == null)
{
if (other.printerName != null)
return false; | }
else if (!printerName.equals(other.printerName))
return false;
if (printerType == null)
{
if (other.printerType != null)
return false;
}
else if (!printerType.equals(other.printerType))
return false;
return true;
}
@Override
public String toString()
{
return "PrintingServiceImpl [printerName=" + printerName + ", printerType=" + printerType + ", isDirectPrint=" + isDirectPrint + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\PrintingServiceImpl.java | 2 |
请完成以下Java代码 | public static ImmutableSet<PickingJobFacet> extractFacets(@NonNull Packageable packageable, @NonNull final CollectingParameters parameters)
{
final ImmutableList<PickingJobFacetGroup> groups = parameters.getGroupsInOrder();
if (groups.isEmpty()) {return ImmutableSet.of();}
final ImmutableSet.Builder<PickingJobFacet> facets = ImmutableSet.builder();
groups.forEach(group -> {
final List<? extends PickingJobFacet> facetsPerGroup = getBy(group).extractFacets(packageable, parameters);
facets.addAll(facetsPerGroup);
});
return facets.build();
}
public static PickingJobQuery.Facets retainFacetsOfGroups(
@NonNull final PickingJobQuery.Facets queryFacets,
@NonNull final Collection<PickingJobFacetGroup> groups)
{
if (groups.isEmpty())
{
return PickingJobQuery.Facets.EMPTY;
}
final PickingJobQuery.Facets.FacetsBuilder builder = PickingJobQuery.Facets.builder();
for (final PickingJobFacetGroup group : groups)
{
PickingJobFacetHandlers.getBy(group).collectHandled(builder, queryFacets);
}
final PickingJobQuery.Facets queryFacetsNew = builder.build();
if (queryFacetsNew.isEmpty())
{
return PickingJobQuery.Facets.EMPTY;
}
else if (queryFacetsNew.equals(queryFacets))
{
return queryFacets;
}
else
{
return queryFacetsNew;
}
}
public static boolean isMatching(@NonNull PickingJobFacet facet, @NonNull PickingJobQuery.Facets queryFacets)
{
final PickingJobFacetGroup group = facet.getGroup();
return getBy(group).isMatching(facet, queryFacets);
} | public static PickingJobQuery.Facets toPickingJobFacetsQuery(@Nullable final Set<WorkflowLaunchersFacetId> facetIds)
{
if (facetIds == null || facetIds.isEmpty())
{
return PickingJobQuery.Facets.EMPTY;
}
final PickingJobQuery.Facets.FacetsBuilder builder = PickingJobQuery.Facets.builder();
facetIds.forEach(facetId -> collectFromFacetId(builder, facetId));
return builder.build();
}
private static void collectFromFacetId(@NonNull PickingJobQuery.Facets.FacetsBuilder collector, @NonNull WorkflowLaunchersFacetId facetId)
{
final PickingJobFacetGroup group = PickingJobFacetGroup.of(facetId.getGroupId());
getBy(group).collectFromFacetId(collector, facetId);
}
public static WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList(
@NonNull final PickingJobFacets pickingFacets,
@NonNull final MobileUIPickingUserProfile profile)
{
final ArrayList<WorkflowLaunchersFacetGroup> groups = new ArrayList<>();
for (final PickingJobFacetGroup filterOption : profile.getFilterGroupsInOrder())
{
final WorkflowLaunchersFacetGroup group = PickingJobFacetHandlers.getBy(filterOption).toWorkflowLaunchersFacetGroup(pickingFacets);
// NOTE: if a group has only one facet that's like not filtering at all, so having that facet in the result is pointless.
if (group != null && !group.isEmpty())
{
groups.add(group);
}
}
return WorkflowLaunchersFacetGroupList.ofList(groups);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\facets\PickingJobFacetHandlers.java | 1 |
请完成以下Java代码 | public RegisteredClient findById(String id) {
Assert.hasText(id, "id cannot be empty");
return this.idRegistrationMap.get(id);
}
@Nullable
@Override
public RegisteredClient findByClientId(String clientId) {
Assert.hasText(clientId, "clientId cannot be empty");
return this.clientIdRegistrationMap.get(clientId);
}
private void assertUniqueIdentifiers(RegisteredClient registeredClient,
Map<String, RegisteredClient> registrations) {
registrations.values().forEach((registration) -> {
if (registeredClient.getId().equals(registration.getId())) { | throw new IllegalArgumentException("Registered client must be unique. " + "Found duplicate identifier: "
+ registeredClient.getId());
}
if (registeredClient.getClientId().equals(registration.getClientId())) {
throw new IllegalArgumentException("Registered client must be unique. "
+ "Found duplicate client identifier: " + registeredClient.getClientId());
}
if (StringUtils.hasText(registeredClient.getClientSecret())
&& registeredClient.getClientSecret().equals(registration.getClientSecret())) {
throw new IllegalArgumentException("Registered client must be unique. "
+ "Found duplicate client secret for identifier: " + registeredClient.getId());
}
});
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\InMemoryRegisteredClientRepository.java | 1 |
请完成以下Java代码 | private AsyncBatchId build0()
{
final I_C_Async_Batch asyncBatch = InterfaceWrapperHelper.create(getCtx(), I_C_Async_Batch.class, ITrx.TRXNAME_None);
asyncBatch.setAD_PInstance_ID(PInstanceId.toRepoId(getAD_PInstance_Creator_ID()));
asyncBatch.setParent_Async_Batch_ID(AsyncBatchId.toRepoId(getParentAsyncBatchId()));
asyncBatch.setName(getName());
asyncBatch.setDescription(getDescription());
if (getOrgId() != null)
{
final int orgIdRepoId = getOrgId().getRepoId();
asyncBatch.setAD_Org_ID(orgIdRepoId);
}
if (getCountExpected() > 0)
{
asyncBatch.setCountExpected(getCountExpected());
}
asyncBatch.setC_Async_Batch_Type(getC_Async_Batch_Type());
queueDAO.save(asyncBatch);
return AsyncBatchId.ofRepoId(asyncBatch.getC_Async_Batch_ID());
}
@Override
public IAsyncBatchBuilder setContext(final Properties ctx)
{
_ctx = ctx;
return this;
}
private final Properties getCtx()
{
Check.assumeNotNull(_ctx, "ctx not null");
return _ctx;
}
@Override
public IAsyncBatchBuilder setCountExpected(final int expected)
{
_countExpected = expected;
return this;
}
private final int getCountExpected()
{
return _countExpected;
}
@Override
public IAsyncBatchBuilder setAD_PInstance_Creator_ID(final PInstanceId adPInstanceId)
{
this.adPInstanceId = adPInstanceId;
return this;
}
private final PInstanceId getAD_PInstance_Creator_ID()
{
return adPInstanceId;
}
private AsyncBatchId getParentAsyncBatchId()
{
return Optional.ofNullable(_parentAsyncBatchId)
.orElse(contextFactory.getThreadInheritedWorkpackageAsyncBatch()); | }
@Override
public IAsyncBatchBuilder setParentAsyncBatchId(final AsyncBatchId parentAsyncBatchId)
{
_parentAsyncBatchId = parentAsyncBatchId;
return this;
}
@Override
public IAsyncBatchBuilder setName(final String name)
{
_name = name;
return this;
}
public String getName()
{
return _name;
}
@Override
public IAsyncBatchBuilder setDescription(final String description)
{
_description = description;
return this;
}
private String getDescription()
{
return _description;
}
private OrgId getOrgId()
{
return orgId;
}
@Override
public IAsyncBatchBuilder setC_Async_Batch_Type(final String internalName)
{
_asyncBatchType = asyncBatchDAO.retrieveAsyncBatchType(getCtx(), internalName);
return this;
}
public I_C_Async_Batch_Type getC_Async_Batch_Type()
{
Check.assumeNotNull(_asyncBatchType, "_asyncBatchType not null");
return _asyncBatchType;
}
@Override
public IAsyncBatchBuilder setOrgId(final OrgId orgId)
{
this.orgId = orgId;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DubboReferencesMetadata extends AbstractDubboMetadata {
public Map<String, Map<String, Object>> references() {
Map<String, Map<String, Object>> referencesMetadata = new LinkedHashMap<>();
ReferenceAnnotationBeanPostProcessor beanPostProcessor = getReferenceAnnotationBeanPostProcessor();
referencesMetadata.putAll(buildReferencesMetadata(beanPostProcessor.getInjectedFieldReferenceBeanMap()));
referencesMetadata.putAll(buildReferencesMetadata(beanPostProcessor.getInjectedMethodReferenceBeanMap()));
return referencesMetadata;
}
private Map<String, Map<String, Object>> buildReferencesMetadata(
Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> injectedElementReferenceBeanMap) {
Map<String, Map<String, Object>> referencesMetadata = new LinkedHashMap<>();
for (Map.Entry<InjectionMetadata.InjectedElement, ReferenceBean<?>> entry :
injectedElementReferenceBeanMap.entrySet()) { | InjectionMetadata.InjectedElement injectedElement = entry.getKey();
ReferenceBean<?> referenceBean = entry.getValue();
Map<String, Object> beanMetadata = resolveBeanMetadata(referenceBean);
beanMetadata.put("invoker", resolveBeanMetadata(referenceBean.get()));
referencesMetadata.put(String.valueOf(injectedElement.getMember()), beanMetadata);
}
return referencesMetadata;
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\metadata\DubboReferencesMetadata.java | 2 |
请完成以下Java代码 | public TaxAccounts getAccounts(@NonNull final TaxId taxId, @NonNull final AcctSchemaId acctSchemaId)
{
final ImmutableMap<AcctSchemaId, TaxAccounts> map = cache.getOrLoad(taxId, this::retrieveAccounts);
final TaxAccounts accounts = map.get(acctSchemaId);
if (accounts == null)
{
throw new AdempiereException("No Tax accounts defined for " + taxId + " and " + acctSchemaId);
}
return accounts;
}
private ImmutableMap<AcctSchemaId, TaxAccounts> retrieveAccounts(@NonNull final TaxId taxId)
{
return queryBL.createQueryBuilder(I_C_Tax_Acct.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Tax_Acct.COLUMNNAME_C_Tax_ID, taxId)
.create()
.stream()
.map(TaxAccountsRepository::fromRecord)
.collect(ImmutableMap.toImmutableMap(TaxAccounts::getAcctSchemaId, accounts -> accounts)); | }
@NonNull
private static TaxAccounts fromRecord(@NonNull final I_C_Tax_Acct record)
{
return TaxAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.T_Due_Acct(Account.of(AccountId.ofRepoId(record.getT_Due_Acct()), TaxAcctType.TaxDue))
.T_Liability_Acct(Account.of(AccountId.ofRepoId(record.getT_Liability_Acct()), TaxAcctType.TaxLiability))
.T_Credit_Acct(Account.of(AccountId.ofRepoId(record.getT_Credit_Acct()), TaxAcctType.TaxCredit))
.T_Receivables_Acct(Account.of(AccountId.ofRepoId(record.getT_Receivables_Acct()), TaxAcctType.TaxReceivables))
.T_Expense_Acct(Account.of(AccountId.ofRepoId(record.getT_Expense_Acct()), TaxAcctType.TaxExpense))
.T_Revenue_Acct(Account.optionalOfRepoId(record.getT_Revenue_Acct(), TaxAcctType.T_Revenue_Acct))
.T_PayDiscount_Exp_Acct(Account.optionalOfRepoId(record.getT_PayDiscount_Exp_Acct(), TaxAcctType.T_PayDiscount_Exp_Acct))
.T_PayDiscount_Rev_Acct(Account.optionalOfRepoId(record.getT_PayDiscount_Rev_Acct(), TaxAcctType.T_PayDiscount_Rev_Acct))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\TaxAccountsRepository.java | 1 |
请完成以下Java代码 | private void initUI()
{
MiniTable table = new MiniTable();
table.setRowSelectionAllowed(true);
table.setShowTotals(true);
warehouseTbl = table;
fieldDescription = new CTextArea();
fieldDescription.setBackground(AdempierePLAF.getInfoBackground());
fieldDescription.setEditable(false);
fieldDescription.setPreferredSize(null); // just to make sure it has no predefined size
}
private void init()
{
ColumnInfo[] s_layoutWarehouse = new ColumnInfo[] {
new ColumnInfo(" ", "M_Warehouse_ID", IDColumn.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "Warehouse"), "Warehouse", String.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "QtyOnHand"), "sum(QtyOnHand)", Double.class),
};
/** From Clause */
String s_sqlFrom = " M_PRODUCT_STOCK_V ";
/** Where Clause */
String s_sqlWhere = "M_Product_ID = ?";
m_sqlWarehouse = warehouseTbl.prepareTable(s_layoutWarehouse, s_sqlFrom, s_sqlWhere, false, "M_PRODUCT_STOCK_V");
m_sqlWarehouse += " GROUP BY M_Warehouse_ID, Warehouse, documentnote ";
warehouseTbl.setMultiSelection(false);
// warehouseTbl.addMouseListener(this);
// warehouseTbl.getSelectionModel().addListSelectionListener(this);
warehouseTbl.autoSize();
}
private void refresh(int M_Product_ID)
{
// int M_Product_ID = 0;
String sql = m_sqlWarehouse;
// Add description to the query
sql = sql.replace(" FROM", ", DocumentNote FROM");
log.trace(sql);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID);
rs = pstmt.executeQuery();
setDescription("");
warehouseTbl.loadTable(rs);
rs = pstmt.executeQuery();
if (rs.next())
{
if (rs.getString("DocumentNote") != null)
setDescription(rs.getString("DocumentNote"));
}
}
catch (Exception e)
{
log.warn(sql, e);
}
finally
{
DB.close(rs, pstmt); | rs = null;
pstmt = null;
}
}
private void setDescription(String description)
{
fieldDescription.setText(description);
}
public java.awt.Component getComponent(int type)
{
if (type == PANELTYPE_Stock)
return (java.awt.Component)warehouseTbl;
else if (type == PANELTYPE_Description)
return fieldDescription;
else
throw new IllegalArgumentException("Unknown panel type " + type);
}
public int getM_Warehouse_ID()
{
if (warehouseTbl.getRowCount() <= 0)
return -1;
Integer id = warehouseTbl.getSelectedRowKey();
return id == null ? -1 : id;
}
@Override
public void refresh(final int M_Product_ID, final int M_Warehouse_ID, final int M_AttributeSetInstance_ID, final int M_PriceList_Version_ID)
{
refresh(M_Product_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductStock.java | 1 |
请完成以下Java代码 | protected FetchAndLockBuilder getBuilder(ProcessEngine engine) {
ExternalTaskService service = engine.getExternalTaskService();
FetchAndLockBuilder builder = service.fetchAndLock()
.workerId(workerId)
.maxTasks(maxTasks)
.usePriority(usePriority);
SortMapper mapper = new SortMapper(sorting, builder);
return mapper.getBuilderWithSortConfigs();
}
/**
* Encapsulates the mapping of sorting configurations (field, order) to the respective methods builder config methods
* and applies them.
* <p>
* To achieve that, maps are used internally to map fields and orders to the corresponding builder method.
*/
static class SortMapper {
protected static Map<String, Consumer<FetchAndLockBuilder>> FIELD_MAPPINGS = Map.of(
"createTime", FetchAndLockBuilder::orderByCreateTime
);
protected static Map<String, Consumer<FetchAndLockBuilder>> ORDER_MAPPINGS = Map.of(
"asc", FetchAndLockBuilder::asc,
"desc", FetchAndLockBuilder::desc
);
protected final List<SortingDto> sorting;
protected final FetchAndLockBuilder builder;
protected SortMapper(List<SortingDto> sorting, FetchAndLockBuilder builder) {
this.sorting = (sorting == null) ? Collections.emptyList() : sorting;
this.builder = builder;
}
/**
* Applies the sorting field mappings to the builder and returns it.
*/
protected FetchAndLockBuilder getBuilderWithSortConfigs() { | for (SortingDto dto : sorting) {
String sortBy = dto.getSortBy();
configureFieldOrBadRequest(sortBy, "sortBy", FIELD_MAPPINGS);
String sortOrder = dto.getSortOrder();
if (sortOrder != null) {
configureFieldOrBadRequest(sortOrder, "sortOrder", ORDER_MAPPINGS);
}
}
return builder;
}
protected void configureFieldOrBadRequest(String key, String parameterName, Map<String, Consumer<FetchAndLockBuilder>> fieldMappings) {
if (!fieldMappings.containsKey(key)) {
throw new InvalidRequestException(BAD_REQUEST, "Cannot set query " + parameterName + " parameter to value " + key);
}
fieldMappings.get(key).accept(builder);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\FetchExternalTasksDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SearchController {
public static final int PAGE_ITEMS_COUNT = 10;
@FXML
private TextField searchField;
@FXML
private Button searchButton;
@FXML
private Label searchLabel;
@FXML
private TableView tableView;
@FXML
private VBox dataContainer;
private ObservableList<Person> masterData = FXCollections.observableArrayList();
private ObservableList<Person> results = FXCollections.observableList(masterData);
public SearchController() {
masterData.add(new Person(5, "John", true));
masterData.add(new Person(7, "Albert", true));
masterData.add(new Person(11, "Monica", false));
}
@FXML
private void initialize() {
// search panel
searchButton.setText("Search");
searchButton.setOnAction(event -> loadData());
searchButton.setStyle("-fx-background-color: slateblue; -fx-text-fill: white;");
searchField.setOnKeyPressed(event -> {
if (event.getCode().equals(KeyCode.ENTER)) {
loadData();
}
});
searchField.textProperty().addListener((observable, oldValue, newValue) -> {
searchLabel.setText(newValue);
});
initTable();
} | private void initTable() {
tableView = new TableView<>(FXCollections.observableList(masterData));
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
TableColumn id = new TableColumn("ID");
id.setCellValueFactory(new PropertyValueFactory("id"));
TableColumn name = new TableColumn("NAME");
name.setCellValueFactory(new PropertyValueFactory("name"));
TableColumn employed = new TableColumn("EMPLOYED");
employed.setCellValueFactory(new PropertyValueFactory("isEmployed"));
tableView.getColumns().addAll(id, name, employed);
dataContainer.getChildren().add(tableView);
}
private void loadData() {
String searchText = searchField.getText();
Task<ObservableList<Person>> task = new Task<ObservableList<Person>>() {
@Override
protected ObservableList<Person> call() throws Exception {
updateMessage("Loading data");
return FXCollections.observableArrayList(masterData
.stream()
.filter(value -> value.getName().toLowerCase().contains(searchText))
.collect(Collectors.toList()));
}
};
task.setOnSucceeded(event -> {
results = task.getValue();
tableView.setItems(FXCollections.observableList(results));
});
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
}
} | repos\tutorials-master\javafx\src\main\java\com\baeldung\view\SearchController.java | 2 |
请完成以下Java代码 | private String asUserRolesProperty(String userProperty) {
return String.format("%s.roles", userProperty);
}
private String asUserUsernameProperty(String userProperty) {
return String.format("%s.username", userProperty);
}
@Nullable
@Override
public Object getProperty(String name) {
return getSource().getProperty(name);
}
@NonNull
protected Predicate<String> getVcapServicePredicate() {
return this.vcapServicePredicate != null
? this.vcapServicePredicate
: propertyName -> true;
}
@Override
public Iterator<String> iterator() {
return Collections.unmodifiableList(Arrays.asList(getSource().getPropertyNames())).iterator();
}
@NonNull | public VcapPropertySource withVcapServiceName(@NonNull String serviceName) {
Assert.hasText(serviceName, "Service name is required");
String resolvedServiceName = StringUtils.trimAllWhitespace(serviceName);
Predicate<String> vcapServiceNamePredicate = propertyName ->
propertyName.startsWith(String.format("%1$s%2$s.", VCAP_SERVICES_PROPERTY, resolvedServiceName));
return withVcapServicePredicate(vcapServiceNamePredicate);
}
@NonNull
public VcapPropertySource withVcapServicePredicate(@Nullable Predicate<String> vcapServicePredicate) {
this.vcapServicePredicate = vcapServicePredicate;
return this;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\VcapPropertySource.java | 1 |
请完成以下Java代码 | public void setResponseCodeText (java.lang.String ResponseCodeText)
{
set_Value (COLUMNNAME_ResponseCodeText, ResponseCodeText);
}
/** Get Antwort Text.
@return Antwort Text */
@Override
public java.lang.String getResponseCodeText ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponseCodeText);
}
/** Set Antwort Details.
@param ResponseDetails Antwort Details */
@Override
public void setResponseDetails (java.lang.String ResponseDetails)
{
set_ValueNoCheck (COLUMNNAME_ResponseDetails, ResponseDetails);
}
/** Get Antwort Details.
@return Antwort Details */
@Override
public java.lang.String getResponseDetails ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponseDetails);
}
/** Set Transaktionsreferenz Kunde .
@param TransactionCustomerId Transaktionsreferenz Kunde */
@Override
public void setTransactionCustomerId (java.lang.String TransactionCustomerId)
{
set_ValueNoCheck (COLUMNNAME_TransactionCustomerId, TransactionCustomerId);
} | /** Get Transaktionsreferenz Kunde .
@return Transaktionsreferenz Kunde */
@Override
public java.lang.String getTransactionCustomerId ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionCustomerId);
}
/** Set Transaktionsreferenz API.
@param TransactionIdAPI Transaktionsreferenz API */
@Override
public void setTransactionIdAPI (java.lang.String TransactionIdAPI)
{
set_ValueNoCheck (COLUMNNAME_TransactionIdAPI, TransactionIdAPI);
}
/** Get Transaktionsreferenz API.
@return Transaktionsreferenz API */
@Override
public java.lang.String getTransactionIdAPI ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\base\src\main\java-gen\de\metas\vertical\creditscore\base\model\X_CS_Transaction_Result.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setIsConsiderAttributes (final boolean IsConsiderAttributes)
{
set_Value (COLUMNNAME_IsConsiderAttributes, IsConsiderAttributes);
}
@Override
public boolean isConsiderAttributes()
{
return get_ValueAsBoolean(COLUMNNAME_IsConsiderAttributes);
}
@Override
public void setIsPickingReviewRequired (final boolean IsPickingReviewRequired)
{
set_Value (COLUMNNAME_IsPickingReviewRequired, IsPickingReviewRequired);
}
@Override
public boolean isPickingReviewRequired() | {
return get_ValueAsBoolean(COLUMNNAME_IsPickingReviewRequired);
}
@Override
public void setM_Picking_Config_V2_ID (final int M_Picking_Config_V2_ID)
{
if (M_Picking_Config_V2_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Config_V2_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Picking_Config_V2_ID, M_Picking_Config_V2_ID);
}
@Override
public int getM_Picking_Config_V2_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Config_V2_ID);
}
} | 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_V2.java | 1 |
请完成以下Java代码 | public final class AuthorizationManagerWebInvocationPrivilegeEvaluator
implements WebInvocationPrivilegeEvaluator, ServletContextAware {
private final AuthorizationManager<HttpServletRequest> authorizationManager;
private @Nullable ServletContext servletContext;
private HttpServletRequestTransformer requestTransformer = HttpServletRequestTransformer.IDENTITY;
public AuthorizationManagerWebInvocationPrivilegeEvaluator(
AuthorizationManager<HttpServletRequest> authorizationManager) {
Assert.notNull(authorizationManager, "authorizationManager cannot be null");
this.authorizationManager = authorizationManager;
}
@Override
public boolean isAllowed(String uri, @Nullable Authentication authentication) {
return isAllowed(null, uri, null, authentication);
}
@Override
public boolean isAllowed(@Nullable String contextPath, String uri, @Nullable String method,
@Nullable Authentication authentication) {
FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method, this.servletContext);
HttpServletRequest httpRequest = this.requestTransformer.transform(filterInvocation.getHttpRequest());
AuthorizationResult result = this.authorizationManager.authorize(() -> authentication, httpRequest);
return result == null || result.isGranted();
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* Set a {@link HttpServletRequestTransformer} to be used prior to passing to the
* {@link AuthorizationManager}. | * @param requestTransformer the {@link HttpServletRequestTransformer} to use.
*/
public void setRequestTransformer(HttpServletRequestTransformer requestTransformer) {
Assert.notNull(requestTransformer, "requestTransformer cannot be null");
this.requestTransformer = requestTransformer;
}
/**
* Used to transform the {@link HttpServletRequest} prior to passing it into the
* {@link AuthorizationManager}.
*/
public interface HttpServletRequestTransformer {
HttpServletRequestTransformer IDENTITY = (request) -> request;
/**
* Return the {@link HttpServletRequest} that is passed into the
* {@link AuthorizationManager}
* @param request the {@link HttpServletRequest} created by the
* {@link WebInvocationPrivilegeEvaluator}
* @return the {@link HttpServletRequest} that is passed into the
* {@link AuthorizationManager}
*/
HttpServletRequest transform(HttpServletRequest request);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\AuthorizationManagerWebInvocationPrivilegeEvaluator.java | 1 |
请完成以下Java代码 | protected String getXMLElementName() {
return ELEMENT_TASK_SEND;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
SendTask sendTask = new SendTask();
BpmnXMLUtil.addXMLLocation(sendTask, xtr);
sendTask.setType(BpmnXMLUtil.getAttributeValue(ATTRIBUTE_TYPE, xtr));
if ("##WebService".equals(xtr.getAttributeValue(null, ATTRIBUTE_TASK_IMPLEMENTATION))) {
sendTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE);
sendTask.setOperationRef(parseOperationRef(xtr.getAttributeValue(null, ATTRIBUTE_TASK_OPERATION_REF), model));
}
parseChildElements(getXMLElementName(), sendTask, model, xtr);
return sendTask;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
SendTask sendTask = (SendTask) element;
if (StringUtils.isNotEmpty(sendTask.getType())) {
writeQualifiedAttribute(ATTRIBUTE_TYPE, sendTask.getType(), xtw);
}
}
@Override
protected boolean writeExtensionChildElements(BaseElement element, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception { | SendTask sendTask = (SendTask) element;
didWriteExtensionStartElement = FieldExtensionExport.writeFieldExtensions(sendTask.getFieldExtensions(), didWriteExtensionStartElement, xtw);
return didWriteExtensionStartElement;
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
}
protected String parseOperationRef(String operationRef, BpmnModel model) {
String result = null;
if (StringUtils.isNotEmpty(operationRef)) {
int indexOfP = operationRef.indexOf(':');
if (indexOfP != -1) {
String prefix = operationRef.substring(0, indexOfP);
String resolvedNamespace = model.getNamespace(prefix);
result = resolvedNamespace + ":" + operationRef.substring(indexOfP + 1);
} else {
result = model.getTargetNamespace() + ":" + operationRef;
}
}
return result;
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\SendTaskXMLConverter.java | 1 |
请完成以下Java代码 | public String getName() {
return MetricsUtil.resolvePublicName(name);
}
public void setName(String name) {
this.name = name;
}
public String getReporter() {
return reporter;
}
public void setReporter(String reporter) {
this.reporter = reporter;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
@Override
public String getId() {
return name + reporter + timestamp.toString();
}
@Override
public void setId(String id) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object getPersistentState() {
return MetricIntervalEntity.class;
}
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + (this.timestamp != null ? this.timestamp.hashCode() : 0);
hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 67 * hash + (this.reporter != null ? this.reporter.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) { | if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MetricIntervalEntity other = (MetricIntervalEntity) obj;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
if ((this.reporter == null) ? (other.reporter != null) : !this.reporter.equals(other.reporter)) {
return false;
}
if (this.timestamp != other.timestamp && (this.timestamp == null || !this.timestamp.equals(other.timestamp))) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MetricIntervalEntity.java | 1 |
请完成以下Java代码 | public void requestFocus()
{
if (isSimpleSearchPanelActive())
{
if (m_editorFirst != null)
{
m_editorFirst.requestFocus();
}
}
}
@Override
public boolean requestFocusInWindow()
{
if (isSimpleSearchPanelActive())
{ | if (m_editorFirst != null)
{
return m_editorFirst.requestFocusInWindow();
}
}
return false;
}
private boolean disposed = false;
boolean isDisposed()
{
return disposed;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanel.java | 1 |
请完成以下Java代码 | public void run() {
// serialize cookies to persistent storage
}
@Override
public void add(URI uri, HttpCookie cookie) {
store.add(uri, cookie);
}
@Override
public List<HttpCookie> get(URI uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<HttpCookie> getCookies() {
// TODO Auto-generated method stub
return null;
}
@Override | public List<URI> getURIs() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean remove(URI uri, HttpCookie cookie) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean removeAll() {
// TODO Auto-generated method stub
return false;
}
} | repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\cookies\PersistentCookieStore.java | 1 |
请完成以下Java代码 | public float calculateTotalWeight() {
return packageItems.stream().map(PackageItem::getWeight)
.reduce(0F, Float::sum);
}
public boolean isTaxable() {
return calculateEstimatedValue() > 100;
}
public float calculateEstimatedValue() {
return packageItems.stream().map(PackageItem::getWeight)
.reduce(0F, Float::sum);
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) { | this.orderId = orderId;
}
public String getTrackingId() {
return trackingId;
}
public void setTrackingId(String trackingId) {
this.trackingId = trackingId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} | repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-shippingcontext\src\main\java\com\baeldung\dddcontexts\shippingcontext\model\Parcel.java | 1 |
请完成以下Java代码 | public void deleteTaskMetricsByTimestamp(Date timestamp) {
Map<String, Object> parameters = Collections.singletonMap("timestamp", timestamp);
getDbEntityManager().delete(TaskMeterLogEntity.class, DELETE_TASK_METER_BY_TIMESTAMP, parameters);
}
public void deleteTaskMetricsById(List<String> taskMetricIds) {
getDbEntityManager().deletePreserveOrder(TaskMeterLogEntity.class, DELETE_TASK_METER_BY_IDS, taskMetricIds);
}
public DbOperation deleteTaskMetricsByRemovalTime(Date currentTimestamp, Integer timeToLive, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<>();
// data inserted prior to now minus timeToLive-days can be removed
Date removalTime = Date.from(currentTimestamp.toInstant().minus(timeToLive, ChronoUnit.DAYS));
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(TaskMeterLogEntity.class, DELETE_TASK_METER_BY_REMOVAL_TIME,
new ListQueryParameterObject(parameters, 0, batchSize)); | }
@SuppressWarnings("unchecked")
public List<String> findTaskMetricsForCleanup(int batchSize, Integer timeToLive, int minuteFrom, int minuteTo) {
Map<String, Object> queryParameters = new HashMap<>();
queryParameters.put("currentTimestamp", ClockUtil.getCurrentTime());
queryParameters.put("timeToLive", timeToLive);
if (minuteTo - minuteFrom + 1 < 60) {
queryParameters.put("minuteFrom", minuteFrom);
queryParameters.put("minuteTo", minuteTo);
}
ListQueryParameterObject parameterObject = new ListQueryParameterObject(queryParameters, 0, batchSize);
parameterObject.getOrderingProperties().add(new QueryOrderingProperty(new QueryPropertyImpl("TIMESTAMP_"), Direction.ASCENDING));
return (List<String>) getDbEntityManager().selectList(SELECT_TASK_METER_FOR_CLEANUP, parameterObject);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MeterLogManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BackupCodeTwoFaProvider implements TwoFaProvider<BackupCodeTwoFaProviderConfig, BackupCodeTwoFaAccountConfig> {
@Autowired @Lazy
private TwoFaConfigManager twoFaConfigManager;
@Override
public BackupCodeTwoFaAccountConfig generateNewAccountConfig(User user, BackupCodeTwoFaProviderConfig providerConfig) {
BackupCodeTwoFaAccountConfig config = new BackupCodeTwoFaAccountConfig();
config.setCodes(generateCodes(providerConfig.getCodesQuantity(), 8));
config.setSerializeHiddenFields(true);
return config;
}
private static Set<String> generateCodes(int count, int length) {
return Stream.generate(() -> StringUtils.random(length, "0123456789abcdef"))
.distinct().limit(count)
.collect(Collectors.toSet());
}
@Override
public boolean checkVerificationCode(SecurityUser user, String code, BackupCodeTwoFaProviderConfig providerConfig, BackupCodeTwoFaAccountConfig accountConfig) { | if (CollectionsUtil.contains(accountConfig.getCodes(), code)) {
accountConfig.getCodes().remove(code);
twoFaConfigManager.saveTwoFaAccountConfig(user.getTenantId(), user, accountConfig);
return true;
} else {
return false;
}
}
@Override
public TwoFaProviderType getType() {
return TwoFaProviderType.BACKUP_CODE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\provider\impl\BackupCodeTwoFaProvider.java | 2 |
请完成以下Java代码 | private JsonDataEntryField toJsonDataEntryField(
@NonNull final DataEntryField layoutField,
@NonNull final DataEntryRecord dataEntryRecord)
{
final Object fieldValue = dataEntryRecord.getFieldValue(layoutField.getId()).orElse(null);
return JsonDataEntryField.builder()
.id(layoutField.getId())
.caption(layoutField.getCaption().translate(adLanguage))
.description(layoutField.getDescription().translate(adLanguage))
.type(JsonFieldType.getBy(layoutField.getType()))
.mandatory(layoutField.isMandatory())
.listValues(toJsonDataEntryListValues(layoutField))
.value(fieldValue)
.build();
}
@NonNull
private ImmutableList<JsonDataEntryListValue> toJsonDataEntryListValues(@NonNull final DataEntryField layoutField) | {
return layoutField.getListValues()
.stream()
.map(this::toJsonDataEntryListValue)
.collect(ImmutableList.toImmutableList());
}
private JsonDataEntryListValue toJsonDataEntryListValue(@NonNull final DataEntryListValue listValue)
{
return JsonDataEntryListValue.builder()
.id(listValue.getId())
.name(listValue.getName().translate(adLanguage))
.description(listValue.getDescription().translate(adLanguage))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\dataentry\impl\JsonDataEntryFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StockAvailabilityRabbitMQListener
{
private static final Logger logger = LoggerFactory.getLogger(StockAvailabilityRabbitMQListener.class);
@Autowired
private StockAvailabilityService stockAvailabilityService;
@RabbitListener(queues = RabbitMQConfig.QUEUENAME_StockAvailabilityUpdatedEvent)
public void onStockAvailabilityUpdatedEvent(final MSV3StockAvailabilityUpdatedEvent event)
{
try
{
stockAvailabilityService.handleEvent(event);
}
catch (Exception ex)
{
logger.warn("Failed handling event: {}", event, ex);
}
} | @RabbitListener(queues = RabbitMQConfig.QUEUENAME_ProductExcludeUpdatedEvents)
public void onProductExcludesUpdateEvent(final MSV3ProductExcludesUpdateEvent event)
{
try
{
stockAvailabilityService.handleEvent(event);
}
catch (Exception ex)
{
logger.warn("Failed handling event: {}", event, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\stockAvailability\sync\StockAvailabilityRabbitMQListener.java | 2 |
请完成以下Java代码 | public class DefaultEdqsRepository implements EdqsRepository {
@Getter
private final static ConcurrentMap<TenantId, TenantRepo> repos = new ConcurrentHashMap<>();
private final EdqsStatsService statsService;
public TenantRepo get(TenantId tenantId) {
return repos.computeIfAbsent(tenantId, id -> new TenantRepo(id, statsService));
}
@Override
public void processEvent(EdqsEvent event) {
if (event.getEventType() == EdqsEventType.DELETED && event.getObjectType() == ObjectType.TENANT) {
log.info("Tenant {} deleted", event.getTenantId());
repos.remove(event.getTenantId());
statsService.reportRemoved(ObjectType.TENANT);
} else {
get(event.getTenantId()).processEvent(event);
}
}
@Override
public long countEntitiesByQuery(TenantId tenantId, CustomerId customerId, EntityCountQuery query, boolean ignorePermissionCheck) {
long startNs = System.nanoTime();
long result = get(tenantId).countEntitiesByQuery(customerId, query, ignorePermissionCheck);
statsService.reportEdqsCountQuery(tenantId, query, System.nanoTime() - startNs);
return result;
} | @Override
public PageData<QueryResult> findEntityDataByQuery(TenantId tenantId, CustomerId customerId,
EntityDataQuery query, boolean ignorePermissionCheck) {
long startNs = System.nanoTime();
var result = get(tenantId).findEntityDataByQuery(customerId, query, ignorePermissionCheck);
statsService.reportEdqsDataQuery(tenantId, query, System.nanoTime() - startNs);
return result;
}
@Override
public void clearIf(Predicate<TenantId> predicate) {
repos.keySet().removeIf(predicate);
}
@Override
public void clear() {
repos.clear();
}
} | repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\repo\DefaultEdqsRepository.java | 1 |
请完成以下Java代码 | public static ViewRowsOrderBy empty(@NonNull final JSONOptions jsonOpts)
{
return new ViewRowsOrderBy(DocumentQueryOrderByList.EMPTY, jsonOpts);
}
private final DocumentQueryOrderByList orderBys;
private final JSONOptions jsonOpts;
private ViewRowsOrderBy(final DocumentQueryOrderByList orderBys, @NonNull final JSONOptions jsonOpts)
{
this.orderBys = orderBys != null ? orderBys : DocumentQueryOrderByList.EMPTY;
this.jsonOpts = jsonOpts;
}
public boolean isEmpty()
{
return orderBys.isEmpty();
}
public DocumentQueryOrderByList toDocumentQueryOrderByList()
{
return orderBys;
}
public ViewRowsOrderBy withOrderBys(final DocumentQueryOrderByList orderBys)
{
if (DocumentQueryOrderByList.equals(this.orderBys, orderBys))
{ | return this;
}
else
{
return new ViewRowsOrderBy(orderBys, jsonOpts);
}
}
public <T extends IViewRow> Comparator<T> toComparator()
{
return orderBys.toComparator(IViewRow::getFieldValueAsComparable, jsonOpts);
}
public <T extends IViewRow> Comparator<T> toComparatorOrNull()
{
return !orderBys.isEmpty() ? toComparator() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowsOrderBy.java | 1 |
请完成以下Java代码 | public void setCustomerNo (java.lang.String CustomerNo)
{
set_Value (COLUMNNAME_CustomerNo, CustomerNo);
}
/** Get Kundennummer.
@return Kundennummer */
@Override
public java.lang.String getCustomerNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_CustomerNo);
}
/** Set MKTG_CleverReach_Config.
@param MKTG_CleverReach_Config_ID MKTG_CleverReach_Config */
@Override
public void setMKTG_CleverReach_Config_ID (int MKTG_CleverReach_Config_ID)
{
if (MKTG_CleverReach_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_CleverReach_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_CleverReach_Config_ID, Integer.valueOf(MKTG_CleverReach_Config_ID));
}
/** Get MKTG_CleverReach_Config.
@return MKTG_CleverReach_Config */
@Override
public int getMKTG_CleverReach_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_CleverReach_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set MKTG_Platform.
@param MKTG_Platform_ID MKTG_Platform */
@Override
public void setMKTG_Platform_ID (int MKTG_Platform_ID)
{
if (MKTG_Platform_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID));
}
/** Get MKTG_Platform.
@return MKTG_Platform */
@Override
public int getMKTG_Platform_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Kennwort.
@param Password Kennwort */
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
} | /** Get Kennwort.
@return Kennwort */
@Override
public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
@Override
public java.lang.String getUserName ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java-gen\de\metas\marketing\cleverreach\model\X_MKTG_CleverReach_Config.java | 1 |
请完成以下Java代码 | public String getPassword(final String hostname, final String port, final String dbName, final String username)
{
final PgPassEntry entryLookup = new PgPassEntry(hostname, port, dbName, username, null); // password=null
for (final PgPassEntry entry : getEntries())
{
if (matches(entry, entryLookup))
{
return entry.getPassword();
}
}
return null;
}
private boolean matches(final PgPassEntry entry, final PgPassEntry entryLookup)
{
return matchesToken(entry.getHost(), entryLookup.getHost())
&& matchesToken(entry.getPort(), entryLookup.getPort())
&& matchesToken(entry.getDbName(), entryLookup.getDbName())
&& matchesToken(entry.getUser(), entryLookup.getUser());
}
private static boolean matchesToken(final String token, final String tokenLookup)
{
if (token == null)
{
// shall not happen, development error
throw new IllegalStateException("token shall not be null");
}
if (ANY.equals(tokenLookup))
{ | throw new IllegalStateException("token lookup shall not be ANY");
}
//
if (token == tokenLookup)
{
return true;
}
if (ANY.equals(token))
{
return true;
}
if (token.equals(tokenLookup))
{
return true;
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\postgresql\PgPassFile.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class MethodObservationConfiguration {
private static final SecurityObservationSettings all = SecurityObservationSettings.withDefaults()
.shouldObserveRequests(true)
.shouldObserveAuthentications(true)
.shouldObserveAuthorizations(true)
.build();
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static ObjectPostProcessor<AuthorizationManager<MethodInvocation>> methodAuthorizationManagerPostProcessor(
ObjectProvider<ObservationRegistry> registry, ObjectProvider<SecurityObservationSettings> predicate) {
return new ObjectPostProcessor<>() {
@Override
public AuthorizationManager postProcess(AuthorizationManager object) {
ObservationRegistry r = registry.getIfUnique(() -> ObservationRegistry.NOOP);
boolean active = !r.isNoop() && predicate.getIfUnique(() -> all).shouldObserveAuthorizations();
return active ? new ObservationAuthorizationManager<>(r, object) : object; | }
};
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static ObjectPostProcessor<AuthorizationManager<MethodInvocationResult>> methodResultAuthorizationManagerPostProcessor(
ObjectProvider<ObservationRegistry> registry, ObjectProvider<SecurityObservationSettings> predicate) {
return new ObjectPostProcessor<>() {
@Override
public AuthorizationManager postProcess(AuthorizationManager object) {
ObservationRegistry r = registry.getIfUnique(() -> ObservationRegistry.NOOP);
boolean active = !r.isNoop() && predicate.getIfUnique(() -> all).shouldObserveAuthorizations();
return active ? new ObservationAuthorizationManager<>(r, object) : object;
}
};
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\MethodObservationConfiguration.java | 2 |
请完成以下Java代码 | public boolean isDebit()
{
if (isReversal())
{
return toMoney().signum() <= 0;
}
else
{
return toMoney().signum() >= 0;
}
}
public CurrencyId getCurrencyId() {return Money.getCommonCurrencyIdOfAll(debit, credit);}
public Balance negateAndInvert()
{
return new Balance(this.credit.negate(), this.debit.negate());
}
public Balance negateAndInvertIf(final boolean condition)
{
return condition ? negateAndInvert() : this;
}
public Balance toSingleSide()
{
final Money min = debit.min(credit);
if (min.isZero())
{
return this;
}
return new Balance(this.debit.subtract(min), this.credit.subtract(min));
}
public Balance computeDiffToBalance()
{
final Money diff = toMoney();
if (isReversal())
{
return diff.signum() < 0 ? ofCredit(diff) : ofDebit(diff.negate());
}
else
{
return diff.signum() < 0 ? ofDebit(diff.negate()) : ofCredit(diff);
}
}
public Balance invert()
{
return new Balance(this.credit, this.debit);
}
//
// | //
//
//
@ToString
private static class BalanceBuilder
{
private Money debit;
private Money credit;
public void add(@NonNull Balance balance)
{
add(balance.getDebit(), balance.getCredit());
}
public BalanceBuilder combine(@NonNull BalanceBuilder balanceBuilder)
{
add(balanceBuilder.debit, balanceBuilder.credit);
return this;
}
public void add(@Nullable Money debitToAdd, @Nullable Money creditToAdd)
{
if (debitToAdd != null)
{
this.debit = this.debit != null ? this.debit.add(debitToAdd) : debitToAdd;
}
if (creditToAdd != null)
{
this.credit = this.credit != null ? this.credit.add(creditToAdd) : creditToAdd;
}
}
public Optional<Balance> build()
{
return debit != null || credit != null
? Optional.of(new Balance(debit, credit))
: Optional.empty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Balance.java | 1 |
请完成以下Java代码 | public class User {
private String name;
private String email;
private int age;
public User() {
}
public User(String name, String emailmail, int age) {
this.name = name;
this.email = email;
this.age = age;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name; | }
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\java\com\baeldung\springvalidator\User.java | 1 |
请完成以下Java代码 | public boolean isBillTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsBillTo);
}
@Override
public void setIsBillToDefault (final boolean IsBillToDefault)
{
set_Value (COLUMNNAME_IsBillToDefault, IsBillToDefault);
}
@Override
public boolean isBillToDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsBillToDefault);
}
@Override
public void setIsHandOverLocation (final boolean IsHandOverLocation)
{
set_Value (COLUMNNAME_IsHandOverLocation, IsHandOverLocation);
}
@Override
public boolean isHandOverLocation()
{
return get_ValueAsBoolean(COLUMNNAME_IsHandOverLocation);
}
@Override
public void setIsOneTime (final boolean IsOneTime)
{
set_Value (COLUMNNAME_IsOneTime, IsOneTime);
}
@Override
public boolean isOneTime()
{
return get_ValueAsBoolean(COLUMNNAME_IsOneTime);
}
@Override
public void setIsRemitTo (final boolean IsRemitTo)
{
set_Value (COLUMNNAME_IsRemitTo, IsRemitTo);
}
@Override
public boolean isRemitTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsRemitTo);
}
@Override
public void setIsReplicationLookupDefault (final boolean IsReplicationLookupDefault)
{
set_Value (COLUMNNAME_IsReplicationLookupDefault, IsReplicationLookupDefault);
}
@Override
public boolean isReplicationLookupDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsReplicationLookupDefault);
}
@Override
public void setIsShipTo (final boolean IsShipTo)
{
set_Value (COLUMNNAME_IsShipTo, IsShipTo);
}
@Override
public boolean isShipTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsShipTo);
}
@Override
public void setIsShipToDefault (final boolean IsShipToDefault) | {
set_Value (COLUMNNAME_IsShipToDefault, IsShipToDefault);
}
@Override
public boolean isShipToDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsShipToDefault);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No)
{
set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No);
}
@Override
public java.lang.String getSetup_Place_No()
{
return get_ValueAsString(COLUMNNAME_Setup_Place_No);
}
@Override
public void setVisitorsAddress (final boolean VisitorsAddress)
{
set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress);
}
@Override
public boolean isVisitorsAddress()
{
return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location_QuickInput.java | 1 |
请完成以下Java代码 | public void linkMaterialTracking(@NonNull final I_C_Invoice_Candidate candidate, @NonNull final I_M_Material_Tracking materialTracking)
{
final MaterialTrackingId oldMaterialTrackingId = MaterialTrackingId.ofRepoIdOrNull(candidate.getM_Material_Tracking_ID());
if (oldMaterialTrackingId != null)
{
final I_M_Material_Tracking oldMaterialTracking = materialTrackingDAO.getById(oldMaterialTrackingId);
if (oldMaterialTracking.isProcessed())
{
//old material tracking is processed, so we can't unlink from it
return;
}
}
final I_C_Invoice_Candidate existingICForMT = repo.getFirstForMaterialTrackingId(MaterialTrackingId.ofRepoId(materialTracking.getM_Material_Tracking_ID()))
.orElse(null);
if (existingICForMT != null && existingICForMT.getBill_BPartner_ID() != candidate.getBill_BPartner_ID())
{
//Not for the same BillBPartner as other ICs of the material tracking, can't add to group
return;
}
candidate.setM_Material_Tracking_ID(materialTracking.getM_Material_Tracking_ID());
if (existingICForMT != null) | {
final InvoiceCandidateHeaderAggregationId effectiveHeaderAggregationKeyId = IAggregationBL.getEffectiveHeaderAggregationKeyId(existingICForMT);
candidate.setC_Invoice_Candidate_HeaderAggregation_Override_ID(InvoiceCandidateHeaderAggregationId.toRepoId(effectiveHeaderAggregationKeyId));
}
aggregationBL.getUpdateProcessor().process(candidate);
repo.save(candidate);
materialTrackingBL.linkModelToMaterialTracking(MTLinkRequest.builder()
.model(candidate)
.previousMaterialTrackingId(MaterialTrackingId.toRepoId(oldMaterialTrackingId))
.ifModelAlreadyLinked(MTLinkRequest.IfModelAlreadyLinked.UNLINK_FROM_PREVIOUS)
.materialTrackingRecord(materialTracking)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingInvoiceCandService.java | 1 |
请完成以下Java代码 | public ViewLayout getViewLayout(@NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType)
{
final LayoutKey key = LayoutKey.builder()
.windowId(windowId)
.viewDataType(viewDataType)
.build();
return viewLayoutCache.getOrLoad(key, this::createViewLayout);
}
private ViewLayout createViewLayout(final LayoutKey key)
{
return ViewLayout.builder()
.setWindowId(key.getWindowId())
.setCaption(caption)
//
.setHasAttributesSupport(false)
.setHasTreeSupport(true) | .setTreeCollapsible(true)
.setTreeExpandedDepth(ViewLayout.TreeExpandedDepth_AllCollapsed)
//
.addElementsFromViewRowClass(PurchaseRow.class, key.getViewDataType())
//
.build();
}
@lombok.Value
@lombok.Builder
private static class LayoutKey
{
WindowId windowId;
JSONViewDataType viewDataType;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewLayoutFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookController {
@Autowired
private BookRepository bookRepository;
@GetMapping
public Iterable<Book> findAll() {
return bookRepository.findAll();
}
@GetMapping("/title/{bookTitle}")
public List<Book> findByTitle(@PathVariable String bookTitle) {
return bookRepository.findByTitle(bookTitle);
}
@GetMapping("/{id}")
public Book findOne(@PathVariable long id) {
return bookRepository.findById(id)
.orElseThrow(BookNotFoundException::new);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Book create(@RequestBody Book book) {
Book book1 = bookRepository.save(book);
return book1;
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) { | bookRepository.findById(id)
.orElseThrow(BookNotFoundException::new);
bookRepository.deleteById(id);
}
@PutMapping("/{id}")
public Book updateBook(@RequestBody Book book, @PathVariable long id) {
if (book.getId() != id) {
throw new BookIdMismatchException();
}
bookRepository.findById(id)
.orElseThrow(BookNotFoundException::new);
return bookRepository.save(book);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-bootstrap\src\main\java\com\baeldung\web\BookController.java | 2 |
请完成以下Java代码 | public EventLogEntryRequest.EventLogEntryRequestBuilder newErrorLogEntry(
@NonNull final Class<?> handlerClass,
@NonNull final Exception e)
{
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(e);
return EventLogEntryRequest.builder()
.error(true)
.eventHandlerClass(handlerClass)
.message(e.getMessage())
.adIssueId(issueId);
}
@Value
@Builder
public static class InvokeHandlerAndLogRequest
{
@NonNull
Class<?> handlerClass;
@NonNull
Runnable invokaction;
@Default
boolean onlyIfNotAlreadyProcessed = true;
}
/**
* Invokes the given {@code request}'s runnable and sets up a threadlocal {@link ILoggable}.
*/
public void invokeHandlerAndLog(@NonNull final InvokeHandlerAndLogRequest request)
{
if (request.isOnlyIfNotAlreadyProcessed()
&& wasEventProcessedByHandler(request.getHandlerClass()))
{
return;
} | try (final IAutoCloseable loggable = EventLogLoggable.createAndRegisterThreadLocal(request.getHandlerClass()))
{
request.getInvokaction().run();
newLogEntry(request.getHandlerClass())
.formattedMessage("this handler is done")
.processed(true)
.createAndStore();
}
catch (final RuntimeException e)
{
// e.printStackTrace();
newErrorLogEntry(
request.getHandlerClass(), e)
.createAndStore();
}
}
private boolean wasEventProcessedByHandler(@NonNull final Class<?> handlerClass)
{
final EventLogEntryCollector eventLogCollector = EventLogEntryCollector.getThreadLocal();
final Collection<String> processedByHandlerClassNames = eventLogCollector.getEvent()
.getProperty(PROPERTY_PROCESSED_BY_HANDLER_CLASS_NAMES);
return processedByHandlerClassNames != null
&& processedByHandlerClassNames.contains(handlerClass.getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogUserService.java | 1 |
请完成以下Java代码 | class BufferedStartupStep implements StartupStep {
private final String name;
private final long id;
private final @Nullable BufferedStartupStep parent;
private final List<Tag> tags = new ArrayList<>();
private final Consumer<BufferedStartupStep> recorder;
private final Instant startTime;
private final AtomicBoolean ended = new AtomicBoolean();
BufferedStartupStep(@Nullable BufferedStartupStep parent, String name, long id, Instant startTime,
Consumer<BufferedStartupStep> recorder) {
this.parent = parent;
this.name = name;
this.id = id;
this.startTime = startTime;
this.recorder = recorder;
}
@Nullable BufferedStartupStep getParent() {
return this.parent;
}
@Override
public String getName() {
return this.name;
}
@Override
public long getId() {
return this.id;
}
Instant getStartTime() {
return this.startTime;
}
@Override
public @Nullable Long getParentId() {
return (this.parent != null) ? this.parent.getId() : null;
}
@Override
public Tags getTags() {
return Collections.unmodifiableList(this.tags)::iterator;
}
@Override
public StartupStep tag(String key, Supplier<String> value) {
return tag(key, value.get());
}
@Override
public StartupStep tag(String key, String value) {
Assert.state(!this.ended.get(), "StartupStep has already ended.");
this.tags.add(new DefaultTag(key, value)); | return this;
}
@Override
public void end() {
this.ended.set(true);
this.recorder.accept(this);
}
boolean isEnded() {
return this.ended.get();
}
static class DefaultTag implements Tag {
private final String key;
private final String value;
DefaultTag(String key, String value) {
this.key = key;
this.value = value;
}
@Override
public String getKey() {
return this.key;
}
@Override
public String getValue() {
return this.value;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\metrics\buffering\BufferedStartupStep.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRefundReferenceId()
{
return refundReferenceId;
}
public void setRefundReferenceId(String refundReferenceId)
{
this.refundReferenceId = refundReferenceId;
}
public OrderRefund refundStatus(String refundStatus)
{
this.refundStatus = refundStatus;
return this;
}
/**
* This enumeration value indicates the current status of the refund to the buyer. This container is always returned for each refund. For implementation help, refer to <a href='https://developer.ebay.com/api-docs/sell/fulfillment/types/sel:RefundStatusEnum'>eBay API documentation</a>
*
* @return refundStatus
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "This enumeration value indicates the current status of the refund to the buyer. This container is always returned for each refund. For implementation help, refer to <a href='https://developer.ebay.com/api-docs/sell/fulfillment/types/sel:RefundStatusEnum'>eBay API documentation</a>")
public String getRefundStatus()
{
return refundStatus;
}
public void setRefundStatus(String refundStatus)
{
this.refundStatus = refundStatus;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
OrderRefund orderRefund = (OrderRefund)o;
return Objects.equals(this.amount, orderRefund.amount) &&
Objects.equals(this.refundDate, orderRefund.refundDate) &&
Objects.equals(this.refundId, orderRefund.refundId) &&
Objects.equals(this.refundReferenceId, orderRefund.refundReferenceId) &&
Objects.equals(this.refundStatus, orderRefund.refundStatus);
}
@Override
public int hashCode()
{ | return Objects.hash(amount, refundDate, refundId, refundReferenceId, refundStatus);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class OrderRefund {\n");
sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" refundDate: ").append(toIndentedString(refundDate)).append("\n");
sb.append(" refundId: ").append(toIndentedString(refundId)).append("\n");
sb.append(" refundReferenceId: ").append(toIndentedString(refundReferenceId)).append("\n");
sb.append(" refundStatus: ").append(toIndentedString(refundStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\OrderRefund.java | 2 |
请完成以下Java代码 | public void onBeforeComplete(final de.metas.rfq.model.I_C_RfQ rfq)
{
if (!isProcurement(rfq))
{
return;
}
final I_C_RfQ pmmRfq = InterfaceWrapperHelper.create(rfq, I_C_RfQ.class);
validatePMM_RfQ(pmmRfq);
}
private void validatePMM_RfQ(final I_C_RfQ pmmRfq)
{
//
// Make sure mandatory fields are filled
final List<String> notFilledMandatoryColumns = new ArrayList<>();
if (pmmRfq.getC_Flatrate_Conditions_ID() <= 0)
{
notFilledMandatoryColumns.add(I_C_RfQ.COLUMNNAME_C_Flatrate_Conditions_ID);
}
if (pmmRfq.getDateWorkStart() == null)
{
notFilledMandatoryColumns.add(de.metas.rfq.model.I_C_RfQ.COLUMNNAME_DateWorkStart);
}
if (pmmRfq.getDateWorkComplete() == null)
{
notFilledMandatoryColumns.add(de.metas.rfq.model.I_C_RfQ.COLUMNNAME_DateWorkComplete);
}
if (pmmRfq.getDateResponse() == null)
{
notFilledMandatoryColumns.add(de.metas.rfq.model.I_C_RfQ.COLUMNNAME_DateResponse);
}
//
if (!notFilledMandatoryColumns.isEmpty())
{
throw new FillMandatoryException(false, notFilledMandatoryColumns);
}
}
@Override
public void onAfterComplete(I_C_RfQResponse rfqResponse)
{
if (!isProcurement(rfqResponse))
{
return;
} | //
// Create and collect RfQ close events (winner unknown)
final List<SyncRfQCloseEvent> syncRfQCloseEvents = new ArrayList<>();
final SyncObjectsFactory syncObjectsFactory = SyncObjectsFactory.newFactory();
final IPMM_RfQ_DAO pmmRfqDAO = Services.get(IPMM_RfQ_DAO.class);
for (final I_C_RfQResponseLine rfqResponseLine : pmmRfqDAO.retrieveResponseLines(rfqResponse))
{
// Create and collect the RfQ close event
final boolean winnerKnown = false;
final SyncRfQCloseEvent syncRfQCloseEvent = syncObjectsFactory.createSyncRfQCloseEvent(rfqResponseLine, winnerKnown);
if (syncRfQCloseEvent != null)
{
syncRfQCloseEvents.add(syncRfQCloseEvent);
}
}
//
// Push to WebUI: RfQ close events
if (!syncRfQCloseEvents.isEmpty())
{
Services.get(ITrxManager.class)
.getTrxListenerManagerOrAutoCommit(ITrx.TRXNAME_ThreadInherited)
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerWeakly(false) // register "hard", because that's how it was before
.invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed
.registerHandlingMethod(innerTrx -> {
final IWebuiPush webuiPush = Services.get(IWebuiPush.class);
webuiPush.pushRfQCloseEvents(syncRfQCloseEvents);
});
}
};
@Override
public void onAfterClose(final I_C_RfQResponse rfqResponse)
{
if (!isProcurement(rfqResponse))
{
return;
}
Services.get(IPMM_RfQ_BL.class).createDraftContractsForSelectedWinners(rfqResponse);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\rfq\model\interceptor\PMMRfQEventListener.java | 1 |
请完成以下Java代码 | public static final ConfigurationException wrapIfNeeded(final Throwable throwable)
{
if (throwable == null)
{
return null;
}
else if (throwable instanceof ConfigurationException)
{
return (ConfigurationException)throwable;
}
final Throwable cause = extractCause(throwable);
if (cause != throwable)
{
return wrapIfNeeded(cause);
} | // default
return new ConfigurationException(cause.getLocalizedMessage(), cause);
}
/**
*
*/
private static final long serialVersionUID = -5463410167655542710L;
public ConfigurationException(String message)
{
super(message);
}
public ConfigurationException(String message, Throwable cause)
{
super(message, cause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\exceptions\ConfigurationException.java | 1 |
请完成以下Java代码 | public static class OpenViewAction implements ResultAction
{
@NonNull
ViewId viewId;
@Nullable
ViewProfileId profileId;
@Builder.Default
ProcessExecutionResult.RecordsToOpen.TargetTab targetTab = ProcessExecutionResult.RecordsToOpen.TargetTab.SAME_TAB_OVERLAY;
}
@lombok.Value
@lombok.Builder
public static class OpenIncludedViewAction implements ResultAction
{
@NonNull
ViewId viewId;
ViewProfileId profileId;
}
@lombok.Value(staticConstructor = "of")
public static class CreateAndOpenIncludedViewAction implements ResultAction
{
@NonNull
CreateViewRequest createViewRequest;
}
public static final class CloseViewAction implements ResultAction
{
public static final CloseViewAction instance = new CloseViewAction();
private CloseViewAction() {}
}
@lombok.Value
@lombok.Builder
public static class OpenSingleDocument implements ResultAction
{
@NonNull
DocumentPath documentPath;
@Builder.Default
ProcessExecutionResult.RecordsToOpen.TargetTab targetTab = ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB;
} | @lombok.Value
@lombok.Builder
public static class SelectViewRowsAction implements ResultAction
{
@NonNull ViewId viewId;
@NonNull DocumentIdsSelection rowIds;
}
@lombok.Value
@lombok.Builder
public static class DisplayQRCodeAction implements ResultAction
{
@NonNull String code;
}
@lombok.Value
@lombok.Builder
public static class NewRecordAction implements ResultAction
{
@NonNull String windowId;
@NonNull @Singular Map<String, String> fieldValues;
@NonNull @Builder.Default ProcessExecutionResult.WebuiNewRecord.TargetTab targetTab = ProcessExecutionResult.WebuiNewRecord.TargetTab.SAME_TAB;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ProcessInstanceResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String content;
@ManyToOne(fetch = FetchType.LAZY)
private User user; // The owner of the post
public Post() {
}
public Post(Long id, String title, String content, User user) {
this.id = id;
this.title = title;
this.content = content;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
} | public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
} | repos\tutorials-master\spring-security-modules\spring-security-authorization\spring-security-url-http-method-auth\src\main\java\com\baeldung\springsecurity\entity\Post.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Result info(@PathVariable("id") Integer id) {
Article article = articleService.queryObject(id);
return ResultGenerator.genSuccessResult(article);
}
/**
* 保存
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Result save(@RequestBody Article article, @TokenToUser AdminUser loginUser) {
if (article.getAddName()==null){
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "作者不能为空!");
}
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (articleService.save(article) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("添加失败");
}
}
/**
* 修改
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
public Result update(@RequestBody Article article, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (articleService.update(article) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("修改失败");
}
}
/** | * 删除
*/
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public Result delete(@RequestBody Integer[] ids, @TokenToUser AdminUser loginUser) {
if (loginUser == null) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!");
}
if (ids.length < 1) {
return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!");
}
if (articleService.deleteBatch(ids) > 0) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
} | repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\controller\ArticleController.java | 2 |
请完成以下Java代码 | private final Iterator<I_C_Doc_Outbound_Log> retrieveSelectedDocOutboundLogs()
{
final IQueryFilter<I_C_Doc_Outbound_Log> filter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
final Stream<I_C_Doc_Outbound_Log> stream = queryBL
.createQueryBuilder(I_C_Doc_Outbound_Log.class)
.addOnlyActiveRecordsFilter()
.filter(filter)
.create()
.iterateAndStream()
.filter(this::hasAttachmentToStore);
return stream.iterator();
}
private boolean hasAttachmentToStore(@NonNull final I_C_Doc_Outbound_Log docoutBoundLogRecord)
{
final List<AttachmentEntry> attachmentEntries = retrieveAllAttachments(docoutBoundLogRecord);
return attachmentEntries
.stream()
.anyMatch(this::isStorable); | }
private List<AttachmentEntry> retrieveAllAttachments(@NonNull final I_C_Doc_Outbound_Log docoutBoundLogRecord)
{
final AttachmentEntryQuery query = AttachmentEntryQuery
.builder()
.referencedRecord(docoutBoundLogRecord)
.build();
return attachmentEntryService.getByQuery(query);
}
private boolean isStorable(@NonNull final AttachmentEntry attachmentEntry)
{
return storeAttachmentService.isAttachmentStorable(attachmentEntry);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\storage\attachments\process\C_Doc_Outbound_Log_StoreAttachments.java | 1 |
请完成以下Java代码 | public String[] getTaskIds() {
return taskIds;
}
public String[] getExecutionIds() {
return executionIds;
}
public String[] getCaseExecutionIds() {
return caseExecutionIds;
}
public String[] getCaseActivityIds() {
return caseActivityIds;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public String getVariableName() {
return variableName;
}
public String getVariableNameLike() {
return variableNameLike;
}
public QueryVariableValue getQueryVariableValue() {
return queryVariableValue;
}
public Boolean getVariableNamesIgnoreCase() {
return variableNamesIgnoreCase;
} | public Boolean getVariableValuesIgnoreCase() {
return variableValuesIgnoreCase;
}
@Override
public HistoricVariableInstanceQuery includeDeleted() {
includeDeleted = true;
return this;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public List<String> getVariableNameIn() {
return variableNameIn;
}
public Date getCreatedAfter() {
return createdAfter;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricVariableInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | JacksonJsonHttpMessageConvertersCustomizer jacksonJsonHttpMessageConvertersCustomizer(JsonMapper jsonMapper) {
return new JacksonJsonHttpMessageConvertersCustomizer(jsonMapper);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(XmlMapper.class)
@ConditionalOnBean(XmlMapper.class)
protected static class JacksonXmlHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(JacksonXmlHttpMessageConverter.class)
JacksonXmlHttpMessageConvertersCustomizer jacksonXmlHttpMessageConvertersCustomizer(XmlMapper xmlMapper) {
return new JacksonXmlHttpMessageConvertersCustomizer(xmlMapper);
}
}
static class JacksonJsonHttpMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final JsonMapper jsonMapper;
JacksonJsonHttpMessageConvertersCustomizer(JsonMapper jsonMapper) {
this.jsonMapper = jsonMapper;
}
@Override
public void customize(ClientBuilder builder) {
builder.withJsonConverter(new JacksonJsonHttpMessageConverter(this.jsonMapper));
}
@Override
public void customize(ServerBuilder builder) {
builder.withJsonConverter(new JacksonJsonHttpMessageConverter(this.jsonMapper));
}
}
static class JacksonXmlHttpMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer { | private final XmlMapper xmlMapper;
JacksonXmlHttpMessageConvertersCustomizer(XmlMapper xmlMapper) {
this.xmlMapper = xmlMapper;
}
@Override
public void customize(ClientBuilder builder) {
builder.withXmlConverter(new JacksonXmlHttpMessageConverter(this.xmlMapper));
}
@Override
public void customize(ServerBuilder builder) {
builder.withXmlConverter(new JacksonXmlHttpMessageConverter(this.xmlMapper));
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\JacksonHttpMessageConvertersConfiguration.java | 2 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_GL_Budget[")
.append(get_ID()).append("]");
return sb.toString();
}
/** BudgetStatus AD_Reference_ID=178 */
public static final int BUDGETSTATUS_AD_Reference_ID=178;
/** Draft = D */
public static final String BUDGETSTATUS_Draft = "D";
/** Approved = A */
public static final String BUDGETSTATUS_Approved = "A";
/** Set Budget Status.
@param BudgetStatus
Indicates the current status of this budget
*/
public void setBudgetStatus (String BudgetStatus)
{
set_Value (COLUMNNAME_BudgetStatus, BudgetStatus);
}
/** Get Budget Status.
@return Indicates the current status of this budget
*/
public String getBudgetStatus ()
{
return (String)get_Value(COLUMNNAME_BudgetStatus);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Budget.
@param GL_Budget_ID
General Ledger Budget
*/
public void setGL_Budget_ID (int GL_Budget_ID)
{
if (GL_Budget_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Budget_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Budget_ID, Integer.valueOf(GL_Budget_ID)); | }
/** Get Budget.
@return General Ledger Budget
*/
public int getGL_Budget_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Primary.
@param IsPrimary
Indicates if this is the primary budget
*/
public void setIsPrimary (boolean IsPrimary)
{
set_Value (COLUMNNAME_IsPrimary, Boolean.valueOf(IsPrimary));
}
/** Get Primary.
@return Indicates if this is the primary budget
*/
public boolean isPrimary ()
{
Object oo = get_Value(COLUMNNAME_IsPrimary);
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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Budget.java | 1 |
请完成以下Java代码 | public void setR_RequestType(org.compiere.model.I_R_RequestType R_RequestType)
{
set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType);
}
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Nutzer-ID/Login.
@param UserName Nutzer-ID/Login */
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Nutzer-ID/Login.
@return Nutzer-ID/Login */
@Override
public java.lang.String getUserName ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java-gen\de\metas\inbound\mail\model\X_C_InboundMailConfig.java | 1 |
请完成以下Java代码 | private ITaxAccountable asTaxAccountable(final I_GL_JournalLine glJournalLine, final boolean accountSignDR)
{
final IGLJournalLineBL glJournalLineBL = Services.get(IGLJournalLineBL.class);
return glJournalLineBL.asTaxAccountable(glJournalLine, accountSignDR);
}
private boolean isAutoTaxAccount(final I_C_ValidCombination accountVC)
{
if (accountVC == null)
{
return false;
}
final I_C_ElementValue account = accountVC.getAccount();
if (account == null)
{
return false;
}
return account.isAutoTaxAccount(); | }
private boolean isAutoTax(final I_GL_JournalLine glJournalLine)
{
return glJournalLine.isDR_AutoTaxAccount() || glJournalLine.isCR_AutoTaxAccount();
}
@Nullable
private AccountConceptualName suggestAccountConceptualName(@NonNull final AccountId accountId)
{
final ElementValueId elementValueId = accountDAO.getElementValueIdByAccountId(accountId);
final ElementValue elementValue = elementValueRepository.getById(elementValueId);
return elementValue.getAccountConceptualName();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\GL_JournalLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setAttach(String attach) {
this.attach = attach;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getMchId() {
return mchId;
}
public void setMchId(String mchId) {
this.mchId = mchId;
}
public String getDeviceInfo() {
return deviceInfo;
}
public void setDeviceInfo(String deviceInfo) {
this.deviceInfo = deviceInfo;
}
public String getNonceStr() {
return nonceStr;
}
public void setNonceStr(String nonceStr) {
this.nonceStr = nonceStr;
}
public String getOutTradeNo() {
return outTradeNo;
}
public void setOutTradeNo(String outTradeNo) {
this.outTradeNo = outTradeNo;
}
public String getFeeType() {
return feeType;
}
public void setFeeType(String feeType) {
this.feeType = feeType;
}
public Integer getTotalFee() {
return totalFee;
}
public void setTotalFee(Integer totalFee) {
this.totalFee = totalFee;
}
public String getSpbillCreateIp() {
return spbillCreateIp;
}
public void setSpbillCreateIp(String spbillCreateIp) {
this.spbillCreateIp = spbillCreateIp;
}
public String getTimeStart() {
return timeStart;
}
public void setTimeStart(String timeStart) {
this.timeStart = timeStart;
}
public String getTimeExpire() {
return timeExpire; | }
public void setTimeExpire(String timeExpire) {
this.timeExpire = timeExpire;
}
public String getGoodsTag() {
return goodsTag;
}
public void setGoodsTag(String goodsTag) {
this.goodsTag = goodsTag;
}
public String getNotifyUrl() {
return notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public WeiXinTradeTypeEnum getTradeType() {
return tradeType;
}
public void setTradeType(WeiXinTradeTypeEnum tradeType) {
this.tradeType = tradeType;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getLimitPay() {
return limitPay;
}
public void setLimitPay(String limitPay) {
this.limitPay = limitPay;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\weixinpay\WeiXinPrePay.java | 2 |
请完成以下Java代码 | public PickingSlotIdAndCaption getPickingSlotNotNull()
{
if (pickingSlot == null)
{
throw new AdempiereException(MISSING_PICKING_SLOT_ID_ERROR_MSG);
}
return pickingSlot;
}
public void assertPickingSlotScanned()
{
if (pickingSlot == null)
{
throw new AdempiereException(MISSING_PICKING_SLOT_ID_ERROR_MSG);
}
}
public boolean isPickingSlotSet() {return pickingSlot != null;}
public Optional<PickingSlotIdAndCaption> getPickingSlot() {return Optional.ofNullable(pickingSlot);}
public Optional<PickingSlotId> getPickingSlotId() {return Optional.ofNullable(pickingSlot).map(PickingSlotIdAndCaption::getPickingSlotId);}
public Optional<String> getPickingSlotCaption() {return Optional.ofNullable(pickingSlot).map(PickingSlotIdAndCaption::getCaption);}
public CurrentPickingTarget withPickingSlot(@Nullable final PickingSlotIdAndCaption pickingSlot)
{
return PickingSlotIdAndCaption.equals(this.pickingSlot, pickingSlot)
? this
: toBuilder().pickingSlot(pickingSlot).build();
}
@NonNull
public Optional<LUPickingTarget> getLuPickingTarget() {return Optional.ofNullable(luPickingTarget);}
@NonNull
public CurrentPickingTarget withLuPickingTarget(@NonNull final UnaryOperator<LUPickingTarget> luPickingTargetMapper)
{
return withLuPickingTarget(luPickingTargetMapper.apply(luPickingTarget));
}
@NonNull
public CurrentPickingTarget withLuPickingTarget(final @Nullable LUPickingTarget luPickingTarget)
{
if (LUPickingTarget.equals(this.luPickingTarget, luPickingTarget))
{
return this;
}
return toBuilder()
.luPickingTarget(luPickingTarget) | .tuPickingTarget(luPickingTarget == null ? null : this.tuPickingTarget)
.build();
}
public CurrentPickingTarget withClosedLUAndTUPickingTarget(@Nullable final LUIdsAndTopLevelTUIdsCollector closedHuIdCollector)
{
// already closed
if (this.luPickingTarget == null && this.tuPickingTarget == null)
{
return this;
}
if (closedHuIdCollector != null)
{
if (luPickingTarget == null || luPickingTarget.isNewLU())
{
// collect only top level TUs i.e. no LUs
if (tuPickingTarget != null && tuPickingTarget.isExistingTU())
{
closedHuIdCollector.addTopLevelTUId(tuPickingTarget.getTuIdNotNull());
}
}
else if (luPickingTarget.isExistingLU())
{
closedHuIdCollector.addLUId(luPickingTarget.getLuIdNotNull());
}
}
return toBuilder()
.luPickingTarget(null)
.tuPickingTarget(null)
.build();
}
@NonNull
public Optional<TUPickingTarget> getTuPickingTarget() {return Optional.ofNullable(tuPickingTarget);}
@NonNull
public CurrentPickingTarget withTuPickingTarget(@Nullable final TUPickingTarget tuPickingTarget)
{
return TUPickingTarget.equals(this.tuPickingTarget, tuPickingTarget)
? this
: toBuilder().tuPickingTarget(tuPickingTarget).build();
}
public boolean matches(@NonNull final HuId huId)
{
return luPickingTarget != null && HuId.equals(luPickingTarget.getLuId(), huId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\CurrentPickingTarget.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void bulkUpdateJobLockWithoutRevisionCheck(List<ExternalWorkerJobEntity> externalWorkerJobs, String lockOwner, Date lockExpirationTime) {
Map<String, Object> params = new HashMap<>(3);
params.put("lockOwner", lockOwner);
params.put("lockExpirationTime", lockExpirationTime);
bulkUpdateEntities("updateExternalWorkerJobLocks", params, "externalWorkerJobs", externalWorkerJobs);
}
@Override
public void resetExpiredJob(String jobId) {
Map<String, Object> params = new HashMap<>(2);
params.put("id", jobId);
params.put("now", jobServiceConfiguration.getClock().getCurrentTime());
getDbSqlSession().directUpdate("resetExpiredExternalWorkerJob", params);
}
@Override
public void deleteJobsByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
deleteCachedEntities(dbSqlSession, jobsByExecutionIdMatcher, executionId);
} else {
bulkDelete("deleteExternalWorkerJobsByExecutionId", jobsByExecutionIdMatcher, executionId);
}
}
@Override
@SuppressWarnings("unchecked")
public List<ExternalWorkerJobEntity> findExternalJobsToExecute(ExternalWorkerJobAcquireBuilderImpl builder, int numberOfJobs) {
return getDbSqlSession().selectList("selectExternalWorkerJobsToExecute", builder, new Page(0, numberOfJobs));
}
@Override
public List<ExternalWorkerJobEntity> findJobsByScopeIdAndSubScopeId(String scopeId, String subScopeId) {
Map<String, String> paramMap = new HashMap<>();
paramMap.put("scopeId", scopeId); | paramMap.put("subScopeId", subScopeId);
return getList(getDbSqlSession(), "selectExternalWorkerJobsByScopeIdAndSubScopeId", paramMap, externalWorkerJobsByScopeIdAndSubScopeIdMatcher, true);
}
@Override
public List<ExternalWorkerJobEntity> findJobsByWorkerId(String workerId) {
return getList("selectExternalWorkerJobsByWorkerId", workerId);
}
@Override
public List<ExternalWorkerJobEntity> findJobsByWorkerIdAndTenantId(String workerId, String tenantId) {
Map<String, String> paramMap = new HashMap<>();
paramMap.put("workerId", workerId);
paramMap.put("tenantId", tenantId);
return getList("selectExternalWorkerJobsByWorkerIdAndTenantId", paramMap);
}
@Override
protected IdGenerator getIdGenerator() {
return jobServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisExternalWorkerJobDataManager.java | 2 |
请完成以下Java代码 | public int getW_Inventory_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Inventory_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getW_Revaluation_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_W_Revaluation_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setW_Revaluation_A(org.compiere.model.I_C_ValidCombination W_Revaluation_A)
{
set_ValueFromPO(COLUMNNAME_W_Revaluation_Acct, org.compiere.model.I_C_ValidCombination.class, W_Revaluation_A);
}
/** Set Lager Wert Korrektur Währungsdifferenz.
@param W_Revaluation_Acct
Konto für Lager Wert Korrektur Währungsdifferenz
*/
@Override
public void setW_Revaluation_Acct (int W_Revaluation_Acct)
{
set_Value (COLUMNNAME_W_Revaluation_Acct, Integer.valueOf(W_Revaluation_Acct));
}
/** Get Lager Wert Korrektur Währungsdifferenz.
@return Konto für Lager Wert Korrektur Währungsdifferenz
*/
@Override
public int getW_Revaluation_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Revaluation_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getWithholding_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Withholding_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setWithholding_A(org.compiere.model.I_C_ValidCombination Withholding_A)
{
set_ValueFromPO(COLUMNNAME_Withholding_Acct, org.compiere.model.I_C_ValidCombination.class, Withholding_A);
}
/** Set Einbehalt.
@param Withholding_Acct
Account for Withholdings
*/
@Override
public void setWithholding_Acct (int Withholding_Acct)
{
set_Value (COLUMNNAME_Withholding_Acct, Integer.valueOf(Withholding_Acct));
}
/** Get Einbehalt.
@return Account for Withholdings
*/ | @Override
public int getWithholding_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Withholding_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getWriteOff_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setWriteOff_A(org.compiere.model.I_C_ValidCombination WriteOff_A)
{
set_ValueFromPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, WriteOff_A);
}
/** Set Forderungsverluste.
@param WriteOff_Acct
Konto für Forderungsverluste
*/
@Override
public void setWriteOff_Acct (int WriteOff_Acct)
{
set_Value (COLUMNNAME_WriteOff_Acct, Integer.valueOf(WriteOff_Acct));
}
/** Get Forderungsverluste.
@return Konto für Forderungsverluste
*/
@Override
public int getWriteOff_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WriteOff_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_Default.java | 1 |
请完成以下Java代码 | public void setPP_Order(final 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 (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public void setPP_Order_IssueSchedule_ID (final int PP_Order_IssueSchedule_ID)
{
if (PP_Order_IssueSchedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_IssueSchedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_IssueSchedule_ID, PP_Order_IssueSchedule_ID);
}
@Override
public int getPP_Order_IssueSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_IssueSchedule_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyIssued (final BigDecimal QtyIssued)
{
set_Value (COLUMNNAME_QtyIssued, QtyIssued);
}
@Override
public BigDecimal getQtyIssued()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyIssued);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReject (final @Nullable BigDecimal QtyReject)
{
set_Value (COLUMNNAME_QtyReject, QtyReject);
} | @Override
public BigDecimal getQtyReject()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReject);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToIssue (final BigDecimal QtyToIssue)
{
set_ValueNoCheck (COLUMNNAME_QtyToIssue, QtyToIssue);
}
@Override
public BigDecimal getQtyToIssue()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToIssue);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_ValueNoCheck (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_PP_Order_IssueSchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
} | public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidOneConfig.java | 2 |
请完成以下Java代码 | public <T> ICompositeQueryUpdater<T> createCompositeQueryUpdater(final Class<T> modelClass)
{
return new CompositeQueryUpdater<>();
}
@Override
public <T> String debugAccept(final IQueryFilter<T> filter, final T model)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n-------------------------------------------------------------------------------");
sb.append("\nModel: " + model);
final List<IQueryFilter<T>> filters = extractAllFilters(filter);
for (final IQueryFilter<T> f : filters)
{
final boolean accept = f.accept(model);
sb.append("\nFilter(accept=" + accept + "): " + f);
}
sb.append("\n-------------------------------------------------------------------------------");
return sb.toString();
}
private <T> List<IQueryFilter<T>> extractAllFilters(@Nullable final IQueryFilter<T> filter)
{
if (filter == null)
{
return Collections.emptyList();
}
final List<IQueryFilter<T>> result = new ArrayList<>();
result.add(filter);
if (filter instanceof ICompositeQueryFilter)
{
final ICompositeQueryFilter<T> compositeFilter = (ICompositeQueryFilter<T>)filter;
for (final IQueryFilter<T> f : compositeFilter.getFilters())
{
final List<IQueryFilter<T>> resultLocal = extractAllFilters(f); | result.addAll(resultLocal);
}
}
return result;
}
@Override
public <T> QueryResultPage<T> retrieveNextPage(
@NonNull final Class<T> clazz,
@NonNull final String next)
{
if (Adempiere.isUnitTestMode())
{
return POJOQuery.getPage(clazz, next);
}
return SpringContextHolder.instance
.getBean(PaginationService.class)
.loadPage(clazz, next);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBL.java | 1 |
请完成以下Java代码 | public B authorizationGrantType(AuthorizationGrantType authorizationGrantType) {
return put(AuthorizationGrantType.class, authorizationGrantType);
}
/**
* Sets the {@link Authentication} representing the authorization grant.
* @param authorizationGrant the {@link Authentication} representing the
* authorization grant
* @return the {@link AbstractBuilder} for further configuration
*/
public B authorizationGrant(Authentication authorizationGrant) {
return put(AUTHORIZATION_GRANT_AUTHENTICATION_KEY, authorizationGrant);
}
/**
* Associates an attribute.
* @param key the key for the attribute
* @param value the value of the attribute
* @return the {@link AbstractBuilder} for further configuration
*/
public B put(Object key, Object value) {
Assert.notNull(key, "key cannot be null");
Assert.notNull(value, "value cannot be null");
this.context.put(key, value);
return getThis();
}
/**
* A {@code Consumer} of the attributes {@code Map} allowing the ability to add,
* replace, or remove.
* @param contextConsumer a {@link Consumer} of the attributes {@code Map}
* @return the {@link AbstractBuilder} for further configuration
*/
public B context(Consumer<Map<Object, Object>> contextConsumer) {
contextConsumer.accept(this.context);
return getThis();
}
@SuppressWarnings("unchecked") | protected <V> V get(Object key) {
return (V) this.context.get(key);
}
protected Map<Object, Object> getContext() {
return this.context;
}
@SuppressWarnings("unchecked")
protected final B getThis() {
return (B) this;
}
/**
* Builds a new {@link OAuth2TokenContext}.
* @return the {@link OAuth2TokenContext}
*/
public abstract T build();
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenContext.java | 1 |
请完成以下Java代码 | public class DeptrackApiServerServiceResource extends CRUDKubernetesDependentResource<Service, DeptrackResource> {
public static final String COMPONENT = "api-server-service";
private Service template;
public DeptrackApiServerServiceResource() {
super(Service.class);
this.template = BuilderHelper.loadTemplate(Service.class, "templates/api-server-service.yaml");
}
@Override
protected Service desired(DeptrackResource primary, Context<DeptrackResource> context) {
ObjectMeta meta = fromPrimary(primary,COMPONENT)
.build();
Map<String, String> selector = new HashMap<>(meta.getLabels());
selector.put("component", DeptrackApiServerDeploymentResource.COMPONENT); | return new ServiceBuilder(template)
.withMetadata(meta)
.editSpec()
.withSelector(selector)
.endSpec()
.build();
}
static class Discriminator extends ResourceIDMatcherDiscriminator<Service,DeptrackResource> {
public Discriminator() {
super(COMPONENT, (p) -> new ResourceID(p.getMetadata().getName() + "-" + COMPONENT,p.getMetadata().getNamespace()));
}
}
} | repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackApiServerServiceResource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | ReactiveClientRegistrationRepository clientRegistrations(
@Value("${spring.security.oauth2.client.provider.bael.token-uri}") String token_uri,
@Value("${spring.security.oauth2.client.registration.bael.client-id}") String client_id,
@Value("${spring.security.oauth2.client.registration.bael.client-secret}") String client_secret,
@Value("${spring.security.oauth2.client.registration.bael.authorization-grant-type}") String authorizationGrantType
) {
ClientRegistration registration = ClientRegistration
.withRegistrationId("keycloak")
.tokenUri(token_uri)
.clientId(client_id)
.clientSecret(client_secret)
.authorizationGrantType(new AuthorizationGrantType(authorizationGrantType))
.build();
return new InMemoryReactiveClientRegistrationRepository(registration);
}
@Bean
public AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
InMemoryReactiveOAuth2AuthorizedClientService clientService =
new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build();
AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = | new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, clientService);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
@Bean
WebClient webClient(AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager auth2AuthorizedClientManager) {
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(auth2AuthorizedClientManager);
oauth2Client.setDefaultClientRegistrationId("bael");
return WebClient.builder()
.filter(oauth2Client)
.build();
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-oauth\src\main\java\com\baeldung\webclient\clientcredentials\configuration\WebClientConfig.java | 2 |
请完成以下Java代码 | public static ObjectNode fillLoggingData(String message, String scopeId, String subScopeId, String scopeType, ObjectMapper objectMapper) {
ObjectNode loggingNode = objectMapper.createObjectNode();
loggingNode.put("message", message);
loggingNode.put("scopeId", scopeId);
if (StringUtils.isNotEmpty(subScopeId)) {
loggingNode.put("subScopeId", subScopeId);
}
loggingNode.put("scopeType", scopeType);
return loggingNode;
}
public static String formatDate(Date date) {
if (date != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
dateFormat.setTimeZone(utcTimeZone); | return dateFormat.format(date);
}
return null;
}
public static String formatDate(DateTime date) {
if (date != null) {
return date.toString("yyyy-MM-dd'T'hh:mm:ss.sss'Z'");
}
return null;
}
public static String formatDate(LocalDate date) {
if (date != null) {
return date.toString("yyyy-MM-dd");
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\logging\LoggingSessionUtil.java | 1 |
请完成以下Java代码 | public final boolean hasColumnName(final String columnName)
{
final GridField gridField = getGridTab().getField(columnName);
return gridField != null;
}
public static int getId(Object model)
{
return getGridTab(model).getRecord_ID();
}
public static boolean isNew(Object model)
{
return getGridTab(model).getRecord_ID() <= 0;
}
public <T> T getDynAttribute(final String attributeName)
{
if (recordId2dynAttributes == null)
{
return null;
}
final int recordId = getGridTab().getRecord_ID();
final Map<String, Object> dynAttributes = recordId2dynAttributes.get(recordId);
// Cleanup old entries to avoid weird cases
// e.g. dynattributes shall be destroyed when user is switching to another record
removeOldDynAttributesEntries(recordId);
if (dynAttributes == null)
{
return null;
}
@SuppressWarnings("unchecked")
final T value = (T)dynAttributes.get(attributeName);
return value;
}
public Object setDynAttribute(final String attributeName, final Object value)
{
Check.assumeNotEmpty(attributeName, "attributeName not empty");
final int recordId = getGridTab().getRecord_ID();
Map<String, Object> dynAttributes = recordId2dynAttributes.get(recordId);
if (dynAttributes == null)
{
dynAttributes = new HashMap<>();
recordId2dynAttributes.put(recordId, dynAttributes);
}
final Object valueOld = dynAttributes.put(attributeName, value); | // Cleanup old entries because in most of the cases we won't use them
removeOldDynAttributesEntries(recordId);
//
// return the old value
return valueOld;
}
private void removeOldDynAttributesEntries(final int recordIdToKeep)
{
for (final Iterator<Integer> recordIds = recordId2dynAttributes.keySet().iterator(); recordIds.hasNext();)
{
final Integer dynAttribute_recordId = recordIds.next();
if (dynAttribute_recordId != null && dynAttribute_recordId == recordIdToKeep)
{
continue;
}
recordIds.remove();
}
}
public final IModelInternalAccessor getModelInternalAccessor()
{
return modelInternalAccessorSupplier.get();
}
public final boolean isOldValues()
{
return useOldValues;
}
public static final boolean isOldValues(final Object model)
{
final GridTabWrapper wrapper = getWrapper(model);
return wrapper == null ? false : wrapper.isOldValues();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GridTabWrapper.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
System.out.println(executeJarWithoutManifestAttribute());
System.out.println(executeJarWithManifestAttribute());
}
public static String executeJarWithoutManifestAttribute() {
return executeJar(CREATE_JAR_WITHOUT_MF_ATT_COMMAND);
}
public static String executeJarWithoutManifestAttributeWithCPOption() {
return executeJar(CREATE_JAR_WITHOUT_MF_WITH_CP_OPTION);
}
public static String executeJarWithoutManifestAttributeWithClasspathOption() {
return executeJar(CREATE_JAR_WITHOUT_MF_WITH_CLASSPATH_OPTION);
}
public static String executeJarWithManifestAttribute() {
createManifestFile();
return executeJar(CREATE_JAR_WITH_MF_ATT_COMMAND);
}
private static void createManifestFile() {
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter(MANIFEST_MF_PATH));
writer.write(MAIN_MANIFEST_ATTRIBUTE);
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String executeJar(String createJarCommand) {
executeCommand(COMPILE_COMMAND); | executeCommand(createJarCommand);
return executeCommand(EXECUTE_JAR_COMMAND);
}
private static String executeCommand(String command) {
String output = null;
try {
output = collectOutput(runProcess(command));
} catch (Exception ex) {
System.out.println(ex);
}
return output;
}
private static String collectOutput(Process process) throws IOException {
StringBuffer output = new StringBuffer();
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = outputReader.readLine()) != null) {
output.append(line + "\n");
}
return output.toString();
}
private static Process runProcess(String command) throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(command.split(DELIMITER));
builder.directory(new File(WORK_PATH).getAbsoluteFile());
builder.redirectErrorStream(true);
Process process = builder.start();
process.waitFor();
return process;
}
} | repos\tutorials-master\core-java-modules\core-java-jar\src\main\java\com\baeldung\manifest\ExecuteJarFile.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebConfig implements WebMvcConfigurer
{
public static final String ENDPOINT_ROOT = "/rest/api";
@Bean
public CookieSerializer cookieSerializer()
{
final DefaultCookieSerializer serializer = new DefaultCookieSerializer();
final WebuiURLs webuiURLs = WebuiURLs.newInstance();
if (webuiURLs.isCrossSiteUsageAllowed())
{
serializer.setSameSite("None");
serializer.setUseSecureCookie(true);
}
return serializer;
}
@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer)
{
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
@Override
public void extendMessageConverters(final List<HttpMessageConverter<?>> converters)
{
// prevent errors on serializing de.metas.ui.web.config.WebuiExceptionHandler#getErrorAttributes
final MediaType javascriptMediaType = MediaType.valueOf("application/javascript");
for (final HttpMessageConverter<?> converter : converters)
{
if (converter instanceof MappingJackson2HttpMessageConverter)
{
final MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
if (jacksonConverter.getSupportedMediaTypes().contains(javascriptMediaType))
{
break;
}
final List<MediaType> supportedMediaTypes = new ArrayList<>(jacksonConverter.getSupportedMediaTypes());
supportedMediaTypes.add(javascriptMediaType);
jacksonConverter.setSupportedMediaTypes(supportedMediaTypes);
break;
}
}
} | @Bean
public Filter corsFilter()
{
return new CORSFilter();
}
@Bean
public Filter addMissingHeadersFilter()
{
return new Filter()
{
@Override
public void init(final FilterConfig filterConfig)
{
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException
{
try
{
chain.doFilter(request, response);
}
finally
{
if (response instanceof HttpServletResponse)
{
final HttpServletResponse httpResponse = (HttpServletResponse)response;
//
// If the Cache-Control is not set then set it to no-cache.
// In this way we precisely tell to browser that it shall not cache our REST calls.
// The Cache-Control is usually defined by features like ETag
if (!httpResponse.containsHeader("Cache-Control"))
{
httpResponse.setHeader("Cache-Control", "no-cache");
}
}
}
}
@Override
public void destroy()
{
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\WebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ProductsServicesFacade
{
private final IProductDAO productsRepo = Services.get(IProductDAO.class);
private final IUOMDAO uomsRepo = Services.get(IUOMDAO.class);
private final IBPartnerProductDAO partnerProductsRepo = Services.get(IBPartnerProductDAO.class);
public Stream<I_M_Product> streamAllProducts()
{
return productsRepo.streamAllProducts(Instant.ofEpochMilli(0));
}
public String getUOMSymbol(@NonNull final UomId uomId)
{
final I_C_UOM uom = uomsRepo.getById(uomId);
return uom.getUOMSymbol();
}
public List<I_C_BPartner_Product> getBPartnerProductRecords(Set<ProductId> productIds)
{
return partnerProductsRepo.retrieveForProductIds(productIds);
}
public JsonCreatedUpdatedInfo extractCreatedUpdatedInfo(final I_M_Product record)
{
return JsonCreatedUpdatedInfo.builder()
.created(TimeUtil.asZonedDateTime(record.getCreated()))
.createdBy(UserId.optionalOfRepoId(record.getCreatedBy()).orElse(UserId.SYSTEM))
.updated(TimeUtil.asZonedDateTime(record.getUpdated()))
.updatedBy(UserId.optionalOfRepoId(record.getUpdatedBy()).orElse(UserId.SYSTEM))
.build(); | }
public Stream<I_M_Product_Category> streamAllProductCategories()
{
return productsRepo.streamAllProductCategories();
}
public JsonCreatedUpdatedInfo extractCreatedUpdatedInfo(final I_M_Product_Category record)
{
return JsonCreatedUpdatedInfo.builder()
.created(TimeUtil.asZonedDateTime(record.getCreated()))
.createdBy(UserId.optionalOfRepoId(record.getCreatedBy()).orElse(UserId.SYSTEM))
.updated(TimeUtil.asZonedDateTime(record.getUpdated()))
.updatedBy(UserId.optionalOfRepoId(record.getUpdatedBy()).orElse(UserId.SYSTEM))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\product\ProductsServicesFacade.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String storeFile(MultipartFile file) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if(fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
// Copy file to the target location (Replacing existing file with the same name)
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex); | }
}
public Resource loadFileAsResource(String fileName) {
try {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if(resource.exists()) {
return resource;
} else {
throw new FileNotFoundException("File not found " + fileName);
}
} catch (MalformedURLException ex) {
throw new FileNotFoundException("File not found " + fileName, ex);
}
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-upload-download-file-rest-api-example\src\main\java\net\alanbinu\springboot\fileuploaddownload\service\FileStorageService.java | 2 |
请完成以下Java代码 | public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) {
try {
LOGGER.info("Initializing flowable-cmmn-cdi.");
// initialize the cmmn engine
lookupCmmnEngine(beanManager);
} catch (Exception e) {
// interpret cmmn engine initialization problems as definition errors
event.addDeploymentProblem(e);
}
}
protected CmmnEngine lookupCmmnEngine(BeanManager beanManager) {
ServiceLoader<CmmnEngineLookup> cmmnEngineServiceLoader = ServiceLoader.load(CmmnEngineLookup.class);
Iterator<CmmnEngineLookup> serviceIterator = cmmnEngineServiceLoader.iterator();
List<CmmnEngineLookup> discoveredLookups = new ArrayList<>();
while (serviceIterator.hasNext()) {
CmmnEngineLookup serviceInstance = serviceIterator.next();
discoveredLookups.add(serviceInstance);
}
Collections.sort(discoveredLookups, new Comparator<CmmnEngineLookup>() {
@Override
public int compare(CmmnEngineLookup o1, CmmnEngineLookup o2) {
return (-1) * ((Integer) o1.getPrecedence()).compareTo(o2.getPrecedence());
}
});
CmmnEngine cmmnEngine = null;
for (CmmnEngineLookup cmmnEngineLookup : discoveredLookups) {
cmmnEngine = cmmnEngineLookup.getCmmnEngine();
if (cmmnEngine != null) {
this.cmmnEngineLookup = cmmnEngineLookup;
LOGGER.debug("CmmnEngineLookup service {} returned cmmn engine.", cmmnEngineLookup.getClass());
break;
} else {
LOGGER.debug("CmmnEngineLookup service {} returned 'null' value.", cmmnEngineLookup.getClass());
}
}
if (cmmnEngineLookup == null) {
throw new FlowableException( | "Could not find an implementation of the " + CmmnEngineLookup.class.getName() + " service returning a non-null cmmnEngine. Giving up.");
}
Bean<FlowableCmmnServices> flowableCmmnServicesBean = (Bean<FlowableCmmnServices>) beanManager.getBeans(FlowableCmmnServices.class).stream()
.findAny()
.orElseThrow(
() -> new IllegalStateException("CDI BeanManager cannot find an instance of requested type " + FlowableCmmnServices.class.getName()));
FlowableCmmnServices services = (FlowableCmmnServices) beanManager
.getReference(flowableCmmnServicesBean, FlowableCmmnServices.class, beanManager.createCreationalContext(flowableCmmnServicesBean));
services.setCmmnEngine(cmmnEngine);
return cmmnEngine;
}
public void beforeShutdown(@Observes BeforeShutdown event) {
if (cmmnEngineLookup != null) {
cmmnEngineLookup.ungetCmmnEngine();
cmmnEngineLookup = null;
}
LOGGER.info("Shutting down flowable-cmmn-cdi");
}
} | repos\flowable-engine-main\modules\flowable-cmmn-cdi\src\main\java\org\flowable\cdi\impl\FlowableCmmnExtension.java | 1 |
请完成以下Java代码 | public void setC_DunningLevel_ID (int C_DunningLevel_ID)
{
if (C_DunningLevel_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DunningLevel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DunningLevel_ID, Integer.valueOf(C_DunningLevel_ID));
}
/** Get Mahnstufe.
@return Mahnstufe */
@Override
public int getC_DunningLevel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningLevel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Notiz.
@param Note
Optional weitere Information
*/
@Override
public void setNote (java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Notiz.
@return Optional weitere Information
*/
@Override
public java.lang.String getNote ()
{
return (java.lang.String)get_Value(COLUMNNAME_Note);
}
/** 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;
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
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 Aussendienst.
@return Aussendienst */
@Override
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.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line.java | 1 |
请完成以下Java代码 | public void setIsDepreciated (boolean IsDepreciated)
{
set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated));
}
/** Get Depreciate.
@return The asset will be depreciated
*/
public boolean isDepreciated ()
{
Object oo = get_Value(COLUMNNAME_IsDepreciated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** PostingType AD_Reference_ID=125 */
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";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType () | {
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Workfile.java | 1 |
请完成以下Java代码 | protected void createDefaultTaskScheduler() {
threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(1);
threadPoolTaskScheduler.setThreadNamePrefix("flowable-event-change-detector-");
taskScheduler = threadPoolTaskScheduler;
}
@Override
public void initialize() {
if (threadPoolTaskScheduler != null) {
threadPoolTaskScheduler.initialize();
}
Instant initialInstant = Instant.now().plus(initialDelay);
taskScheduler.scheduleWithFixedDelay(createChangeDetectionRunnable(), initialInstant, delay);
}
protected Runnable createChangeDetectionRunnable() {
return new EventRegistryChangeDetectionRunnable(eventRegistryChangeDetectionManager);
}
@Override
public void shutdown() {
destroy();
}
@Override
public void destroy() {
if (threadPoolTaskScheduler != null) {
threadPoolTaskScheduler.destroy();
}
} | public EventRegistryChangeDetectionManager getEventRegistryChangeDetectionManager() {
return eventRegistryChangeDetectionManager;
}
@Override
public void setEventRegistryChangeDetectionManager(EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager) {
this.eventRegistryChangeDetectionManager = eventRegistryChangeDetectionManager;
}
public TaskScheduler getTaskScheduler() {
return taskScheduler;
}
public void setTaskScheduler(TaskScheduler taskScheduler) {
this.taskScheduler = taskScheduler;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\management\DefaultSpringEventRegistryChangeDetectionExecutor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MybatisPlusConfig {
@Autowired
DruidProperties druidProperties;
@Autowired
MutiDataSourceProperties mutiDataSourceProperties;
/**
* 核心数据源
*/
private DruidDataSource coreDataSource() {
DruidDataSource dataSource = new DruidDataSource();
druidProperties.config(dataSource);
return dataSource;
}
/**
* 另一个数据源
*/
private DruidDataSource bizDataSource() {
DruidDataSource dataSource = new DruidDataSource();
druidProperties.config(dataSource);
mutiDataSourceProperties.config(dataSource);
return dataSource;
}
/**
* 单数据源连接池配置
*/
@Bean
@ConditionalOnProperty(prefix = "xncoding", name = "muti-datasource-open", havingValue = "false")
public DruidDataSource singleDatasource() {
return coreDataSource();
}
/**
* 多数据源连接池配置
*/
@Bean
@ConditionalOnProperty(prefix = "xncoding", name = "muti-datasource-open", havingValue = "true")
public DynamicDataSource mutiDataSource() {
DruidDataSource coreDataSource = coreDataSource();
DruidDataSource bizDataSource = bizDataSource();
try {
coreDataSource.init(); | bizDataSource.init();
} catch (SQLException sql) {
sql.printStackTrace();
}
DynamicDataSource dynamicDataSource = new DynamicDataSource();
HashMap<Object, Object> hashMap = new HashMap<>();
hashMap.put(DSEnum.DATA_SOURCE_CORE, coreDataSource);
hashMap.put(DSEnum.DATA_SOURCE_BIZ, bizDataSource);
dynamicDataSource.setTargetDataSources(hashMap);
dynamicDataSource.setDefaultTargetDataSource(coreDataSource);
return dynamicDataSource;
}
/**
* mybatis-plus分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
} | repos\SpringBootBucket-master\springboot-multisource\src\main\java\com\xncoding\pos\config\MybatisPlusConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setMilestone_DueDate (final @Nullable java.sql.Timestamp Milestone_DueDate)
{
set_Value (COLUMNNAME_Milestone_DueDate, Milestone_DueDate);
}
@Override
public java.sql.Timestamp getMilestone_DueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_Milestone_DueDate);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed() | {
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setS_Milestone_ID (final int S_Milestone_ID)
{
if (S_Milestone_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, S_Milestone_ID);
}
@Override
public int getS_Milestone_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Milestone_ID);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Milestone.java | 2 |
请完成以下Java代码 | public SetRemovalTimeToHistoricDecisionInstancesBuilder hierarchical() {
isHierarchical = true;
return this;
}
public Batch executeAsync() {
return commandExecutor.execute(new SetRemovalTimeToHistoricDecisionInstancesCmd(this));
}
public HistoricDecisionInstanceQuery getQuery() {
return query;
}
public List<String> getIds() {
return ids;
}
public Date getRemovalTime() {
return removalTime; | }
public Mode getMode() {
return mode;
}
public enum Mode {
CALCULATED_REMOVAL_TIME,
ABSOLUTE_REMOVAL_TIME,
CLEARED_REMOVAL_TIME;
}
public boolean isHierarchical() {
return isHierarchical;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricDecisionInstancesBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class DefaultTbAiModelService extends AbstractTbEntityService implements TbAiModelService {
private final AiModelService aiModelService;
@Override
public AiModel save(AiModel model, User user) {
var actionType = model.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
var tenantId = user.getTenantId();
model.setTenantId(tenantId);
AiModel savedModel;
try {
savedModel = aiModelService.save(model);
autoCommit(user, savedModel.getId());
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, requireNonNullElseGet(model.getId(), () -> emptyId(EntityType.AI_MODEL)), model, actionType, user, e);
throw e;
}
logEntityActionService.logEntityAction(tenantId, savedModel.getId(), savedModel, actionType, user);
return savedModel;
} | @Override
public boolean delete(AiModel model, User user) {
var actionType = ActionType.DELETED;
var tenantId = user.getTenantId();
var modelId = model.getId();
boolean deleted;
try {
deleted = aiModelService.deleteByTenantIdAndId(tenantId, modelId);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, modelId, model, actionType, user, e, modelId.toString());
throw e;
}
if (deleted) {
logEntityActionService.logEntityAction(tenantId, modelId, model, actionType, user, modelId.toString());
}
return deleted;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\ai\DefaultTbAiModelService.java | 2 |
请完成以下Java代码 | public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) {
this.processDefinitionKeyIn = processDefinitionKeyIn;
}
@CamundaQueryParam(value = "tenantIdIn", converter = StringArrayConverter.class)
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
@CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class)
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
@CamundaQueryParam(value = "compact", converter = BooleanConverter.class)
public void setCompact(Boolean compact) {
this.compact = compact;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected CleanableHistoricProcessInstanceReport createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createCleanableHistoricProcessInstanceReport();
}
@Override
protected void applyFilters(CleanableHistoricProcessInstanceReport query) { | if (processDefinitionIdIn != null && processDefinitionIdIn.length > 0) {
query.processDefinitionIdIn(processDefinitionIdIn);
}
if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) {
query.processDefinitionKeyIn(processDefinitionKeyIn);
}
if (Boolean.TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (tenantIdIn != null && tenantIdIn.length > 0) {
query.tenantIdIn(tenantIdIn);
}
if (Boolean.TRUE.equals(compact)) {
query.compact();
}
}
@Override
protected void applySortBy(CleanableHistoricProcessInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_FINISHED_VALUE)) {
query.orderByFinished();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricProcessInstanceReportDto.java | 1 |
请完成以下Java代码 | public List<VariableInstance> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
ensureVariablesInitialized();
List<VariableInstance> result = commandContext
.getVariableInstanceManager()
.findVariableInstanceByQueryCriteria(this, page);
if (result == null) {
return result;
}
// iterate over the result array to initialize the value and serialized value of the variable
for (VariableInstance variableInstance : result) {
VariableInstanceEntity variableInstanceEntity = (VariableInstanceEntity) variableInstance;
if (shouldFetchValue(variableInstanceEntity)) {
try {
variableInstanceEntity.getTypedValue(isCustomObjectDeserializationEnabled);
} catch(Exception t) {
// do not fail if one of the variables fails to load
LOG.exceptionWhileGettingValueForVariable(t);
}
}
}
return result;
}
protected boolean shouldFetchValue(VariableInstanceEntity entity) {
// do not fetch values for byte arrays eagerly (unless requested by the user)
return isByteArrayFetchingEnabled
|| !AbstractTypedValueSerializer.BINARY_VALUE_TYPES.contains(entity.getSerializer().getType().getName());
}
// getters ////////////////////////////////////////////////////
public String getVariableId() {
return variableId;
}
public String getVariableName() {
return variableName;
} | public String[] getVariableNames() {
return variableNames;
}
public String getVariableNameLike() {
return variableNameLike;
}
public String[] getExecutionIds() {
return executionIds;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public String[] getCaseExecutionIds() {
return caseExecutionIds;
}
public String[] getCaseInstanceIds() {
return caseInstanceIds;
}
public String[] getTaskIds() {
return taskIds;
}
public String[] getBatchIds() {
return batchIds;
}
public String[] getVariableScopeIds() {
return variableScopeIds;
}
public String[] getActivityInstanceIds() {
return activityInstanceIds;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\VariableInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode() {
return Objects.hash(_id, customerId, type, isLegalCarer, gender, title, firstName, lastName, address, postalCode, city, phone, mobilePhone, fax, email, archived, timestamp);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CareGiver {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" isLegalCarer: ").append(toIndentedString(isLegalCarer)).append("\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n"); | sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" mobilePhone: ").append(toIndentedString(mobilePhone)).append("\n");
sb.append(" fax: ").append(toIndentedString(fax)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\CareGiver.java | 2 |
请完成以下Java代码 | public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public Entry next() {
Map.Entry<Object, Object> entry = this.iterator.next();
return new Entry((String) entry.getKey(), (String) entry.getValue());
}
@Override
public void remove() {
throw new UnsupportedOperationException("InfoProperties are immutable.");
}
}
/**
* Property entry.
*/
public static final class Entry {
private final String key;
private final String value; | private Entry(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return this.key;
}
public String getValue() {
return this.value;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\InfoProperties.java | 1 |
请完成以下Java代码 | public class PurposeSEPA {
@XmlElement(name = "Cd", required = true)
protected String cd;
/**
* Gets the value of the cd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCd() {
return cd; | }
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PurposeSEPA.java | 1 |
请完成以下Java代码 | public void assertInTransit()
{
assertNotDroppedTo();
assertPickedFrom();
}
public void removePickedHUs()
{
this.pickedHUs = null;
this.qtyNotPickedReason = null;
updateStatus();
}
public void markAsPickedFrom(
@Nullable final QtyRejectedReasonCode qtyNotPickedReason,
@NonNull final DDOrderMoveSchedulePickedHUs pickedHUs)
{
assertNotPickedFrom();
final Quantity qtyPicked = pickedHUs.getQtyPicked();
Quantity.assertSameUOM(this.qtyToPick, qtyPicked);
if (qtyPicked.signum() <= 0)
{
throw new AdempiereException("QtyPicked must be greater than zero");
}
if (!this.qtyToPick.qtyAndUomCompareToEquals(qtyPicked))
{
if (qtyNotPickedReason == null)
{
throw new AdempiereException("Reason must be provided when not picking the whole scheduled qty");
}
this.qtyNotPickedReason = qtyNotPickedReason;
}
else
{
this.qtyNotPickedReason = null;
}
this.pickedHUs = pickedHUs;
updateStatus();
}
public boolean isDropTo()
{
return pickedHUs != null && pickedHUs.isDroppedTo();
}
public void assertNotDroppedTo()
{
if (isDropTo())
{
throw new AdempiereException("Already Dropped To");
}
}
public void markAsDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId)
{
assertInTransit();
final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this);
pickedHUs.setDroppedTo(dropToLocatorId, dropToMovementId);
updateStatus(); | }
private void updateStatus()
{
this.status = computeStatus();
}
private DDOrderMoveScheduleStatus computeStatus()
{
if (isDropTo())
{
return DDOrderMoveScheduleStatus.COMPLETED;
}
else if (isPickedFrom())
{
return DDOrderMoveScheduleStatus.IN_PROGRESS;
}
else
{
return DDOrderMoveScheduleStatus.NOT_STARTED;
}
}
@NonNull
public ExplainedOptional<LocatorId> getInTransitLocatorId()
{
if (pickedHUs == null)
{
return ExplainedOptional.emptyBecause("Schedule is not picked yet");
}
return pickedHUs.getInTransitLocatorId();
}
@NonNull
public ImmutableSet<HuId> getPickedHUIds()
{
final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this);
return pickedHUs.getActualHUIdsPicked();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void recursion(List<Menu> allMenus, List<Menu> routes, Menu roleMenu) {
Optional<Menu> menu = allMenus.stream().filter(x -> Func.equals(x.getId(), roleMenu.getParentId())).findFirst();
if (menu.isPresent() && !routes.contains(menu.get())) {
routes.add(menu.get());
recursion(allMenus, routes, menu.get());
}
}
@Override
public List<MenuVO> buttons(String roleId) {
List<Menu> buttons = baseMapper.buttons(Func.toLongList(roleId));
MenuWrapper menuWrapper = new MenuWrapper();
return menuWrapper.listNodeVO(buttons);
}
@Override
public List<MenuVO> tree() {
return ForestNodeMerger.merge(baseMapper.tree());
}
@Override
public List<MenuVO> grantTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTree() : baseMapper.grantTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<MenuVO> grantDataScopeTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantDataScopeTree() : baseMapper.grantDataScopeTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<String> roleTreeKeys(String roleIds) {
List<RoleMenu> roleMenus = roleMenuService.list(Wrappers.<RoleMenu>query().lambda().in(RoleMenu::getRoleId, Func.toLongList(roleIds)));
return roleMenus.stream().map(roleMenu -> Func.toStr(roleMenu.getMenuId())).collect(Collectors.toList());
}
@Override
public List<String> dataScopeTreeKeys(String roleIds) {
List<RoleScope> roleScopes = roleScopeService.list(Wrappers.<RoleScope>query().lambda().in(RoleScope::getRoleId, Func.toLongList(roleIds))); | return roleScopes.stream().map(roleScope -> Func.toStr(roleScope.getScopeId())).collect(Collectors.toList());
}
@Override
public List<Kv> authRoutes(BladeUser user) {
if (Func.isEmpty(user)) {
return null;
}
List<MenuDTO> routes = baseMapper.authRoutes(Func.toLongList(user.getRoleId()));
List<Kv> list = new ArrayList<>();
routes.forEach(route -> list.add(Kv.init().set(route.getPath(), Kv.init().set("authority", Func.toStrArray(route.getAlias())))));
return list;
}
@Override
public List<MenuVO> grantTopTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTopTree() : baseMapper.grantTopTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<String> topTreeKeys(String topMenuIds) {
List<TopMenuSetting> settings = topMenuSettingService.list(Wrappers.<TopMenuSetting>query().lambda().in(TopMenuSetting::getTopMenuId, Func.toLongList(topMenuIds)));
return settings.stream().map(setting -> Func.toStr(setting.getMenuId())).collect(Collectors.toList());
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\MenuServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
UpdateEvidencePaymentDisputeRequest updateEvidencePaymentDisputeRequest = (UpdateEvidencePaymentDisputeRequest)o;
return Objects.equals(this.evidenceId, updateEvidencePaymentDisputeRequest.evidenceId) &&
Objects.equals(this.evidenceType, updateEvidencePaymentDisputeRequest.evidenceType) &&
Objects.equals(this.files, updateEvidencePaymentDisputeRequest.files) &&
Objects.equals(this.lineItems, updateEvidencePaymentDisputeRequest.lineItems);
}
@Override
public int hashCode()
{
return Objects.hash(evidenceId, evidenceType, files, lineItems);
}
@Override
public String toString()
{ | StringBuilder sb = new StringBuilder();
sb.append("class UpdateEvidencePaymentDisputeRequest {\n");
sb.append(" evidenceId: ").append(toIndentedString(evidenceId)).append("\n");
sb.append(" evidenceType: ").append(toIndentedString(evidenceType)).append("\n");
sb.append(" files: ").append(toIndentedString(files)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\UpdateEvidencePaymentDisputeRequest.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.