instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public static KeyValues valueOf(String s) {
String[] tokens = StringUtils.tokenizeToStringArray(s, ",", true, true);
List<KeyValue> parsedKeyValues = Arrays.stream(tokens).map(KeyValue::valueOf).toList();
KeyValues keyValues = new KeyValues();
keyValues.setKeyValues(parsedKeyValues);
return keyValues;
}
public static class KeyValue {
private final String key;
private final String value;
public KeyValue(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key; | }
public String getValue() {
return value;
}
@Override
public String toString() {
return new ToStringCreator(this).append("name", key).append("value", value).toString();
}
public static KeyValue valueOf(String s) {
String[] tokens = StringUtils.tokenizeToStringArray(s, ":", true, true);
Assert.isTrue(tokens.length == 2, () -> "String must be two tokens delimited by colon, but was " + s);
return new KeyValue(tokens[0], tokens[1]);
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\common\KeyValues.java | 1 |
请完成以下Java代码 | public boolean updateAssignedCustomer(Customer customer) {
ShortCustomerInfo customerInfo = customer.toShortCustomerInfo();
if (this.assignedCustomers != null && this.assignedCustomers.contains(customerInfo)) {
this.assignedCustomers.remove(customerInfo);
this.assignedCustomers.add(customerInfo);
return true;
} else {
return false;
}
}
public boolean removeAssignedCustomer(Customer customer) {
ShortCustomerInfo customerInfo = customer.toShortCustomerInfo();
if (this.assignedCustomers != null && this.assignedCustomers.contains(customerInfo)) {
this.assignedCustomers.remove(customerInfo);
return true;
} else {
return false;
}
}
@Schema(description = "Same as title of the dashboard. Read-only field. Update the 'title' to change the 'name' of the dashboard.", accessMode = Schema.AccessMode.READ_ONLY)
@Override
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getName() {
return title;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode()); | result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
DashboardInfo that = (DashboardInfo) o;
return mobileHide == that.mobileHide
&& Objects.equals(tenantId, that.tenantId)
&& Objects.equals(title, that.title)
&& Objects.equals(image, that.image)
&& Objects.equals(assignedCustomers, that.assignedCustomers)
&& Objects.equals(mobileOrder, that.mobileOrder);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DashboardInfo [tenantId=");
builder.append(tenantId);
builder.append(", title=");
builder.append(title);
builder.append("]");
return builder.toString();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\DashboardInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ImmutableSet<ShipmentScheduleId> generateSchedules(@NonNull final OrderId orderId)
{
final I_C_Order order = orderDAO.getById(orderId);
if (!order.getDocStatus().equals(DOCSTATUS_Completed))
{
Loggables.withLogger(logger, Level.INFO).addLog("Returning! Order not COMPLETED!");
return ImmutableSet.of();
}
generateMissingShipmentSchedulesFromOrder(order);
return shipmentSchedulePA.retrieveScheduleIdsByOrderId(orderId);
}
private void generateOrdersForBatch(
@NonNull final AsyncBatchId asyncBatchId, | final boolean propagateAsyncIdsToShipmentSchduleWPs)
{
final Supplier<IEnqueueResult> action = () -> olCandToOrderEnqueuer.enqueueBatch(asyncBatchId, propagateAsyncIdsToShipmentSchduleWPs);
asyncBatchService.executeBatch(action, asyncBatchId);
}
private void generateMissingShipmentSchedulesFromOrder(@NonNull final I_C_Order order)
{
final ImmutablePair<AsyncBatchId, I_C_Order> batchIdWithOrder = asyncBatchBL.assignPermAsyncBatchToModelIfMissing(order, C_Async_Batch_InternalName_EnqueueScheduleForOrder);
final Supplier<IEnqueueResult> action = () -> CreateMissingShipmentSchedulesWorkpackageProcessor.scheduleIfNotPostponed(batchIdWithOrder.getRight());
asyncBatchService.executeBatch(action, batchIdWithOrder.getLeft());
}
} | repos\metasfresh-new_dawn_uat\backend\de-metas-salesorder\src\main\java\de\metas\salesorder\service\OrderService.java | 2 |
请完成以下Java代码 | public Void execute(CommandContext commandContext) {
commandContext.getAuthorizationManager().checkCamundaAdminOrPermission(CommandChecker::checkDeleteMetrics);
writeUserOperationLog(commandContext);
if(timestamp == null && reporter == null) {
commandContext.getMeterLogManager()
.deleteAll();
}
else {
commandContext.getMeterLogManager()
.deleteByTimestampAndReporter(timestamp, reporter);
}
return null;
} | protected void writeUserOperationLog(CommandContext commandContext) {
List<PropertyChange> propertyChanges = new ArrayList<>();
if (timestamp != null) {
propertyChanges.add(new PropertyChange("timestamp", null, timestamp));
}
if (reporter != null) {
propertyChanges.add(new PropertyChange("reporter", null, reporter));
}
if (propertyChanges.isEmpty()) {
propertyChanges.add(PropertyChange.EMPTY_CHANGE);
}
commandContext.getOperationLogManager().logMetricsOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE,
propertyChanges);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteMetricsCmd.java | 1 |
请完成以下Java代码 | public TransportProtos.ProvisionDeviceRequestMsg convertToProvisionRequestMsg(UUID sessionId, Request inbound) throws AdaptorException {
try {
return ProtoConverter.convertToProvisionRequestMsg(inbound.getPayload());
} catch (InvalidProtocolBufferException ex) {
throw new AdaptorException(ex);
}
}
@Override
public Response convertToPublish(TransportProtos.AttributeUpdateNotificationMsg msg) throws AdaptorException {
return getObserveNotification(msg.toByteArray());
}
@Override
public Response convertToPublish(TransportProtos.ToDeviceRpcRequestMsg rpcRequest, DynamicMessage.Builder rpcRequestDynamicMessageBuilder) throws AdaptorException {
return getObserveNotification(ProtoConverter.convertToRpcRequest(rpcRequest, rpcRequestDynamicMessageBuilder));
}
@Override
public Response convertToPublish(TransportProtos.ToServerRpcResponseMsg msg) throws AdaptorException {
Response response = new Response(CoAP.ResponseCode.CONTENT);
response.setPayload(msg.toByteArray());
return response;
}
@Override
public Response convertToPublish(TransportProtos.GetAttributeResponseMsg msg) throws AdaptorException {
if (msg.getSharedStateMsg()) {
if (StringUtils.isEmpty(msg.getError())) {
Response response = new Response(CoAP.ResponseCode.CONTENT);
TransportProtos.AttributeUpdateNotificationMsg notificationMsg = TransportProtos.AttributeUpdateNotificationMsg.newBuilder().addAllSharedUpdated(msg.getSharedAttributeListList()).build();
response.setPayload(notificationMsg.toByteArray());
return response;
} else {
return new Response(CoAP.ResponseCode.INTERNAL_SERVER_ERROR); | }
} else {
if (msg.getClientAttributeListCount() == 0 && msg.getSharedAttributeListCount() == 0) {
return new Response(CoAP.ResponseCode.NOT_FOUND);
} else {
Response response = new Response(CoAP.ResponseCode.CONTENT);
response.setPayload(msg.toByteArray());
return response;
}
}
}
private Response getObserveNotification(byte[] notification) {
Response response = new Response(CoAP.ResponseCode.CONTENT);
response.setPayload(notification);
return response;
}
@Override
public int getContentFormat() {
return MediaTypeRegistry.APPLICATION_OCTET_STREAM;
}
} | repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\adaptors\ProtoCoapAdaptor.java | 1 |
请完成以下Java代码 | private static Map<String, String> getSynchronizedMap() {
Map<String, String> synchronizedMap = Collections.synchronizedMap(new IdentityHashMap<String, String>());
return synchronizedMap;
}
private static IdentityHashMap<String, String> createFromAnotherMap(Map<String, String> otherMap) {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>(otherMap);
return identityHashMap;
}
private static void updateWithNewValue(IdentityHashMap<String, String> identityHashMap) {
String oldTitle = identityHashMap.put("title", "Harry Potter and the Deathly Hallows");
assertEquals("Harry Potter and the Goblet of Fire", oldTitle);
assertEquals("Harry Potter and the Deathly Hallows", identityHashMap.get("title"));
}
public static void addValue(IdentityHashMap<String, String> identityHashMap, String key, String value) {
identityHashMap.put(key, value); | }
public static void addAllValues(IdentityHashMap<String, String> identityHashMap, Map<String, String> otherMap) {
identityHashMap.putAll(otherMap);
}
public static IdentityHashMap<String, String> createWithSimpleData() {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>();
identityHashMap.put("title", "Harry Potter and the Goblet of Fire");
identityHashMap.put("author", "J. K. Rowling");
identityHashMap.put("language", "English");
identityHashMap.put("genre", "Fantasy");
return identityHashMap;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-5\src\main\java\com\baeldung\map\identity\IdentityHashMapDemonstrator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Kryo initialValue() {
final Kryo kryo = new Kryo();
kryo.register(Foo.class, 1);
return kryo;
}
};
public KryoHttpMessageConverter() {
super(KRYO);
}
@Override
protected boolean supports(final Class<?> clazz) {
return Object.class.isAssignableFrom(clazz);
}
@Override
protected Object readInternal(final Class<? extends Object> clazz,
final HttpInputMessage inputMessage) throws IOException {
final Input input = new Input(inputMessage.getBody()); | return kryoThreadLocal.get().readClassAndObject(input);
}
@Override
protected void writeInternal(final Object object,
final HttpOutputMessage outputMessage) throws IOException {
final Output output = new Output(outputMessage.getBody());
kryoThreadLocal.get().writeClassAndObject(output, object);
output.flush();
}
@Override
protected MediaType getDefaultContentType(final Object object) {
return KRYO;
}
} | repos\tutorials-master\spring-web-modules\spring-rest-simple\src\main\java\com\baeldung\config\converter\KryoHttpMessageConverter.java | 2 |
请完成以下Java代码 | 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代码 | class FreeMarkerReactiveWebConfiguration extends AbstractFreeMarkerConfiguration {
FreeMarkerReactiveWebConfiguration(FreeMarkerProperties properties,
ObjectProvider<FreeMarkerVariablesCustomizer> variablesCustomizers) {
super(properties, variablesCustomizers);
}
@Bean
@ConditionalOnMissingBean(FreeMarkerConfig.class)
FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
applyProperties(configurer);
return configurer;
}
@Bean | freemarker.template.Configuration freeMarkerConfiguration(FreeMarkerConfig configurer) {
return configurer.getConfiguration();
}
@Bean
@ConditionalOnMissingBean(name = "freeMarkerViewResolver")
FreeMarkerViewResolver freeMarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setPrefix(getProperties().getPrefix());
resolver.setSuffix(getProperties().getSuffix());
resolver.setRequestContextAttribute(getProperties().getRequestContextAttribute());
resolver.setViewNames(getProperties().getViewNames());
return resolver;
}
} | repos\spring-boot-4.0.1\module\spring-boot-freemarker\src\main\java\org\springframework\boot\freemarker\autoconfigure\FreeMarkerReactiveWebConfiguration.java | 2 |
请完成以下Java代码 | public Date getRecentOrderTime() {
return recentOrderTime;
}
public void setRecentOrderTime(Date recentOrderTime) {
this.recentOrderTime = recentOrderTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", consumeAmount=").append(consumeAmount);
sb.append(", orderCount=").append(orderCount);
sb.append(", couponCount=").append(couponCount); | sb.append(", commentCount=").append(commentCount);
sb.append(", returnOrderCount=").append(returnOrderCount);
sb.append(", loginCount=").append(loginCount);
sb.append(", attendCount=").append(attendCount);
sb.append(", fansCount=").append(fansCount);
sb.append(", collectProductCount=").append(collectProductCount);
sb.append(", collectSubjectCount=").append(collectSubjectCount);
sb.append(", collectTopicCount=").append(collectTopicCount);
sb.append(", collectCommentCount=").append(collectCommentCount);
sb.append(", inviteFriendCount=").append(inviteFriendCount);
sb.append(", recentOrderTime=").append(recentOrderTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberStatisticsInfo.java | 1 |
请完成以下Java代码 | public class LocalInstrumentSEPA {
@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\LocalInstrumentSEPA.java | 1 |
请完成以下Java代码 | public Color deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
final JsonObject jo = json.getAsJsonObject();
final int r = jo.get("r").getAsInt();
final int g = jo.get("g").getAsInt();
final int b = jo.get("b").getAsInt();
final int a = jo.get("a").getAsInt();
return new ColorUIResource(new Color(r, g, b, a));
}
}
public static class FontJsonSerializer extends UIResourceJsonSerializer<Font>
{
@Override
public JsonElement serialize(Font src, Type typeOfSrc, JsonSerializationContext context)
{
JsonObject jo = new JsonObject();
jo.addProperty(PROPERTY_Classname, src.getClass().getName());
jo.addProperty("name", src.getName());
jo.addProperty("style", src.getStyle());
jo.addProperty("size", src.getSize());
return jo;
}
@Override
public Font deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
final JsonObject jo = json.getAsJsonObject();
String name = jo.get("name").getAsString();
int style = jo.get("style").getAsInt();
int size = jo.get("size").getAsInt();
return new FontUIResource(name, style, size);
}
}
public static class VEditorDialogButtonAlignJsonSerializer extends UIResourceJsonSerializer<VEditorDialogButtonAlign>
{
@Override
public JsonElement serialize(VEditorDialogButtonAlign src, Type typeOfSrc, JsonSerializationContext context)
{
final JsonObject jo = new JsonObject();
jo.addProperty(PROPERTY_Classname, src.getClass().getName());
jo.addProperty("value", src.toString());
return jo; | }
@Override
public VEditorDialogButtonAlign deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
final JsonObject jo = json.getAsJsonObject();
final String value = jo.get("value").getAsString();
try
{
return VEditorDialogButtonAlign.valueOf(value);
}
catch (Exception e)
{
logger.warn("Failed parsing value {}. Using default", value);
}
return VEditorDialogButtonAlign.DEFAULT_Value;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\UIDefaultsSerializer.java | 1 |
请完成以下Java代码 | public void assertNotEmpty()
{
if (list.isEmpty())
{
throw new AdempiereException("candidates list shall not be empty");
}
}
public boolean isEmpty() {return list.isEmpty();}
@Override
@NonNull
public Iterator<Candidate> iterator() {return list.iterator();}
@Override
public void forEach(@NonNull final Consumer<? super Candidate> action) {list.forEach(action);}
public ClientAndOrgId getClientAndOrgId()
{
assertNotEmpty();
return list.get(0).getClientAndOrgId();
}
public MaterialDispoGroupId getEffectiveGroupId()
{
assertNotEmpty();
return list.get(0).getEffectiveGroupId();
}
public CandidateBusinessCase getBusinessCase() | {
assertNotEmpty();
return CollectionUtils.extractSingleElement(list, Candidate::getBusinessCase);
}
public Candidate getSingleCandidate()
{
return CollectionUtils.singleElement(list);
}
public Candidate getSingleSupplyCandidate()
{
return CollectionUtils.singleElement(list, candidate -> CandidateType.equals(candidate.getType(), CandidateType.SUPPLY));
}
public Candidate getSingleDemandCandidate()
{
return CollectionUtils.singleElement(list, candidate -> CandidateType.equals(candidate.getType(), CandidateType.DEMAND));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\CandidatesGroup.java | 1 |
请完成以下Java代码 | protected void addAuthorizationsFromIterator(
CommandContext commandContext,
List<String> expressions,
ProcessDefinitionEntity processDefinition,
ExpressionType expressionType
) {
if (expressions != null) {
Iterator<String> iterator = expressions.iterator();
while (iterator.hasNext()) {
@SuppressWarnings("cast")
String expression = iterator.next();
IdentityLinkEntity identityLink = commandContext.getIdentityLinkEntityManager().create();
identityLink.setProcessDef(processDefinition);
if (expressionType.equals(ExpressionType.USER)) {
identityLink.setUserId(expression);
} else if (expressionType.equals(ExpressionType.GROUP)) {
identityLink.setGroupId(expression);
}
identityLink.setType(IdentityLinkType.CANDIDATE);
commandContext.getIdentityLinkEntityManager().insert(identityLink);
}
}
} | public TimerManager getTimerManager() {
return timerManager;
}
public void setTimerManager(TimerManager timerManager) {
this.timerManager = timerManager;
}
public EventSubscriptionManager getEventSubscriptionManager() {
return eventSubscriptionManager;
}
public void setEventSubscriptionManager(EventSubscriptionManager eventSubscriptionManager) {
this.eventSubscriptionManager = eventSubscriptionManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeploymentHelper.java | 1 |
请完成以下Java代码 | public class MElementValueTreeSupport extends DefaultPOTreeSupport
{
private ChartOfAccountsService _chartOfAccountsService; // lazy
@Override
public int getAD_Tree_ID(final PO po)
{
if (!InterfaceWrapperHelper.isInstanceOf(po, I_C_ElementValue.class))
{
return -1;
}
final I_C_ElementValue ev = InterfaceWrapperHelper.create(po, I_C_ElementValue.class);
final ChartOfAccountsId chartOfAccountsId = ChartOfAccountsId.ofRepoId(ev.getC_Element_ID());
final AdTreeId chartOfAccountsTreeId = chartOfAccountsService().getById(chartOfAccountsId).getTreeId();
return chartOfAccountsTreeId.getRepoId();
}
private ChartOfAccountsService chartOfAccountsService()
{
ChartOfAccountsService chartOfAccountsService = this._chartOfAccountsService;
if (chartOfAccountsService == null)
{
chartOfAccountsService = this._chartOfAccountsService = SpringContextHolder.instance.getBean(ChartOfAccountsService.class);
}
return chartOfAccountsService;
}
@Override
public String getWhereClause(final MTree_Base tree)
{
final ChartOfAccountsId chartOfAccountsId = getChartOfAccountsId(tree).orElse(null);
if (chartOfAccountsId == null)
{
// the tree is not yet referenced from any C_Element record. maybe it was just created | return "0=1";
}
else
{
return I_C_ElementValue.COLUMNNAME_C_Element_ID + "=" + chartOfAccountsId.getRepoId();
}
}
private Optional<ChartOfAccountsId> getChartOfAccountsId(final MTree_Base tree)
{
return chartOfAccountsService()
.getByTreeId(AdTreeId.ofRepoId(tree.getAD_Tree_ID()))
.map(ChartOfAccounts::getId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\MElementValueTreeSupport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HEADERXlief getHEADER() {
return header;
}
/**
* Sets the value of the header property.
*
* @param value
* allowed object is
* {@link HEADERXlief }
*
*/
public void setHEADER(HEADERXlief value) {
this.header = value;
}
/**
* Gets the value of the trailr property.
*
* @return
* possible object is
* {@link TRAILR }
*
*/
public TRAILR getTRAILR() {
return trailr; | }
/**
* Sets the value of the trailr property.
*
* @param value
* allowed object is
* {@link TRAILR }
*
*/
public void setTRAILR(TRAILR value) {
this.trailr = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\Xlief4H.java | 2 |
请完成以下Java代码 | public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd;
}
/**
* Sets the value of the cdtDbtInd property.
*
* @param value
* allowed object is
* {@link CreditDebitCode }
*
*/
public void setCdtDbtInd(CreditDebitCode value) {
this.cdtDbtInd = value;
}
/**
* Gets the value of the dt property.
*
* @return
* possible object is
* {@link DateAndDateTimeChoice }
*
*/
public DateAndDateTimeChoice getDt() {
return dt;
}
/**
* Sets the value of the dt property.
*
* @param value
* allowed object is
* {@link DateAndDateTimeChoice }
*
*/
public void setDt(DateAndDateTimeChoice value) {
this.dt = value;
}
/**
* Gets the value of the avlbty property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object. | * This is why there is not a <CODE>set</CODE> method for the avlbty property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAvlbty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CashBalanceAvailability2 }
*
*
*/
public List<CashBalanceAvailability2> getAvlbty() {
if (avlbty == null) {
avlbty = new ArrayList<CashBalanceAvailability2>();
}
return this.avlbty;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CashBalance3.java | 1 |
请完成以下Java代码 | public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSubject() { | return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
} | repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\java\client\domain\Book.java | 1 |
请完成以下Java代码 | private List<BpmnModel> parseSubModels(
FlowElement subElement,
Map<String, GraphicInfo> locations,
Map<String, List<GraphicInfo>> flowLocations,
Map<String, GraphicInfo> labelLocations
) {
List<BpmnModel> subModels = new ArrayList<BpmnModel>();
BpmnModel subModel = new BpmnModel();
String elementId = null;
// find nested subprocess models
Collection<FlowElement> subFlowElements = ((SubProcess) subElement).getFlowElements();
// set main process in submodel to subprocess
Process newMainProcess = new Process();
newMainProcess.setId(subElement.getId());
newMainProcess.getFlowElements().addAll(subFlowElements);
newMainProcess.getArtifacts().addAll(((SubProcess) subElement).getArtifacts());
subModel.addProcess(newMainProcess);
for (FlowElement element : subFlowElements) {
elementId = element.getId();
if (element instanceof SubProcess) {
subModels.addAll(parseSubModels(element, locations, flowLocations, labelLocations));
}
if (element instanceof SequenceFlow && null != flowLocations.get(elementId)) {
// must be an edge
subModel.getFlowLocationMap().put(elementId, flowLocations.get(elementId)); | } else {
// do not include data objects because they do not have a corresponding shape in the BPMNDI data
if (!(element instanceof DataObject) && null != locations.get(elementId)) {
// must be a shape
subModel.getLocationMap().put(elementId, locations.get(elementId));
}
}
// also check for any labels
if (null != labelLocations.get(elementId)) {
subModel.getLabelLocationMap().put(elementId, labelLocations.get(elementId));
}
}
subModels.add(subModel);
return subModels;
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\SubprocessXMLConverter.java | 1 |
请完成以下Java代码 | public int getCleanInstancesEndedAfterNumberOfDays() {
return (int) cleanInstancesEndedAfter.toDays();
}
/**
* @deprecated use {@link #setCleanInstancesEndedAfter(Duration)} instead
*/
@Deprecated
public ProcessEngineConfiguration setCleanInstancesEndedAfterNumberOfDays(int cleanInstancesEndedAfterNumberOfDays) {
return setCleanInstancesEndedAfter(Duration.ofDays(cleanInstancesEndedAfterNumberOfDays));
}
public Duration getCleanInstancesEndedAfter() {
return cleanInstancesEndedAfter;
}
public ProcessEngineConfiguration setCleanInstancesEndedAfter(Duration cleanInstancesEndedAfter) {
this.cleanInstancesEndedAfter = cleanInstancesEndedAfter;
return this;
}
public int getCleanInstancesBatchSize() {
return cleanInstancesBatchSize;
}
public ProcessEngineConfiguration setCleanInstancesBatchSize(int cleanInstancesBatchSize) {
this.cleanInstancesBatchSize = cleanInstancesBatchSize;
return this; | }
public HistoryCleaningManager getHistoryCleaningManager() {
return historyCleaningManager;
}
public ProcessEngineConfiguration setHistoryCleaningManager(HistoryCleaningManager historyCleaningManager) {
this.historyCleaningManager = historyCleaningManager;
return this;
}
public boolean isAlwaysUseArraysForDmnMultiHitPolicies() {
return alwaysUseArraysForDmnMultiHitPolicies;
}
public ProcessEngineConfiguration setAlwaysUseArraysForDmnMultiHitPolicies(boolean alwaysUseArraysForDmnMultiHitPolicies) {
this.alwaysUseArraysForDmnMultiHitPolicies = alwaysUseArraysForDmnMultiHitPolicies;
return this;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\ProcessEngineConfiguration.java | 1 |
请完成以下Java代码 | public void setC_Doc_Responsible_ID (int C_Doc_Responsible_ID)
{
if (C_Doc_Responsible_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, Integer.valueOf(C_Doc_Responsible_ID));
}
/** Get Document Responsible.
@return Document Responsible */
@Override
public int getC_Doc_Responsible_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Doc_Responsible_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID | */
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\workflow\model\X_C_Doc_Responsible.java | 1 |
请完成以下Java代码 | public class RcCaptchaValidateFilter extends AccessControlFilter {
private boolean captchaEbabled = true;// 是否开启验证码支持
private String captchaParam = "captchaCode";// 前台提交的验证码参数名
private String failureKeyAttribute = "shiroLoginFailure"; // 验证码验证失败后存储到的属性名
public void setCaptchaEbabled(boolean captchaEbabled) {
this.captchaEbabled = captchaEbabled;
}
public void setCaptchaParam(String captchaParam) {
this.captchaParam = captchaParam;
}
public void setFailureKeyAttribute(String failureKeyAttribute) {
this.failureKeyAttribute = failureKeyAttribute;
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
// 1、设置验证码是否开启属性,页面可以根据该属性来决定是否显示验证码
request.setAttribute("captchaEbabled", captchaEbabled);
HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
// 2、判断验证码是否禁用 或不是表单提交(允许访问) | if (captchaEbabled == false || !"post".equalsIgnoreCase(httpServletRequest.getMethod())) {
return true;
}
// 3、此时是表单提交,验证验证码是否正确
// 获取页面提交的验证码
String submitCaptcha = httpServletRequest.getParameter(captchaParam);
// 获取session中的验证码
String captcha = (String) httpServletRequest.getSession().getAttribute("rcCaptcha");
if (submitCaptcha.equals(captcha)) {
return true;
}
return false;
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
// 如果验证码失败了,存储失败key属性
request.setAttribute(failureKeyAttribute, "验证码错误!");
return true;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\filter\RcCaptchaValidateFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExtendedPeriodType {
@XmlElement(name = "Quantity")
protected ConditionalUnitType quantity;
@XmlElement(name = "StartDate")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar startDate;
@XmlElement(name = "EndDate")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar endDate;
/**
* Gets the value of the quantity property.
*
* @return
* possible object is
* {@link ConditionalUnitType }
*
*/
public ConditionalUnitType getQuantity() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
* @param value
* allowed object is
* {@link ConditionalUnitType }
*
*/
public void setQuantity(ConditionalUnitType value) {
this.quantity = value;
}
/**
* Gets the value of the startDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartDate() {
return startDate;
}
/**
* Sets the value of the startDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartDate(XMLGregorianCalendar value) { | this.startDate = value;
}
/**
* Gets the value of the endDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEndDate() {
return endDate;
}
/**
* Sets the value of the endDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndDate(XMLGregorianCalendar value) {
this.endDate = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ExtendedPeriodType.java | 2 |
请完成以下Java代码 | public String getTenantId() {
return tenantId;
}
public long getPriority() {
return priority;
}
public String getBusinessKey() {
return businessKey;
}
public static ExternalTaskDto fromExternalTask(ExternalTask task) {
ExternalTaskDto dto = new ExternalTaskDto();
dto.activityId = task.getActivityId();
dto.activityInstanceId = task.getActivityInstanceId();
dto.errorMessage = task.getErrorMessage();
dto.executionId = task.getExecutionId();
dto.id = task.getId();
dto.lockExpirationTime = task.getLockExpirationTime(); | dto.createTime = task.getCreateTime();
dto.processDefinitionId = task.getProcessDefinitionId();
dto.processDefinitionKey = task.getProcessDefinitionKey();
dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag();
dto.processInstanceId = task.getProcessInstanceId();
dto.retries = task.getRetries();
dto.suspended = task.isSuspended();
dto.topicName = task.getTopicName();
dto.workerId = task.getWorkerId();
dto.tenantId = task.getTenantId();
dto.priority = task.getPriority();
dto.businessKey = task.getBusinessKey();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\ExternalTaskDto.java | 1 |
请完成以下Java代码 | default Date getStartTime() {
return getCreateTime();
}
Date getCreateTime();
Date getLastAvailableTime();
Date getLastUnavailableTime();
Date getLastEnabledTime();
Date getLastDisabledTime();
Date getLastStartedTime();
Date getLastSuspendedTime();
Date getCompletedTime();
Date getOccurredTime();
Date getTerminatedTime();
Date getExitTime();
Date getEndedTime();
String getStartUserId(); | String getAssignee();
String getCompletedBy();
String getReferenceId();
String getReferenceType();
boolean isCompletable();
String getEntryCriterionId();
String getExitCriterionId();
String getFormKey();
String getExtraValue();
String getTenantId();
Map<String, Object> getPlanItemInstanceLocalVariables();
/** Sets an optional localized name for the plan item */
void setLocalizedName(String localizedName);
} | repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\runtime\PlanItemInstance.java | 1 |
请完成以下Java代码 | public class DmnEngineMetricCollectorWrapper implements DmnEngineMetricCollector, DmnDecisionEvaluationListener {
protected final DmnEngineMetricCollector collector;
public DmnEngineMetricCollectorWrapper(DmnEngineMetricCollector collector) {
this.collector = collector;
}
@Override
public void notify(DmnDecisionTableEvaluationEvent evaluationEvent) {
// the wrapper listen for decision evaluation events
}
@Override
public void notify(DmnDecisionEvaluationEvent evaluationEvent) {
notifyCollector(evaluationEvent.getDecisionResult());
for (DmnDecisionLogicEvaluationEvent event : evaluationEvent.getRequiredDecisionResults()) {
notifyCollector(event);
}
}
protected void notifyCollector(DmnDecisionLogicEvaluationEvent evaluationEvent) {
if (evaluationEvent instanceof DmnDecisionTableEvaluationEvent) {
collector.notify((DmnDecisionTableEvaluationEvent) evaluationEvent);
} | // ignore other evaluation events since the collector is implemented as decision table evaluation listener
}
@Override
public long getExecutedDecisionInstances() {
return collector.getExecutedDecisionInstances();
}
@Override
public long getExecutedDecisionElements() {
return collector.getExecutedDecisionElements();
}
@Override
public long clearExecutedDecisionInstances() {
return collector.clearExecutedDecisionInstances();
}
@Override
public long clearExecutedDecisionElements() {
return collector.clearExecutedDecisionElements();
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\metrics\DmnEngineMetricCollectorWrapper.java | 1 |
请完成以下Java代码 | public void setTitle(String title)
{
if (title != null)
{
final int pos = title.indexOf('&');
if (pos != -1 && title.length() > pos) // We have a nemonic
{
final int mnemonic = title.toUpperCase().charAt(pos + 1);
if (mnemonic != ' ')
{
title = title.substring(0, pos) + title.substring(pos + 1);
}
}
}
super.setTitle(title);
} // setTitle
/** Dispose Action Name */
protected static String ACTION_DISPOSE = "CDialogDispose";
/** Action */
protected static DialogAction s_dialogAction = new DialogAction(ACTION_DISPOSE);
/** ALT-EXCAPE */
protected static KeyStroke s_disposeKeyStroke =
KeyStroke.getKeyStroke(KeyEvent.VK_PAUSE, InputEvent.ALT_MASK);
/**
* Adempiere Dialog Action
*
* @author Jorg Janke
* @version $Id: CDialog.java,v 1.3 2006/07/30 00:52:24 jjanke Exp $
*/
static class DialogAction extends AbstractAction
{
/**
*
*/
private static final long serialVersionUID = -1502992970807699945L;
DialogAction(final String actionName)
{
super(actionName);
putValue(Action.ACTION_COMMAND_KEY, actionName);
} // DialogAction
/**
* Action Listener
*
* @param e event
*/
@Override
public void actionPerformed(final ActionEvent e)
{
if (ACTION_DISPOSE.equals(e.getActionCommand())) | {
Object source = e.getSource();
while (source != null)
{
if (source instanceof Window)
{
((Window)source).dispose();
return;
}
if (source instanceof Container)
{
source = ((Container)source).getParent();
}
else
{
source = null;
}
}
}
else
{
System.out.println("Action: " + e);
}
} // actionPerformed
} // DialogAction
} // CDialog | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CDialog.java | 1 |
请完成以下Java代码 | public void setAD_Session_ID (int AD_Session_ID)
{
if (AD_Session_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Session_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Session_ID, Integer.valueOf(AD_Session_ID));
}
@Override
public int getAD_Session_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Session_ID);
}
@Override
public void setBinaryFormat (java.lang.String BinaryFormat)
{
set_Value (COLUMNNAME_BinaryFormat, BinaryFormat);
}
@Override
public java.lang.String getBinaryFormat()
{
return (java.lang.String)get_Value(COLUMNNAME_BinaryFormat);
}
@Override
public void setCopies (int Copies)
{
set_Value (COLUMNNAME_Copies, Integer.valueOf(Copies));
}
@Override
public int getCopies()
{
return get_ValueAsInt(COLUMNNAME_Copies);
}
@Override
public de.metas.printing.model.I_C_Print_Job_Instructions getC_Print_Job_Instructions()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Job_Instructions_ID, de.metas.printing.model.I_C_Print_Job_Instructions.class);
}
@Override
public void setC_Print_Job_Instructions(de.metas.printing.model.I_C_Print_Job_Instructions C_Print_Job_Instructions)
{
set_ValueFromPO(COLUMNNAME_C_Print_Job_Instructions_ID, de.metas.printing.model.I_C_Print_Job_Instructions.class, C_Print_Job_Instructions);
}
@Override
public void setC_Print_Job_Instructions_ID (int C_Print_Job_Instructions_ID)
{
if (C_Print_Job_Instructions_ID < 1)
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, null);
else
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, Integer.valueOf(C_Print_Job_Instructions_ID));
}
@Override
public int getC_Print_Job_Instructions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Instructions_ID);
}
@Override | public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setPackageInfoCount (int PackageInfoCount)
{
throw new IllegalArgumentException ("PackageInfoCount is virtual column"); }
@Override
public int getPackageInfoCount()
{
return get_ValueAsInt(COLUMNNAME_PackageInfoCount);
}
@Override
public void setPageCount (int PageCount)
{
set_Value (COLUMNNAME_PageCount, Integer.valueOf(PageCount));
}
@Override
public int getPageCount()
{
return get_ValueAsInt(COLUMNNAME_PageCount);
}
@Override
public void setTransactionID (java.lang.String TransactionID)
{
set_Value (COLUMNNAME_TransactionID, TransactionID);
}
@Override
public java.lang.String getTransactionID()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Package.java | 1 |
请完成以下Java代码 | public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getJobManager()
.findJobsByQueryCriteria(this, page);
}
@Override
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobManager()
.findDeploymentIdMappingsByQueryCriteria(this);
}
//getters //////////////////////////////////////////
public Set<String> getIds() {
return ids;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public String getExecutionId() { | return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public boolean getAcquired() {
return acquired;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobQueryImpl.java | 1 |
请完成以下Java代码 | protected boolean afterSave(boolean newRecord, boolean success) {
if (!success)
return false;
return updateParent();
}
@Override
protected boolean afterDelete(boolean success) {
if (!success)
return false;
return updateParent();
}
/**
* Update parent flags
* @return true if success
*/
private boolean updateParent() {
final String sql_count = "SELECT COUNT(*) FROM "+Table_Name+" r"
+" WHERE r."+COLUMNNAME_AD_Alert_ID+"=a."+MAlert.COLUMNNAME_AD_Alert_ID
+" AND r."+COLUMNNAME_IsValid+"='N'"
+" AND r.IsActive='Y'"
;
final String sql = "UPDATE "+MAlert.Table_Name+" a SET "
+" "+MAlert.COLUMNNAME_IsValid+"=(CASE WHEN ("+sql_count+") > 0 THEN 'N' ELSE 'Y' END)"
+" WHERE a."+MAlert.COLUMNNAME_AD_Alert_ID+"=?"
;
int no = DB.executeUpdateAndSaveErrorOnFail(sql, getAD_Alert_ID(), get_TrxName()); | return no == 1;
}
/**
* String Representation
* @return info
*/
@Override
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAlertRule[");
sb.append(get_ID())
.append("-").append(getName())
.append(",Valid=").append(isValid())
.append(",").append(getSql(false));
sb.append ("]");
return sb.toString ();
} // toString
} // MAlertRule | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlertRule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setConcurrency(Integer concurrency) {
this.concurrency = concurrency;
}
@Override
protected ConcurrentMessageListenerContainer<K, V> createContainerInstance(KafkaListenerEndpoint endpoint) {
TopicPartitionOffset[] topicPartitions = endpoint.getTopicPartitionsToAssign();
if (topicPartitions != null && topicPartitions.length > 0) {
ContainerProperties properties = new ContainerProperties(topicPartitions);
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
}
else {
Collection<String> topics = endpoint.getTopics();
Assert.state(topics != null, "'topics' must not be null");
if (!topics.isEmpty()) { // NOSONAR
ContainerProperties properties = new ContainerProperties(topics.toArray(new String[0]));
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
}
else {
ContainerProperties properties = new ContainerProperties(endpoint.getTopicPattern()); // NOSONAR
return new ConcurrentMessageListenerContainer<>(getConsumerFactory(), properties);
}
}
} | @Override
protected void initializeContainer(ConcurrentMessageListenerContainer<K, V> instance,
KafkaListenerEndpoint endpoint) {
super.initializeContainer(instance, endpoint);
Integer conc = endpoint.getConcurrency();
if (conc != null) {
instance.setConcurrency(conc);
}
else if (this.concurrency != null) {
instance.setConcurrency(this.concurrency);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\ConcurrentKafkaListenerContainerFactory.java | 2 |
请完成以下Java代码 | public boolean isDefaultPO ()
{
Object oo = get_Value(COLUMNNAME_IsDefaultPO);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Standard (Verkauf).
@param IsDefaultSO
Default value for sales transactions
*/
@Override
public void setIsDefaultSO (boolean IsDefaultSO)
{
set_Value (COLUMNNAME_IsDefaultSO, Boolean.valueOf(IsDefaultSO));
}
/** Get Standard (Verkauf).
@return Default value for sales transactions
*/
@Override
public boolean isDefaultSO ()
{
Object oo = get_Value(COLUMNNAME_IsDefaultSO);
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
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_Aggregation.java | 1 |
请完成以下Java代码 | public class WEBUI_M_HU_ReturnFromCustomer extends HUEditorProcessTemplate implements IProcessPrecondition
{
private final ReturnsServiceFacade returnsServiceFacade = SpringContextHolder.instance.getBean(ReturnsServiceFacade.class);
private ImmutableList<I_M_HU> _selectedHUsToReturn = null;
private MultiCustomerHUReturnsResult result;
private static final HUEditorRowFilter ELIGIBLE_ROWS_FILTER = HUEditorRowFilter.builder().select(Select.ONLY_TOPLEVEL).onlyHUStatus(X_M_HU.HUSTATUS_Shipped).build();
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!isHUEditorView())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view");
}
if (!streamEligibleSelectedRows().findAny().isPresent())
{
return ProcessPreconditionsResolution.reject(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU);
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final ImmutableList<I_M_HU> husToReturn = getSelectedHUsToReturn();
if (husToReturn.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
this.result = returnsServiceFacade.createCustomerReturnInOutForHUs(husToReturn);
return MSG_OK;
} | private Stream<HUEditorRow> streamEligibleSelectedRows()
{
return streamSelectedRows(ELIGIBLE_ROWS_FILTER);
}
private ImmutableList<I_M_HU> getSelectedHUsToReturn()
{
ImmutableList<I_M_HU> selectedHUsToReturn = this._selectedHUsToReturn;
if (selectedHUsToReturn == null)
{
final ImmutableSet<HuId> huIds = streamEligibleSelectedRows()
.map(HUEditorRow::getHuId)
.distinct()
.collect(ImmutableSet.toImmutableSet());
selectedHUsToReturn = this._selectedHUsToReturn = ImmutableList.copyOf(handlingUnitsRepo.getByIds(huIds));
}
return selectedHUsToReturn;
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
final HashSet<HuId> huIdsToRefresh = new HashSet<>();
getSelectedHUsToReturn().stream()
.map(hu -> HuId.ofRepoId(hu.getM_HU_ID()))
.forEach(huIdsToRefresh::add);
if (result != null)
{
huIdsToRefresh.addAll(result.getReturnedHUIds());
}
addHUIdsAndInvalidateView(huIdsToRefresh);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReturnFromCustomer.java | 1 |
请完成以下Java代码 | public boolean isCompleted(final I_C_RfQResponse rfqResponse)
{
return X_C_RfQResponse.DOCSTATUS_Completed.equals(rfqResponse.getDocStatus());
}
@Override
public boolean isCompleted(final I_C_RfQResponseLine rfqResponseLine)
{
return X_C_RfQResponseLine.DOCSTATUS_Completed.equals(rfqResponseLine.getDocStatus());
}
@Override
public boolean isClosed(final I_C_RfQResponse rfqResponse)
{
return X_C_RfQResponse.DOCSTATUS_Closed.equals(rfqResponse.getDocStatus());
}
@Override
public boolean isClosed(final I_C_RfQResponseLine rfqResponseLine)
{
return X_C_RfQResponseLine.DOCSTATUS_Closed.equals(rfqResponseLine.getDocStatus());
}
@Override
public String getSummary(final I_C_RfQ rfq)
{
// NOTE: nulls shall be tolerated because the method is used for building exception error messages
if (rfq == null)
{
return "@C_RfQ_ID@ ?";
}
return "@C_RfQ_ID@ #" + rfq.getDocumentNo();
}
@Override
public String getSummary(final I_C_RfQResponse rfqResponse)
{
// NOTE: nulls shall be tolerated because the method is used for building exception error messages
if (rfqResponse == null) | {
return "@C_RfQResponse_ID@ ?";
}
return "@C_RfQResponse_ID@ #" + rfqResponse.getName();
}
@Override
public void updateQtyPromisedAndSave(final I_C_RfQResponseLine rfqResponseLine)
{
final BigDecimal qtyPromised = Services.get(IRfqDAO.class).calculateQtyPromised(rfqResponseLine);
rfqResponseLine.setQtyPromised(qtyPromised);
InterfaceWrapperHelper.save(rfqResponseLine);
}
// @Override
// public void uncloseInTrx(final I_C_RfQResponse rfqResponse)
// {
// if (!isClosed(rfqResponse))
// {
// throw new RfQDocumentNotClosedException(getSummary(rfqResponse));
// }
//
// //
// final IRfQEventDispacher rfQEventDispacher = getRfQEventDispacher();
// rfQEventDispacher.fireBeforeUnClose(rfqResponse);
//
// //
// // Mark as NOT closed
// rfqResponse.setDocStatus(X_C_RfQResponse.DOCSTATUS_Completed);
// InterfaceWrapperHelper.save(rfqResponse);
// updateRfQResponseLinesStatus(rfqResponse);
//
// //
// rfQEventDispacher.fireAfterUnClose(rfqResponse);
//
// // Make sure it's saved
// InterfaceWrapperHelper.save(rfqResponse);
// }
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqBL.java | 1 |
请完成以下Java代码 | public void enableTenantCheck() {
tenantCheckEnabled = true;
}
public void disableTenantCheck() {
tenantCheckEnabled = false;
}
public void setTenantCheckEnabled(boolean tenantCheckEnabled) {
this.tenantCheckEnabled = tenantCheckEnabled;
}
public boolean isTenantCheckEnabled() {
return tenantCheckEnabled;
}
public JobEntity getCurrentJob() {
return currentJob;
}
public void setCurrentJob(JobEntity currentJob) {
this.currentJob = currentJob;
}
public boolean isRestrictUserOperationLogToAuthenticatedUsers() {
return restrictUserOperationLogToAuthenticatedUsers;
}
public void setRestrictUserOperationLogToAuthenticatedUsers(boolean restrictUserOperationLogToAuthenticatedUsers) {
this.restrictUserOperationLogToAuthenticatedUsers = restrictUserOperationLogToAuthenticatedUsers;
}
public String getOperationId() {
if (!getOperationLogManager().isUserOperationLogEnabled()) {
return null;
}
if (operationId == null) {
operationId = Context.getProcessEngineConfiguration().getIdGenerator().getNextId();
}
return operationId;
}
public void setOperationId(String operationId) {
this.operationId = operationId;
}
public OptimizeManager getOptimizeManager() { | return getSession(OptimizeManager.class);
}
public <T> void executeWithOperationLogPrevented(Command<T> command) {
boolean initialLegacyRestrictions =
isRestrictUserOperationLogToAuthenticatedUsers();
disableUserOperationLog();
setRestrictUserOperationLogToAuthenticatedUsers(true);
try {
command.execute(this);
} finally {
enableUserOperationLog();
setRestrictUserOperationLogToAuthenticatedUsers(initialLegacyRestrictions);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandContext.java | 1 |
请完成以下Java代码 | public ExecutionImpl getReplacedBy() {
return (ExecutionImpl) replacedBy;
}
public void setExecutions(List<ExecutionImpl> executions) {
this.executions = executions;
}
public String getCurrentActivityName() {
String currentActivityName = null;
if (this.activity != null) {
currentActivityName = (String) activity.getProperty("name");
}
return currentActivityName;
}
public FlowElement getBpmnModelElementInstance() {
throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl");
}
public BpmnModelInstance getBpmnModelInstance() {
throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl");
} | public ProcessEngineServices getProcessEngineServices() {
throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl");
}
public ProcessEngine getProcessEngine() {
throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl");
}
public void forceUpdate() {
// nothing to do
}
public void fireHistoricProcessStartEvent() {
// do nothing
}
protected void removeVariablesLocalInternal(){
// do nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\ExecutionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Mono<Void> validateKeyIdAndSignature(Token token) {
return getTokenKey(token).filter((tokenKey) -> hasValidSignature(token, tokenKey))
.switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE,
"RSA Signature did not match content")))
.then();
}
private Mono<String> getTokenKey(Token token) {
String keyId = token.getKeyId();
String cached = this.cachedTokenKeys.get(keyId);
if (cached != null) {
return Mono.just(cached);
}
return this.securityService.fetchTokenKeys()
.doOnSuccess(this::cacheTokenKeys)
.filter((tokenKeys) -> tokenKeys.containsKey(keyId))
.map((tokenKeys) -> {
String tokenKey = tokenKeys.get(keyId);
Assert.state(tokenKey != null, "No token key found for '%s'".formatted(keyId));
return tokenKey;
})
.switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID,
"Key Id present in token header does not match")));
}
private void cacheTokenKeys(Map<String, String> tokenKeys) {
this.cachedTokenKeys = Map.copyOf(tokenKeys);
}
private boolean hasValidSignature(Token token, String key) {
try {
PublicKey publicKey = getPublicKey(key);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(publicKey);
signature.update(token.getContent());
return signature.verify(token.getSignature());
}
catch (GeneralSecurityException ex) {
return false;
}
}
private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
key = key.replace("-----BEGIN PUBLIC KEY-----\n", "");
key = key.replace("-----END PUBLIC KEY-----", ""); | key = key.trim().replace("\n", "");
byte[] bytes = Base64.getDecoder().decode(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
return KeyFactory.getInstance("RSA").generatePublic(keySpec);
}
private Mono<Void> validateExpiry(Token token) {
long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
if (currentTime > token.getExpiry()) {
return Mono.error(new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired"));
}
return Mono.empty();
}
private Mono<Void> validateIssuer(Token token) {
return this.securityService.getUaaUrl()
.map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl))
.filter((issuerUri) -> issuerUri.equals(token.getIssuer()))
.switchIfEmpty(Mono
.error(new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match")))
.then();
}
private Mono<Void> validateAudience(Token token) {
if (!token.getScope().contains("actuator.read")) {
return Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_AUDIENCE,
"Token does not have audience actuator"));
}
return Mono.empty();
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\reactive\TokenValidator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MerchandiseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private BigDecimal price;
private String brand;
public MerchandiseEntity() {
}
public MerchandiseEntity(String title, BigDecimal price) {
this.title = title;
this.price = price;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) { | this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "MerchandiseEntity{" +
"id=" + id +
", title='" + title + '\'' +
", price=" + price +
", brand='" + brand + '\'' +
'}';
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\boot\domain\MerchandiseEntity.java | 2 |
请完成以下Java代码 | public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
public void invoke(FilterInvocation filterInvocation) throws IOException, ServletException {
if (isApplied(filterInvocation) && this.observeOncePerRequest) {
// filter already applied to this request and user wants us to observe
// once-per-request handling, so don't re-do security checking
filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());
return;
}
// first time this request being called, so perform security checking
if (filterInvocation.getRequest() != null && this.observeOncePerRequest) {
filterInvocation.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE);
}
InterceptorStatusToken token = super.beforeInvocation(filterInvocation);
try {
filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());
}
finally {
super.finallyInvocation(token);
}
super.afterInvocation(token, null);
}
private boolean isApplied(FilterInvocation filterInvocation) {
return (filterInvocation.getRequest() != null)
&& (filterInvocation.getRequest().getAttribute(FILTER_APPLIED) != null);
}
/**
* Indicates whether once-per-request handling will be observed. By default this is
* <code>true</code>, meaning the <code>FilterSecurityInterceptor</code> will only
* execute once-per-request. Sometimes users may wish it to execute more than once per | * request, such as when JSP forwards are being used and filter security is desired on
* each included fragment of the HTTP request.
* @return <code>true</code> (the default) if once-per-request is honoured, otherwise
* <code>false</code> if <code>FilterSecurityInterceptor</code> will enforce
* authorizations for each and every fragment of the HTTP request.
*/
public boolean isObserveOncePerRequest() {
return this.observeOncePerRequest;
}
public void setObserveOncePerRequest(boolean observeOncePerRequest) {
this.observeOncePerRequest = observeOncePerRequest;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\intercept\FilterSecurityInterceptor.java | 1 |
请完成以下Java代码 | public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("id", this.id);
persistentState.put("type", this.type);
if (this.userId != null) {
persistentState.put("userId", this.userId);
}
if (this.groupId != null) {
persistentState.put("groupId", this.groupId);
}
if (this.taskId != null) {
persistentState.put("taskId", this.taskId);
}
if (this.processInstanceId != null) {
persistentState.put("processInstanceId", this.processInstanceId);
}
if (this.details != null) {
persistentState.put("details", this.details);
}
return persistentState;
}
public boolean isUser() {
return userId != null;
}
public boolean isGroup() {
return groupId != null;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
if (this.groupId != null && userId != null) {
throw new ActivitiException("Cannot assign a userId to a task assignment that already has a groupId");
}
this.userId = userId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) { | if (this.userId != null && groupId != null) {
throw new ActivitiException("Cannot assign a groupId to a task assignment that already has a userId");
}
this.groupId = groupId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public byte[] getDetails() {
return this.details;
}
public void setDetails(byte[] details) {
this.details = details;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntityImpl.java | 1 |
请完成以下Java代码 | public int getA_Asset_Info_Ins_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Info_Ins_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Info_Ins_ID()));
}
/** Set Insurance Premium.
@param A_Ins_Premium Insurance Premium */
public void setA_Ins_Premium (BigDecimal A_Ins_Premium)
{
set_Value (COLUMNNAME_A_Ins_Premium, A_Ins_Premium);
}
/** Get Insurance Premium.
@return Insurance Premium */
public BigDecimal getA_Ins_Premium ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Ins_Premium);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Insurance Company.
@param A_Insurance_Co Insurance Company */
public void setA_Insurance_Co (String A_Insurance_Co)
{
set_Value (COLUMNNAME_A_Insurance_Co, A_Insurance_Co);
}
/** Get Insurance Company.
@return Insurance Company */
public String getA_Insurance_Co ()
{
return (String)get_Value(COLUMNNAME_A_Insurance_Co);
}
/** Set Insured Value.
@param A_Ins_Value Insured Value */
public void setA_Ins_Value (BigDecimal A_Ins_Value)
{
set_Value (COLUMNNAME_A_Ins_Value, A_Ins_Value);
}
/** Get Insured Value.
@return Insured Value */
public BigDecimal getA_Ins_Value ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Ins_Value);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Policy Number.
@param A_Policy_No Policy Number */
public void setA_Policy_No (String A_Policy_No)
{
set_Value (COLUMNNAME_A_Policy_No, A_Policy_No);
}
/** Get Policy Number. | @return Policy Number */
public String getA_Policy_No ()
{
return (String)get_Value(COLUMNNAME_A_Policy_No);
}
/** Set Policy Renewal Date.
@param A_Renewal_Date Policy Renewal Date */
public void setA_Renewal_Date (Timestamp A_Renewal_Date)
{
set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date);
}
/** Get Policy Renewal Date.
@return Policy Renewal Date */
public Timestamp getA_Renewal_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date);
}
/** Set Replacement Costs.
@param A_Replace_Cost Replacement Costs */
public void setA_Replace_Cost (BigDecimal A_Replace_Cost)
{
set_Value (COLUMNNAME_A_Replace_Cost, A_Replace_Cost);
}
/** Get Replacement Costs.
@return Replacement Costs */
public BigDecimal getA_Replace_Cost ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Replace_Cost);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Ins.java | 1 |
请完成以下Java代码 | private IReportServer getServer()
{
return serverSupplier.get();
}
private IReportServer createReportServer()
{
final String serverClassname = Services.get(ISysConfigBL.class).getValue(SYSCONFIG_ReportsServerClass, SYSCONFIG_ReportsServerClass_DEFAULT);
logger.info("Reports server classname: {}", serverClassname);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
{
classLoader = getClass().getClassLoader();
}
try
{
final IReportServer server = (IReportServer)classLoader
.loadClass(serverClassname)
.newInstance();
logger.info("Reports server instance: {}", server);
return server;
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException e)
{
throw new AdempiereException("Reports server class with name " + serverClassname + " could not be instantated", e)
.appendParametersToMessage()
.setParameter("jrClassname", serverClassname)
.setParameter("classLoader", classLoader);
}
}
/**
* Extracts reporting language from given {@link ProcessInfo}.
*
* @return Language; never returns null
* @implNote Usually the ProcessInfo already has the language set, so this method is just a fallback.
* If you are thinking to extend how the reporting language is fetched, please check {@link ProcessInfoBuilder}'s getReportLanguage() method.
*/
private static Language extractLanguage(final ProcessInfo pi)
{
//
// Get Language from ProcessInfo, if any (08023)
Language lang = pi.getReportLanguage();
if (lang != null)
{
return lang; | }
// task 09740
// In case the report is not linked to a window but it has C_BPartner_ID as parameter and it is set, take the language of that bpartner
// TODO: i think this one is no longer needed because we already checking this case in ProcessInfo.findReportingLanguage()
if (lang == null)
{
final IRangeAwareParams parameterAsIParams = pi.getParameterAsIParams();
final int bPartnerID = parameterAsIParams.getParameterAsInt(I_C_BPartner.COLUMNNAME_C_BPartner_ID, -1);
if (bPartnerID > 0)
{
lang = Services.get(IBPartnerBL.class).getLanguage(pi.getCtx(), bPartnerID);
return lang;
}
}
//
// Get Organization Language if any (03040)
if (null == lang)
{
lang = Services.get(ILanguageBL.class).getOrgLanguage(pi.getCtx(), pi.getAD_Org_ID());
}
// If we got an Language already, return it
if (null != lang)
{
return lang;
}
//
// Fallback: get it from client context
return Env.getLanguage(Env.getCtx());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\de.metas.report.jasper.client\src\main\java\de\metas\report\client\ReportsClient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return JPA_VERSION;
} | @Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
transformers.add(transformer);
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\hibernate\jpabootstrap\config\HibernatePersistenceUnitInfo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RfqQty extends AbstractSyncConfirmAwareEntity
{
/* package */static final String TABLE_NAME = "rfq_qty";
@ManyToOne(fetch = FetchType.LAZY)
@NonNull
@Setter
private Rfq rfq;
@NonNull
private java.sql.Date datePromised;
@NonNull
@Getter
private BigDecimal qtyPromised = BigDecimal.ZERO;
@NonNull
@Getter
private BigDecimal qtyPromisedUserEntered = BigDecimal.ZERO;
protected RfqQty() {}
@Builder
private RfqQty(
@NonNull final Rfq rfq,
@NonNull final LocalDate datePromised)
{
this.rfq = rfq;
this.datePromised = DateUtils.toSqlDate(datePromised);
}
@Override
protected void toString(final MoreObjects.ToStringHelper toStringHelper)
{
toStringHelper
.add("datePromised", datePromised)
.add("qtyPromisedUserEntered", qtyPromisedUserEntered)
.add("qtyPromised", qtyPromised);
}
public LocalDate getDatePromised() | {
return DateUtils.toLocalDate(datePromised);
}
public void setQtyPromisedUserEntered(@NonNull final BigDecimal qtyPromisedUserEntered)
{
this.qtyPromisedUserEntered = qtyPromisedUserEntered;
}
public boolean isConfirmedByUser()
{
return getQtyPromised().compareTo(getQtyPromisedUserEntered()) == 0;
}
public void confirmByUser()
{
this.qtyPromised = getQtyPromisedUserEntered();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\RfqQty.java | 2 |
请完成以下Java代码 | public class GeodeBindingsPropertiesProcessor implements BindingsPropertiesProcessor {
public static final String TYPE = "gemfire";
/**
* @inheritDoc
*/
@Override
public void process(@NonNull Environment environment, @NonNull Bindings bindings,
@NonNull Map<String, Object> properties) {
if (Guards.isTypeEnabled(environment, TYPE)) {
bindings.filterBindings(TYPE).forEach(binding -> {
// TODO - Change! Current mappings and property configuration is based on VMware Tanzu GemFire for VMS | // (i.e. PCC in PCF).
MapMapper mapMapper = new MapMapper(binding.getSecret(), properties);
mapMapper.from("gemfire.security-username").to("spring.data.gemfire.security.username");
mapMapper.from("gemfire.security-password").to("spring.data.gemfire.security.password");
mapMapper.from("gemfire.locators").to("spring.data.gemfire.pool.locators");
mapMapper.from("gemfire.http-service-bind-address").to("spring.data.gemfire.management.http.host");
mapMapper.from("gemfire.http-service-port").to("spring.data.gemfire.management.http.port");
properties.put("spring.data.gemfire.management.require-https", true);
properties.put("spring.data.gemfire.management.use-http", true);
properties.put("spring.data.gemfire.security.ssl.use-default-context", true);
});
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-cloud\src\main\java\org\springframework\geode\cloud\bindings\boot\GeodeBindingsPropertiesProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultTbMobileAppBundleService extends AbstractTbEntityService implements TbMobileAppBundleService {
private final MobileAppBundleService mobileAppBundleService;
@Override
public MobileAppBundle save(MobileAppBundle mobileAppBundle, List<OAuth2ClientId> oauth2Clients, User user) throws Exception {
ActionType actionType = mobileAppBundle.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = mobileAppBundle.getTenantId();
try {
MobileAppBundle savedMobileAppBundle = checkNotNull(mobileAppBundleService.saveMobileAppBundle(tenantId, mobileAppBundle));
if (CollectionUtils.isNotEmpty(oauth2Clients)) {
mobileAppBundleService.updateOauth2Clients(tenantId, savedMobileAppBundle.getId(), oauth2Clients);
}
logEntityActionService.logEntityAction(tenantId, savedMobileAppBundle.getId(), savedMobileAppBundle, actionType, user);
return savedMobileAppBundle;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.MOBILE_APP), mobileAppBundle, actionType, user, e);
throw e;
}
}
@Override
public void updateOauth2Clients(MobileAppBundle mobileAppBundle, List<OAuth2ClientId> oAuth2ClientIds, User user) {
ActionType actionType = ActionType.UPDATED;
TenantId tenantId = mobileAppBundle.getTenantId();
MobileAppBundleId mobileAppBundleId = mobileAppBundle.getId();
try {
mobileAppBundleService.updateOauth2Clients(tenantId, mobileAppBundleId, oAuth2ClientIds);
logEntityActionService.logEntityAction(tenantId, mobileAppBundleId, mobileAppBundle, actionType, user, oAuth2ClientIds);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, mobileAppBundleId, mobileAppBundle, actionType, user, e, oAuth2ClientIds); | throw e;
}
}
@Override
public void delete(MobileAppBundle mobileAppBundle, User user) {
ActionType actionType = ActionType.DELETED;
TenantId tenantId = mobileAppBundle.getTenantId();
MobileAppBundleId mobileAppBundleId = mobileAppBundle.getId();
try {
mobileAppBundleService.deleteMobileAppBundleById(tenantId, mobileAppBundleId);
logEntityActionService.logEntityAction(tenantId, mobileAppBundleId, mobileAppBundle, actionType, user);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, mobileAppBundleId, mobileAppBundle, actionType, user, e);
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\mobile\DefaultTbMobileAppBundleService.java | 2 |
请完成以下Java代码 | public void resume(String listenerId) {
Assert.notNull(this.registry, "Resume by id is only supported when a registry is provided");
getListenerContainer(listenerId).ifPresent(this::resume);
}
/**
* Resume the listener container.
* @param messageListenerContainer the listener container
*/
public void resume(MessageListenerContainer messageListenerContainer) {
if (messageListenerContainer.isPauseRequested()) {
LOGGER.debug(() -> "Resuming container " + messageListenerContainer);
messageListenerContainer.resume();
}
else {
LOGGER.debug(() -> "Container " + messageListenerContainer + " was not paused");
} | }
/*
* Callers must ensure this.registry is not null before calling.
*/
private Optional<MessageListenerContainer> getListenerContainer(String listenerId) {
MessageListenerContainer messageListenerContainer = Objects.requireNonNull(this.registry).getListenerContainer(listenerId); // NOSONAR
if (messageListenerContainer == null) {
LOGGER.warn(() -> "MessageListenerContainer " + listenerId + " does not exists");
}
return Optional.ofNullable(messageListenerContainer);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ListenerContainerPauseService.java | 1 |
请完成以下Spring Boot application配置 | # dubbo 配置项,对应 DubboConfigurationProperties 配置类
dubbo:
# Dubbo 应用配置
application:
name: user-service-consumer # 应用名
# Dubbo 注册中心配置
registry:
address: zookeeper://127.0.0.1:2181 # 注册中心地址。个鞥多注册中心,可见 http://dubbo.apache.org/zh-cn/docs/user/references/registry/introduction.html 文档。
# D | ubbo 消费者配置
consumer:
timeout: 1000 # 【重要】远程服务调用超时时间,单位:毫秒。默认为 1000 毫秒,胖友可以根据自己业务修改
UserRpcService:
version: 1.0.0 | repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-annotations-demo\user-rpc-service-consumer-02\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | private List<DocumentLayoutElementGroupDescriptor> buildElementGroups()
{
return elementGroupsBuilders
.stream()
.map(DocumentLayoutElementGroupDescriptor.Builder::build)
.filter(this::checkValid)
.collect(GuavaCollectors.toImmutableList());
}
private boolean checkValid(final DocumentLayoutElementGroupDescriptor elementGroup)
{
if(!elementGroup.hasElementLines())
{
logger.trace("Skip adding {} to {} because it does not have element line", elementGroup, this);
return false;
}
return true;
}
public Builder setInternalName(String internalName)
{
this.internalName = internalName; | return this;
}
public Builder addElementGroups(@NonNull final List<DocumentLayoutElementGroupDescriptor.Builder> elementGroupBuilders)
{
elementGroupsBuilders.addAll(elementGroupBuilders);
return this;
}
public Builder addElementGroup(@NonNull final DocumentLayoutElementGroupDescriptor.Builder elementGroupBuilder)
{
elementGroupsBuilders.add(elementGroupBuilder);
return this;
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementGroupsBuilders.stream().flatMap(DocumentLayoutElementGroupDescriptor.Builder::streamElementBuilders);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutColumnDescriptor.java | 1 |
请完成以下Java代码 | public class RuleChainActor extends RuleEngineComponentActor<RuleChainId, RuleChainActorMessageProcessor> {
private final RuleChain ruleChain;
private RuleChainActor(ActorSystemContext systemContext, TenantId tenantId, RuleChain ruleChain) {
super(systemContext, tenantId, ruleChain.getId());
this.ruleChain = ruleChain;
}
@Override
protected RuleChainActorMessageProcessor createProcessor(TbActorCtx ctx) {
return new RuleChainActorMessageProcessor(tenantId, ruleChain, systemContext,
ctx.getParentRef(), ctx);
}
@Override
protected boolean doProcess(TbActorMsg msg) {
switch (msg.getMsgType()) {
case COMPONENT_LIFE_CYCLE_MSG:
onComponentLifecycleMsg((ComponentLifecycleMsg) msg);
break;
case QUEUE_TO_RULE_ENGINE_MSG:
processor.onQueueToRuleEngineMsg((QueueToRuleEngineMsg) msg);
break;
case RULE_TO_RULE_CHAIN_TELL_NEXT_MSG:
processor.onTellNext((RuleNodeToRuleChainTellNextMsg) msg);
break;
case RULE_CHAIN_TO_RULE_CHAIN_MSG:
processor.onRuleChainToRuleChainMsg((RuleChainToRuleChainMsg) msg);
break;
case RULE_CHAIN_INPUT_MSG:
processor.onRuleChainInputMsg((RuleChainInputMsg) msg);
break;
case RULE_CHAIN_OUTPUT_MSG:
processor.onRuleChainOutputMsg((RuleChainOutputMsg) msg);
break;
case PARTITION_CHANGE_MSG:
processor.onPartitionChangeMsg((PartitionChangeMsg) msg);
break;
case STATS_PERSIST_TICK_MSG:
onStatsPersistTick(id);
break;
default:
return false;
}
return true;
}
public static class ActorCreator extends ContextBasedCreator {
private static final long serialVersionUID = 1L;
private final TenantId tenantId;
private final RuleChain ruleChain;
public ActorCreator(ActorSystemContext context, TenantId tenantId, RuleChain ruleChain) {
super(context);
this.tenantId = tenantId;
this.ruleChain = ruleChain; | }
@Override
public TbActorId createActorId() {
return new TbEntityActorId(ruleChain.getId());
}
@Override
public TbActor createActor() {
return new RuleChainActor(context, tenantId, ruleChain);
}
}
@Override
protected RuleChainId getRuleChainId() {
return ruleChain.getId();
}
@Override
protected String getRuleChainName() {
return ruleChain.getName();
}
@Override
protected long getErrorPersistFrequency() {
return systemContext.getRuleChainErrorPersistFrequency();
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleChainActor.java | 1 |
请完成以下Java代码 | public class Milestone extends PlanItemDefinition {
protected Integer displayOrder;
protected String includeInStageOverview;
protected String milestoneVariable;
protected String businessStatus;
public Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
public String getIncludeInStageOverview() {
return includeInStageOverview;
}
public void setIncludeInStageOverview(String includeInStageOverview) {
this.includeInStageOverview = includeInStageOverview;
} | public String getMilestoneVariable() {
return milestoneVariable;
}
public void setMilestoneVariable(String milestoneVariable) {
this.milestoneVariable = milestoneVariable;
}
public String getBusinessStatus() {
return businessStatus;
}
public void setBusinessStatus(String businessStatus) {
this.businessStatus = businessStatus;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Milestone.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UnitType getQuantityVariances() {
return quantityVariances;
}
/**
* Sets the value of the quantityVariances property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setQuantityVariances(UnitType value) {
this.quantityVariances = value;
}
/**
* Gets the value of the variancesReasonCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVariancesReasonCode() {
return variancesReasonCode;
}
/**
* Sets the value of the variancesReasonCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVariancesReasonCode(String value) { | this.variancesReasonCode = value;
}
/**
* Gets the value of the contractReference property.
*
* @return
* possible object is
* {@link ReferenceType }
*
*/
public ReferenceType getContractReference() {
return contractReference;
}
/**
* Sets the value of the contractReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setContractReference(ReferenceType value) {
this.contractReference = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\RECADVListLineItemExtensionType.java | 2 |
请完成以下Java代码 | public class ActivitiEventListenerValidator extends ProcessLevelValidator {
@Override
protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) {
List<EventListener> eventListeners = process.getEventListeners();
if (eventListeners != null) {
for (EventListener eventListener : eventListeners) {
if (
eventListener.getImplementationType() != null &&
eventListener
.getImplementationType()
.equals(ImplementationType.IMPLEMENTATION_TYPE_INVALID_THROW_EVENT)
) {
addError(errors, Problems.EVENT_LISTENER_INVALID_THROW_EVENT_TYPE, process, eventListener);
} else if (
eventListener.getImplementationType() == null || eventListener.getImplementationType().length() == 0
) {
addError(errors, Problems.EVENT_LISTENER_IMPLEMENTATION_MISSING, process, eventListener);
} else if (eventListener.getImplementationType() != null) {
if (
!ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(eventListener.getImplementationType()) &&
!ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(
eventListener.getImplementationType()
) && | !ImplementationType.IMPLEMENTATION_TYPE_THROW_SIGNAL_EVENT.equals(
eventListener.getImplementationType()
) &&
!ImplementationType.IMPLEMENTATION_TYPE_THROW_GLOBAL_SIGNAL_EVENT.equals(
eventListener.getImplementationType()
) &&
!ImplementationType.IMPLEMENTATION_TYPE_THROW_MESSAGE_EVENT.equals(
eventListener.getImplementationType()
) &&
!ImplementationType.IMPLEMENTATION_TYPE_THROW_ERROR_EVENT.equals(
eventListener.getImplementationType()
)
) {
addError(errors, Problems.EVENT_LISTENER_INVALID_IMPLEMENTATION, process, eventListener);
}
}
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\ActivitiEventListenerValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private final class SyncAfterCommit implements TransactionSynchronization, ISyncAfterCommitCollector
{
private final ArrayList<ProductSupply> productSupplies = new ArrayList<>();
private final ArrayList<WeekSupply> weeklySupplies = new ArrayList<>();
private final ArrayList<Rfq> rfqs = new ArrayList<>();
private final ArrayList<User> users = new ArrayList<>();
@Override
public ISyncAfterCommitCollector add(@NonNull final ProductSupply productSupply)
{
createAndStoreSyncConfirmRecord(productSupply);
productSupplies.add(productSupply);
logger.debug("Enqueued {}", productSupply);
return this;
}
@Override
public ISyncAfterCommitCollector add(@NonNull final WeekSupply weeklySupply)
{
createAndStoreSyncConfirmRecord(weeklySupply);
weeklySupplies.add(weeklySupply);
return this;
}
@Override
public ISyncAfterCommitCollector add(@NonNull final Rfq rfq)
{
createAndStoreSyncConfirmRecord(rfq);
rfqs.add(rfq);
return this;
}
@Override
public ISyncAfterCommitCollector add(@NonNull final User user)
{
users.add(user);
return this;
}
/**
* Creates a new local DB record for the given <code>abstractEntity</code>.
*/
private void createAndStoreSyncConfirmRecord(final AbstractSyncConfirmAwareEntity abstractEntity)
{
final SyncConfirm syncConfirmRecord = new SyncConfirm();
syncConfirmRecord.setEntryType(abstractEntity.getClass().getSimpleName());
syncConfirmRecord.setEntryUuid(abstractEntity.getUuid());
syncConfirmRecord.setEntryId(abstractEntity.getId());
syncConfirmRepo.save(syncConfirmRecord);
abstractEntity.setSyncConfirmId(syncConfirmRecord.getId());
}
@Override
public void afterCommit()
{
publishToMetasfreshAsync();
}
public void publishToMetasfreshAsync()
{
logger.debug("Synchronizing: {}", this);
//
// Sync daily product supplies | {
final List<ProductSupply> productSupplies = ImmutableList.copyOf(this.productSupplies);
this.productSupplies.clear();
pushDailyReportsAsync(productSupplies);
}
//
// Sync weekly product supplies
{
final List<WeekSupply> weeklySupplies = ImmutableList.copyOf(this.weeklySupplies);
this.weeklySupplies.clear();
pushWeeklyReportsAsync(weeklySupplies);
}
//
// Sync RfQ changes
{
final List<Rfq> rfqs = ImmutableList.copyOf(this.rfqs);
this.rfqs.clear();
pushRfqsAsync(rfqs);
}
//
// Sync User changes
{
final List<User> users = ImmutableList.copyOf(this.users);
this.users.clear();
pushUsersAsync(users);
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SenderToMetasfreshService.java | 2 |
请完成以下Java代码 | public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getC_Prepayment_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getC_Prepayment_Acct(), get_TrxName()); }
/** Set Customer Prepayment.
@param C_Prepayment_Acct
Account for customer prepayments
*/
public void setC_Prepayment_Acct (int C_Prepayment_Acct)
{
set_Value (COLUMNNAME_C_Prepayment_Acct, Integer.valueOf(C_Prepayment_Acct));
}
/** Get Customer Prepayment.
@return Account for customer prepayments
*/
public int getC_Prepayment_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Prepayment_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getC_Receivable_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getC_Receivable_Acct(), get_TrxName()); }
/** Set Customer Receivables.
@param C_Receivable_Acct
Account for Customer Receivables | */
public void setC_Receivable_Acct (int C_Receivable_Acct)
{
set_Value (COLUMNNAME_C_Receivable_Acct, Integer.valueOf(C_Receivable_Acct));
}
/** Get Customer Receivables.
@return Account for Customer Receivables
*/
public int getC_Receivable_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Receivable_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getC_Receivable_Services_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getC_Receivable_Services_Acct(), get_TrxName()); }
/** Set Receivable Services.
@param C_Receivable_Services_Acct
Customer Accounts Receivables Services Account
*/
public void setC_Receivable_Services_Acct (int C_Receivable_Services_Acct)
{
set_Value (COLUMNNAME_C_Receivable_Services_Acct, Integer.valueOf(C_Receivable_Services_Acct));
}
/** Get Receivable Services.
@return Customer Accounts Receivables Services Account
*/
public int getC_Receivable_Services_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Receivable_Services_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_BP_Customer_Acct.java | 1 |
请完成以下Java代码 | public List<IdentityLinkEntity> findIdentityLinkByProcessDefinitionUserAndGroup(String processDefinitionId, String userId, String groupId) {
Map<String, String> parameters = new HashMap<>();
parameters.put("processDefinitionId", processDefinitionId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
return getDbSqlSession().selectList("selectIdentityLinkByProcessDefinitionUserAndGroup", parameters);
}
public void deleteIdentityLinksByTaskId(String taskId) {
List<IdentityLinkEntity> identityLinks = findIdentityLinksByTaskId(taskId);
for (IdentityLinkEntity identityLink : identityLinks) {
deleteIdentityLink(identityLink, false);
}
}
public void deleteIdentityLinksByProcInstance(String processInstanceId) {
// Identity links from db
List<IdentityLinkEntity> identityLinks = findIdentityLinksByProcessInstanceId(processInstanceId);
// Delete
for (IdentityLinkEntity identityLink : identityLinks) {
deleteIdentityLink(identityLink, false);
}
// Identity links from cache, if not already deleted | List<IdentityLinkEntity> identityLinksFromCache = Context.getCommandContext().getDbSqlSession().findInCache(IdentityLinkEntity.class);
boolean alreadyDeleted = false;
for (IdentityLinkEntity identityLinkEntity : identityLinksFromCache) {
if (processInstanceId.equals(identityLinkEntity.getProcessInstanceId())) {
alreadyDeleted = false;
for (IdentityLinkEntity deleted : identityLinks) {
if (deleted.getId() != null && deleted.getId().equals(identityLinkEntity.getId())) {
alreadyDeleted = true;
break;
}
}
if (!alreadyDeleted) {
deleteIdentityLink(identityLinkEntity, false);
}
}
}
}
public void deleteIdentityLinksByProcDef(String processDefId) {
getDbSqlSession().delete("deleteIdentityLinkByProcDef", processDefId);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntityManager.java | 1 |
请完成以下Java代码 | protected class QueryServiceRowCountCmd implements Command<Long> {
protected String statement;
protected ListQueryParameterObject parameter;
public QueryServiceRowCountCmd(String statement, ListQueryParameterObject parameter) {
this.statement = statement;
this.parameter = parameter;
}
@Override
public Long execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl engineConfig = getProcessEngineConfiguration(commandContext);
configureAuthCheck(parameter, engineConfig, commandContext);
return (Long) commandContext.getDbSqlSession().selectOne(statement, parameter);
}
}
protected class ExecuteListQueryCmd<T> implements Command<List<T>> {
protected String statement;
protected QueryParameters parameter;
public ExecuteListQueryCmd(String statement, QueryParameters parameter) {
this.statement = statement;
this.parameter = parameter;
}
@Override
public List<T> execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl engineConfig = getProcessEngineConfiguration(commandContext);
configureAuthCheck(parameter, engineConfig, commandContext);
if (parameter.isMaxResultsLimitEnabled()) {
QueryMaxResultsLimitUtil.checkMaxResultsLimit(parameter.getMaxResults(), engineConfig);
} | return (List<T>) commandContext.getDbSqlSession().selectList(statement, parameter);
}
}
protected class ExecuteSingleQueryCmd<T> implements Command<T> {
protected String statement;
protected Object parameter;
protected Class clazz;
public <T> ExecuteSingleQueryCmd(String statement, Object parameter, Class<T> clazz) {
this.statement = statement;
this.parameter = parameter;
this.clazz = clazz;
}
@Override
public T execute(CommandContext commandContext) {
return (T) commandContext.getDbSqlSession().selectOne(statement, parameter);
}
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\db\QueryServiceImpl.java | 1 |
请完成以下Java代码 | private Document getParentDocument()
{
return _parentDocument;
}
private DocumentPath getDocumentPath()
{
if (_documentPath == null)
{
final DocumentEntityDescriptor entityDescriptor = getEntityDescriptor();
final DocumentId documentId = getDocumentId();
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
_documentPath = DocumentPath.rootDocumentPath(entityDescriptor.getDocumentType(), entityDescriptor.getDocumentTypeId(), documentId);
}
else
{
_documentPath = parentDocument.getDocumentPath().createChildPath(entityDescriptor.getDetailId(), documentId);
}
}
return _documentPath;
}
private int getWindowNo()
{
if (_windowNo == null)
{
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
_windowNo = _nextWindowNo.incrementAndGet();
}
else
{
_windowNo = parentDocument.getWindowNo();
}
}
return _windowNo;
}
private boolean isWritable() | {
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
return isNewDocument();
}
else
{
return parentDocument.isWritable();
}
}
private ReentrantReadWriteLock createLock()
{
// don't create locks for any other entity which is not window
final DocumentEntityDescriptor entityDescriptor = getEntityDescriptor();
if (entityDescriptor.getDocumentType() != DocumentType.Window)
{
return null;
}
//
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
return new ReentrantReadWriteLock();
}
else
{
// don't create lock for included documents
return null;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\Document.java | 1 |
请完成以下Java代码 | public class ResourceParameterBindingImpl extends BaseElementImpl implements ResourceParameterBinding {
protected static AttributeReference<ResourceParameter> parameterRefAttribute;
protected static ChildElement<Expression> expressionChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ResourceParameterBinding.class, BPMN_ELEMENT_RESOURCE_PARAMETER_BINDING)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ResourceParameterBinding>() {
public ResourceParameterBinding newInstance(ModelTypeInstanceContext instanceContext) {
return new ResourceParameterBindingImpl(instanceContext);
}
});
parameterRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_PARAMETER_REF)
.required()
.qNameAttributeReference(ResourceParameter.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
expressionChild = sequenceBuilder.element(Expression.class)
.required() | .build();
typeBuilder.build();
}
public ResourceParameterBindingImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public ResourceParameter getParameter() {
return parameterRefAttribute.getReferenceTargetElement(this);
}
public void setParameter(ResourceParameter parameter) {
parameterRefAttribute.setReferenceTargetElement(this, parameter);
}
public Expression getExpression() {
return expressionChild.getChild(this);
}
public void setExpression(Expression expression) {
expressionChild.setChild(this, expression);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ResourceParameterBindingImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static void putIfNotNull(ObjectNode map, String key, Date value) {
if (value != null) {
map.put(key, AsyncHistoryDateUtil.formatDate(value));
}
}
public static void putIfNotNull(Map<String, String> map, String key, Boolean value) {
if (value != null) {
map.put(key, Boolean.toString(value));
}
}
public static void putIfNotNull(ObjectNode map, String key, Boolean value) {
if (value != null) {
map.put(key, value);
}
}
public static String convertToBase64(VariableInstanceEntity variable) {
byte[] bytes = variable.getBytes();
if (bytes != null) {
return new String(Base64.getEncoder().encode(variable.getBytes()), StandardCharsets.US_ASCII);
} else {
return null;
}
}
public static String getStringFromJson(ObjectNode objectNode, String fieldName) {
if (objectNode.has(fieldName)) {
return objectNode.get(fieldName).asString();
}
return null;
}
public static Date getDateFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName);
return AsyncHistoryDateUtil.parseDate(s);
}
public static Integer getIntegerFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName);
if (StringUtils.isNotEmpty(s)) {
return Integer.valueOf(s);
}
return null;
}
public static Double getDoubleFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName); | if (StringUtils.isNotEmpty(s)) {
return Double.valueOf(s);
}
return null;
}
public static Long getLongFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName);
if (StringUtils.isNotEmpty(s)) {
return Long.valueOf(s);
}
return null;
}
public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName, Boolean defaultValue) {
Boolean value = getBooleanFromJson(objectNode, fieldName);
return value != null ? value : defaultValue;
}
public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName);
if (StringUtils.isNotEmpty(s)) {
return Boolean.valueOf(s);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\history\async\util\AsyncHistoryJsonUtil.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ListenableFuture<ReclaimResult> reClaimDevice(TenantId tenantId, Device device) {
if (!device.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
cacheEviction(device.getId());
Customer unassignedCustomer = customerService.findCustomerById(tenantId, device.getCustomerId());
device.setCustomerId(null);
Device savedDevice = deviceService.saveDevice(device);
if (isAllowedClaimingByDefault) {
return Futures.immediateFuture(new ReclaimResult(unassignedCustomer));
}
SettableFuture<ReclaimResult> result = SettableFuture.create();
telemetryService.saveAttributes(AttributesSaveRequest.builder()
.tenantId(tenantId)
.entityId(savedDevice.getId())
.scope(AttributeScope.SERVER_SCOPE)
.entry(new BooleanDataEntry(CLAIM_ATTRIBUTE_NAME, true))
.callback(new FutureCallback<>() {
@Override
public void onSuccess(@Nullable Void tmp) {
result.set(new ReclaimResult(unassignedCustomer));
}
@Override
public void onFailure(Throwable t) {
result.setException(t);
}
})
.build());
return result;
}
cacheEviction(device.getId());
return Futures.immediateFuture(new ReclaimResult(null));
}
private List<Object> constructCacheKey(DeviceId deviceId) {
return List.of(deviceId);
}
private void persistInCache(String secretKey, long durationMs, Cache cache, List<Object> key) {
ClaimData claimData = new ClaimData(secretKey, | System.currentTimeMillis() + validateDurationMs(durationMs));
cache.putIfAbsent(key, claimData);
}
private long validateDurationMs(long durationMs) {
if (durationMs > 0L) {
return durationMs;
}
return systemDurationMs;
}
private ListenableFuture<Void> removeClaimingSavedData(Cache cache, ClaimDataInfo data, Device device) {
if (data.isFromCache()) {
cache.evict(data.getKey());
}
SettableFuture<Void> result = SettableFuture.create();
telemetryService.deleteAttributes(AttributesDeleteRequest.builder()
.tenantId(device.getTenantId())
.entityId(device.getId())
.scope(AttributeScope.SERVER_SCOPE)
.keys(Arrays.asList(CLAIM_ATTRIBUTE_NAME, CLAIM_DATA_ATTRIBUTE_NAME))
.future(result)
.build());
return result;
}
private void cacheEviction(DeviceId deviceId) {
Cache cache = cacheManager.getCache(CLAIM_DEVICES_CACHE);
cache.evict(constructCacheKey(deviceId));
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\device\ClaimDevicesServiceImpl.java | 2 |
请完成以下Java代码 | public @Nullable Integer getActive() {
return getDataSource().getNumActive();
}
@Override
public @Nullable Integer getIdle() {
return getDataSource().getNumIdle();
}
@Override
public @Nullable Integer getMax() {
return getDataSource().getMaxTotal();
}
@Override | public @Nullable Integer getMin() {
return getDataSource().getMinIdle();
}
@Override
public @Nullable String getValidationQuery() {
return getDataSource().getValidationQuery();
}
@Override
public @Nullable Boolean getDefaultAutoCommit() {
return getDataSource().getDefaultAutoCommit();
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\CommonsDbcp2DataSourcePoolMetadata.java | 1 |
请完成以下Java代码 | public static DocumentFieldWidgetType extractWidgetType(
final String columnName,
final int displayType,
@NonNull final Optional<LookupDescriptor> lookupDescriptor)
{
final DocumentFieldWidgetType widgetType = extractWidgetType(columnName, displayType);
if (lookupDescriptor.isPresent()
&& (widgetType == DocumentFieldWidgetType.List || widgetType == DocumentFieldWidgetType.Lookup))
{
final LookupSource lookupSourceType = lookupDescriptor.get().getLookupSourceType();
final DocumentFieldWidgetType lookupWidgetType = extractWidgetType(lookupSourceType);
if (lookupWidgetType != widgetType)
{
logger.warn("Inconsistent '{}/{}'({}) vs '{}'({}). Considering the widgetType provided by lookupSourceType." //
, columnName, displayType, widgetType //
, lookupSourceType, lookupWidgetType);
}
return lookupWidgetType;
}
return widgetType;
}
private static DocumentFieldWidgetType extractWidgetType(final DocumentLayoutElementFieldDescriptor.LookupSource lookupSource)
{
Check.assumeNotNull(lookupSource, "Parameter lookupSource is not null");
switch (lookupSource)
{
case list:
return DocumentFieldWidgetType.List;
case lookup:
return DocumentFieldWidgetType.Lookup;
default:
throw new AdempiereException("LookupSource " + lookupSource + " is not supported");
}
}
public static DocumentLayoutElementFieldDescriptor.LookupSource extractLookupSource(@NonNull final ReferenceId displayType, @Nullable final ReferenceId adReferenceValueId)
{
return extractLookupSource(displayType.getRepoId(), adReferenceValueId);
}
@Nullable
public static DocumentLayoutElementFieldDescriptor.LookupSource extractLookupSource(final int displayType, @Nullable final ReferenceId adReferenceValueId)
{
if (DisplayType.Search == displayType)
{
return DocumentLayoutElementFieldDescriptor.LookupSource.lookup;
}
else if (DisplayType.List == displayType)
{ | return DocumentLayoutElementFieldDescriptor.LookupSource.list;
}
else if (DisplayType.TableDir == displayType)
{
return DocumentLayoutElementFieldDescriptor.LookupSource.list;
}
else if (DisplayType.Table == displayType)
{
return DocumentLayoutElementFieldDescriptor.LookupSource.list;
}
else if (DisplayType.isAnyLookup(displayType))
{
return DocumentLayoutElementFieldDescriptor.LookupSource.lookup;
}
else if (DisplayType.Button == displayType && adReferenceValueId != null)
{
return DocumentLayoutElementFieldDescriptor.LookupSource.list;
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\DescriptorsFactoryHelper.java | 1 |
请完成以下Java代码 | public String getSvcCd() {
return svcCd;
}
/**
* Sets the value of the svcCd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSvcCd(String value) {
this.svcCd = value;
}
/**
* Gets the value of the trckData property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the trckData property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTrckData().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TrackData1 }
*
*
*/
public List<TrackData1> getTrckData() {
if (trckData == null) {
trckData = new ArrayList<TrackData1>();
}
return this.trckData;
}
/**
* Gets the value of the cardSctyCd property. | *
* @return
* possible object is
* {@link CardSecurityInformation1 }
*
*/
public CardSecurityInformation1 getCardSctyCd() {
return cardSctyCd;
}
/**
* Sets the value of the cardSctyCd property.
*
* @param value
* allowed object is
* {@link CardSecurityInformation1 }
*
*/
public void setCardSctyCd(CardSecurityInformation1 value) {
this.cardSctyCd = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PlainCardData1.java | 1 |
请完成以下Java代码 | public String getId() {
return historicProcessInstance.getId();
}
@Override
public String getBusinessKey() {
return historicProcessInstance.getBusinessKey();
}
@Override
public String getProcessDefinitionId() {
return historicProcessInstance.getProcessDefinitionId();
}
@Override
public Date getStartTime() {
return historicProcessInstance.getStartTime();
}
@Override
public Date getEndTime() {
return historicProcessInstance.getEndTime();
}
@Override
public Long getDurationInMillis() {
return historicProcessInstance.getDurationInMillis();
}
@Override
public String getStartUserId() {
return historicProcessInstance.getStartUserId();
}
@Override
public String getStartActivityId() {
return historicProcessInstance.getStartActivityId();
}
@Override | public String getDeleteReason() {
return historicProcessInstance.getDeleteReason();
}
@Override
public String getSuperProcessInstanceId() {
return historicProcessInstance.getSuperProcessInstanceId();
}
@Override
public String getTenantId() {
return historicProcessInstance.getTenantId();
}
@Override
public List<HistoricData> getHistoricData() {
return historicData;
}
public void addHistoricData(HistoricData historicEvent) {
historicData.add(historicEvent);
}
public void addHistoricData(Collection<? extends HistoricData> historicEvents) {
historicData.addAll(historicEvents);
}
public void orderHistoricData() {
Collections.sort(
historicData,
new Comparator<HistoricData>() {
@Override
public int compare(HistoricData data1, HistoricData data2) {
return data1.getTime().compareTo(data2.getTime());
}
}
);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceHistoryLogImpl.java | 1 |
请完成以下Java代码 | void addVertex(String label) {
adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>());
}
void removeVertex(String label) {
Vertex v = new Vertex(label);
adjVertices.values().stream().forEach(e -> e.remove(v));
adjVertices.remove(new Vertex(label));
}
void addEdge(String label1, String label2) {
Vertex v1 = new Vertex(label1);
Vertex v2 = new Vertex(label2);
adjVertices.get(v1).add(v2);
adjVertices.get(v2).add(v1);
}
void removeEdge(String label1, String label2) {
Vertex v1 = new Vertex(label1);
Vertex v2 = new Vertex(label2);
List<Vertex> eV1 = adjVertices.get(v1);
List<Vertex> eV2 = adjVertices.get(v2);
if (eV1 != null)
eV1.remove(v2);
if (eV2 != null)
eV2.remove(v1);
}
List<Vertex> getAdjVertices(String label) {
return adjVertices.get(new Vertex(label));
}
String printGraph() {
StringBuffer sb = new StringBuffer();
for(Vertex v : adjVertices.keySet()) {
sb.append(v);
sb.append(adjVertices.get(v));
}
return sb.toString();
}
class Vertex {
String label; | Vertex(String label) {
this.label = label;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((label == null) ? 0 : label.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;
Vertex other = (Vertex) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
return true;
}
@Override
public String toString() {
return label;
}
private Graph getOuterType() {
return Graph.this;
}
}
} | repos\tutorials-master\data-structures\src\main\java\com\baeldung\graph\Graph.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void updateUser(@PathVariable String id, User user) {
userService.updateUser(id, user);
}
/**
* 根据用户 id查找
* 存在返回,不存在返回 null
*/
@GetMapping("/{id}")
public User getUser(@PathVariable String id) {
return userService.getUser(id).orElse(null);
}
/**
* 根据年龄段来查找
*/
@GetMapping("/age/{from}/{to}")
public List<User> getUserByAge(@PathVariable Integer from, @PathVariable Integer to) {
return userService.getUserByAge(from, to);
}
/**
* 根据用户名查找
*/
@GetMapping("/name/{name}")
public List<User> getUserByName(@PathVariable String name) {
return userService.getUserByName(name);
} | /**
* 根据用户描述模糊查找
*/
@GetMapping("/description/{description}")
public List<User> getUserByDescription(@PathVariable String description) {
return userService.getUserByDescription(description);
}
/**
* 根据多个检索条件查询
*/
@GetMapping("/condition")
public Page<User> getUserByCondition(int size, int page, User user) {
return userService.getUserByCondition(size, page, user);
}
} | repos\SpringAll-master\56.Spring-Boot-MongoDB-crud\src\main\java\com\example\mongodb\controller\UserController.java | 2 |
请完成以下Java代码 | public class IntermediateCatchEventParseHandler extends AbstractFlowNodeBpmnParseHandler<IntermediateCatchEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(IntermediateCatchEventParseHandler.class);
@Override
public Class<? extends BaseElement> getHandledType() {
return IntermediateCatchEvent.class;
}
@Override
protected void executeParse(BpmnParse bpmnParse, IntermediateCatchEvent event) {
ActivityImpl nestedActivity = null;
EventDefinition eventDefinition = null;
if (!event.getEventDefinitions().isEmpty()) {
eventDefinition = event.getEventDefinitions().get(0);
}
if (eventDefinition == null) {
nestedActivity = createActivityOnCurrentScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH);
nestedActivity.setAsync(event.isAsynchronous());
nestedActivity.setExclusive(!event.isNotExclusive());
} else {
ScopeImpl scope = bpmnParse.getCurrentScope();
String eventBasedGatewayId = getPrecedingEventBasedGateway(bpmnParse, event);
if (eventBasedGatewayId != null) {
ActivityImpl gatewayActivity = scope.findActivity(eventBasedGatewayId);
nestedActivity = createActivityOnScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH, gatewayActivity); | } else {
nestedActivity = createActivityOnScope(bpmnParse, event, BpmnXMLConstants.ELEMENT_EVENT_CATCH, scope);
}
nestedActivity.setAsync(event.isAsynchronous());
nestedActivity.setExclusive(!event.isNotExclusive());
// Catch event behavior is the same for all types
nestedActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateCatchEventActivityBehavior(event));
if (eventDefinition instanceof TimerEventDefinition
|| eventDefinition instanceof SignalEventDefinition
|| eventDefinition instanceof MessageEventDefinition) {
bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition);
} else {
LOGGER.warn("Unsupported intermediate catch event type for event {}", event.getId());
}
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\IntermediateCatchEventParseHandler.java | 1 |
请完成以下Java代码 | public ArticleDataList findUserFeed(User user, Page page) {
List<String> followdUsers = userRelationshipQueryService.followedUsers(user.getId());
if (followdUsers.size() == 0) {
return new ArticleDataList(new ArrayList<>(), 0);
} else {
List<ArticleData> articles = articleReadService.findArticlesOfAuthors(followdUsers, page);
fillExtraInfo(articles, user);
int count = articleReadService.countFeedSize(followdUsers);
return new ArticleDataList(articles, count);
}
}
private void fillExtraInfo(List<ArticleData> articles, User currentUser) {
setFavoriteCount(articles);
if (currentUser != null) {
setIsFavorite(articles, currentUser);
setIsFollowingAuthor(articles, currentUser);
}
}
private void setIsFollowingAuthor(List<ArticleData> articles, User currentUser) {
Set<String> followingAuthors =
userRelationshipQueryService.followingAuthors(
currentUser.getId(),
articles.stream()
.map(articleData1 -> articleData1.getProfileData().getId())
.collect(toList()));
articles.forEach(
articleData -> {
if (followingAuthors.contains(articleData.getProfileData().getId())) {
articleData.getProfileData().setFollowing(true);
}
});
}
private void setFavoriteCount(List<ArticleData> articles) {
List<ArticleFavoriteCount> favoritesCounts =
articleFavoritesReadService.articlesFavoriteCount(
articles.stream().map(ArticleData::getId).collect(toList()));
Map<String, Integer> countMap = new HashMap<>();
favoritesCounts.forEach( | item -> {
countMap.put(item.getId(), item.getCount());
});
articles.forEach(
articleData -> articleData.setFavoritesCount(countMap.get(articleData.getId())));
}
private void setIsFavorite(List<ArticleData> articles, User currentUser) {
Set<String> favoritedArticles =
articleFavoritesReadService.userFavorites(
articles.stream().map(articleData -> articleData.getId()).collect(toList()),
currentUser);
articles.forEach(
articleData -> {
if (favoritedArticles.contains(articleData.getId())) {
articleData.setFavorited(true);
}
});
}
private void fillExtraInfo(String id, User user, ArticleData articleData) {
articleData.setFavorited(articleFavoritesReadService.isUserFavorite(user.getId(), id));
articleData.setFavoritesCount(articleFavoritesReadService.articleFavoriteCount(id));
articleData
.getProfileData()
.setFollowing(
userRelationshipQueryService.isUserFollowing(
user.getId(), articleData.getProfileData().getId()));
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\application\ArticleQueryService.java | 1 |
请完成以下Java代码 | public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setProductNo (final @Nullable java.lang.String ProductNo)
{
set_Value (COLUMNNAME_ProductNo, ProductNo);
}
@Override
public java.lang.String getProductNo()
{
return get_ValueAsString(COLUMNNAME_ProductNo);
}
@Override
public void setQualityRating (final @Nullable BigDecimal QualityRating)
{
set_Value (COLUMNNAME_QualityRating, QualityRating);
}
@Override
public BigDecimal getQualityRating()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QualityRating);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setShelfLifeMinDays (final int ShelfLifeMinDays)
{
set_Value (COLUMNNAME_ShelfLifeMinDays, ShelfLifeMinDays);
}
@Override
public int getShelfLifeMinDays()
{
return get_ValueAsInt(COLUMNNAME_ShelfLifeMinDays);
}
@Override
public void setShelfLifeMinPct (final int ShelfLifeMinPct)
{
set_Value (COLUMNNAME_ShelfLifeMinPct, ShelfLifeMinPct);
}
@Override
public int getShelfLifeMinPct()
{
return get_ValueAsInt(COLUMNNAME_ShelfLifeMinPct);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setUsedForCustomer (final boolean UsedForCustomer)
{ | set_Value (COLUMNNAME_UsedForCustomer, UsedForCustomer);
}
@Override
public boolean isUsedForCustomer()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForCustomer);
}
@Override
public void setUsedForVendor (final boolean UsedForVendor)
{
set_Value (COLUMNNAME_UsedForVendor, UsedForVendor);
}
@Override
public boolean isUsedForVendor()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForVendor);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
@Override
public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
@Override
public java.lang.String getVendorProductNo()
{
return get_ValueAsString(COLUMNNAME_VendorProductNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product.java | 1 |
请完成以下Java代码 | public void validateAndSetMissingFields(final I_PP_Cost_Collector cc)
{
//
// Set default locator, if not set and we have the warehouse:
if (cc.getM_Locator_ID() <= 0 && cc.getM_Warehouse_ID() > 0)
{
final WarehouseId warehouseId = WarehouseId.ofRepoId(cc.getM_Warehouse_ID());
final LocatorId locatorId = Services.get(IWarehouseBL.class).getOrCreateDefaultLocatorId(warehouseId);
cc.setM_Locator_ID(locatorId.getRepoId());
}
//
// Case: Material Issue and By/Co-Products receipts
// => validate against PP_Order_BOMLine which is mandatory
final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType());
final PPOrderBOMLineId orderBOMLineId = PPOrderBOMLineId.ofRepoIdOrNull(cc.getPP_Order_BOMLine_ID());
if (costCollectorType.isAnyComponentIssueOrCoProduct(orderBOMLineId))
{
if (orderBOMLineId == null)
{
throw new FillMandatoryException(I_PP_Cost_Collector.COLUMNNAME_PP_Order_BOMLine_ID);
}
final UomId bomLineUOMId = orderBOMBL.getBOMLineUOMId(orderBOMLineId);
// If no UOM, use the UOM from BOMLine | if (cc.getC_UOM_ID() <= 0)
{
cc.setC_UOM_ID(bomLineUOMId.getRepoId());
}
// If Cost Collector UOM differs from BOM Line UOM then throw exception because this conversion is not supported yet
if (cc.getC_UOM_ID() != bomLineUOMId.getRepoId())
{
throw new LiberoException("@PP_Cost_Collector_ID@ @C_UOM_ID@ <> @PP_Order_BOMLine_ID@ @C_UOM_ID@");
}
}
//
// Case: Activity Control
// => validate against PP_Order_Node which is mandatory
else if (costCollectorType.isActivityControl())
{
if (cc.getPP_Order_Node_ID() <= 0)
{
throw new FillMandatoryException(I_PP_Cost_Collector.COLUMNNAME_PP_Order_Node_ID);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Cost_Collector.java | 1 |
请完成以下Java代码 | public Class<?> getSecureObjectClass() {
return Message.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.metadataSource;
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
InterceptorStatusToken token = beforeInvocation(message);
if (token != null) {
tokenHolder.set(token);
}
return message;
}
@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
InterceptorStatusToken token = clearToken();
afterInvocation(token, null);
}
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {
InterceptorStatusToken token = clearToken();
finallyInvocation(token); | }
@Override
public boolean preReceive(MessageChannel channel) {
return true;
}
@Override
public Message<?> postReceive(Message<?> message, MessageChannel channel) {
return message;
}
@Override
public void afterReceiveCompletion(@Nullable Message<?> message, MessageChannel channel, @Nullable Exception ex) {
}
private InterceptorStatusToken clearToken() {
InterceptorStatusToken token = tokenHolder.get();
tokenHolder.remove();
return token;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\messaging\access\intercept\ChannelSecurityInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ReconciliationConfigUtil {
private static final Log LOG = LogFactory.getLog(ReconciliationConfigUtil.class);
/**
* 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例)
*/
private static Properties properties = new Properties();
private ReconciliationConfigUtil() {
}
// 通过类装载器装载进来
static {
try {
// 从类路径下读取属性文件
properties.load(ReconciliationConfigUtil.class.getClassLoader().getResourceAsStream("reconciliation_config.properties")); | } catch (IOException e) {
LOG.error(e);
}
}
/**
* 函数功能说明 :读取配置项 Administrator 2012-12-14 修改者名字 : 修改日期 : 修改内容 :
*
* @参数:
* @return void
* @throws
*/
public static String readConfig(String key) {
return (String) properties.get(key);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\ReconciliationConfigUtil.java | 2 |
请完成以下Java代码 | public int getAD_User_Substitute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_Substitute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public org.compiere.model.I_AD_User getSubstitute() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Substitute_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSubstitute(org.compiere.model.I_AD_User Substitute)
{
set_ValueFromPO(COLUMNNAME_Substitute_ID, org.compiere.model.I_AD_User.class, Substitute);
}
/** Set Ersatz.
@param Substitute_ID
Entity which can be used in place of this entity
*/
@Override
public void setSubstitute_ID (int Substitute_ID) | {
if (Substitute_ID < 1)
set_Value (COLUMNNAME_Substitute_ID, null);
else
set_Value (COLUMNNAME_Substitute_ID, Integer.valueOf(Substitute_ID));
}
/** Get Ersatz.
@return Entity which can be used in place of this entity
*/
@Override
public int getSubstitute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Substitute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Valid from including this date (first day)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Valid from including this date (first day)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Valid to including this date (last day)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Valid to including this date (last day)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Substitute.java | 1 |
请完成以下Java代码 | protected void walkToSave(ObjectOutput out) throws IOException
{
out.writeChar(c);
out.writeInt(status.ordinal());
if (status == Status.WORD_END_3 || status == Status.WORD_MIDDLE_2)
{
out.writeObject(value);
}
int childSize = 0;
if (child != null) childSize = child.length;
out.writeInt(childSize);
if (child == null) return;
for (BaseNode node : child)
{
node.walkToSave(out);
}
}
protected void walkToLoad(ByteArray byteArray, _ValueArray<V> valueArray)
{
c = byteArray.nextChar();
status = ARRAY_STATUS[byteArray.nextInt()];
if (status == Status.WORD_END_3 || status == Status.WORD_MIDDLE_2)
{
value = valueArray.nextValue();
}
int childSize = byteArray.nextInt();
child = new BaseNode[childSize];
for (int i = 0; i < childSize; ++i)
{
child[i] = new Node<V>();
child[i].walkToLoad(byteArray, valueArray);
}
}
protected void walkToLoad(ObjectInput byteArray) throws IOException, ClassNotFoundException
{
c = byteArray.readChar();
status = ARRAY_STATUS[byteArray.readInt()];
if (status == Status.WORD_END_3 || status == Status.WORD_MIDDLE_2)
{
value = (V) byteArray.readObject();
}
int childSize = byteArray.readInt();
child = new BaseNode[childSize];
for (int i = 0; i < childSize; ++i)
{
child[i] = new Node<V>();
child[i].walkToLoad(byteArray);
}
}
public enum Status
{
/**
* 未指定,用于删除词条
*/
UNDEFINED_0,
/**
* 不是词语的结尾
*/
NOT_WORD_1,
/**
* 是个词语的结尾,并且还可以继续
*/
WORD_MIDDLE_2,
/** | * 是个词语的结尾,并且没有继续
*/
WORD_END_3,
}
public class TrieEntry extends AbstractMap.SimpleEntry<String, V> implements Comparable<TrieEntry>
{
public TrieEntry(String key, V value)
{
super(key, value);
}
@Override
public int compareTo(TrieEntry o)
{
return getKey().compareTo(o.getKey());
}
}
@Override
public String toString()
{
if (child == null)
{
return "BaseNode{" +
"status=" + status +
", c=" + c +
", value=" + value +
'}';
}
return "BaseNode{" +
"child=" + child.length +
", status=" + status +
", c=" + c +
", value=" + value +
'}';
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\bintrie\BaseNode.java | 1 |
请完成以下Java代码 | public void setupDatabaseAndConnect() throws SQLException {
connection = DriverManager.getConnection("jdbc:h2:mem:testDB", "dbUser", "dbPassword");
String createTable = "CREATE TABLE CUSTOMER (id INT, first_name TEXT, last_name TEXT)";
connection.createStatement()
.execute(createTable);
}
public void destroyDB() throws SQLException {
String destroy = "DROP table IF EXISTS CUSTOMER";
connection.prepareStatement(destroy)
.execute();
connection.close();
}
public void inefficientUsage() throws SQLException {
for (int i = 0; i < 10000; i++) {
PreparedStatement preparedStatement = connection.prepareStatement(SQL);
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "firstname" + i);
preparedStatement.setString(3, "secondname" + i);
preparedStatement.executeUpdate();
preparedStatement.close();
}
}
public void betterUsage() {
try (PreparedStatement preparedStatement = connection.prepareStatement(SQL)) {
for (int i = 0; i < 10000; i++) {
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "firstname" + i);
preparedStatement.setString(3, "secondname" + i);
preparedStatement.executeUpdate();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void bestUsage() {
try (PreparedStatement preparedStatement = connection.prepareStatement(SQL)) { | connection.setAutoCommit(false);
for (int i = 0; i < 10000; i++) {
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "firstname" + i);
preparedStatement.setString(3, "secondname" + i);
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
try {
connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public int checkRowCount() {
try (PreparedStatement counter = connection.prepareStatement("SELECT COUNT(*) AS customers FROM CUSTOMER")) {
ResultSet resultSet = counter.executeQuery();
resultSet.next();
int count = resultSet.getInt("customers");
resultSet.close();
return count;
} catch (SQLException e) {
return -1;
}
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\resusepreparedstatement\ReusePreparedStatement.java | 1 |
请完成以下Java代码 | public void notify(DelegateExecution execution) {
// test whether cdi is setup correctly. (if not, just do not deliver the
// event)
try {
ProgrammaticBeanLookup.lookup(ProcessEngine.class);
} catch (Exception e) {
return;
}
BusinessProcessEvent event = createEvent(execution);
Annotation[] qualifiers = getQualifiers(event);
getBeanManager().getEvent().select(qualifiers).fire(event);
}
protected BusinessProcessEvent createEvent(DelegateExecution execution) {
ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(execution.getProcessDefinitionId());
ProcessEngineConfiguration engineConfiguration = org.flowable.engine.impl.context.Context.getProcessEngineConfiguration();
Date now = engineConfiguration.getClock().getCurrentTime();
return new CdiBusinessProcessEvent(activityId, transitionName, processDefinition, execution, type, execution.getProcessInstanceId(), execution.getId(), now);
} | protected BeanManager getBeanManager() {
BeanManager bm = BeanManagerLookup.getBeanManager();
if (bm == null) {
throw new FlowableException("No cdi bean manager available, cannot publish event.");
}
return bm;
}
protected Annotation[] getQualifiers(BusinessProcessEvent event) {
Annotation businessProcessQualifier = new BusinessProcessLiteral(event.getProcessDefinition().getKey());
if (type == BusinessProcessEventType.TAKE) {
return new Annotation[] { businessProcessQualifier, new TakeTransitionLiteral(transitionName) };
}
if (type == BusinessProcessEventType.START_ACTIVITY) {
return new Annotation[] { businessProcessQualifier, new StartActivityLiteral(activityId) };
}
if (type == BusinessProcessEventType.END_ACTIVITY) {
return new Annotation[] { businessProcessQualifier, new EndActivityLiteral(activityId) };
}
return new Annotation[] {};
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\event\CdiExecutionListener.java | 1 |
请完成以下Java代码 | public class FileValueTypeImpl extends AbstractValueTypeImpl implements FileValueType {
private static final long serialVersionUID = 1L;
public FileValueTypeImpl() {
super("file");
}
@Override
public TypedValue createValue(Object value, Map<String, Object> valueInfo) {
if (valueInfo == null) {
throw new IllegalArgumentException("Cannot create file without valueInfo.");
}
Object filename = valueInfo.get(VALUE_INFO_FILE_NAME);
if (filename == null) {
throw new IllegalArgumentException("Cannot create file without filename! Please set a name into ValueInfo with key " + VALUE_INFO_FILE_NAME);
}
FileValueBuilder builder = Variables.fileValue(filename.toString());
if (value instanceof File) {
builder.file((File) value);
} else if (value instanceof InputStream) {
builder.file((InputStream) value);
} else if (value instanceof byte[]) {
builder.file((byte[]) value);
} else {
throw new IllegalArgumentException("Provided value is not of File, InputStream or byte[] type.");
}
if (valueInfo.containsKey(VALUE_INFO_FILE_MIME_TYPE)) {
Object mimeType = valueInfo.get(VALUE_INFO_FILE_MIME_TYPE);
if (mimeType == null) {
throw new IllegalArgumentException("The provided mime type is null. Set a non-null value info property with key '" + VALUE_INFO_FILE_NAME + "'");
}
builder.mimeType(mimeType.toString());
}
if (valueInfo.containsKey(VALUE_INFO_FILE_ENCODING)) {
Object encoding = valueInfo.get(VALUE_INFO_FILE_ENCODING);
if (encoding == null) { | throw new IllegalArgumentException("The provided encoding is null. Set a non-null value info property with key '" + VALUE_INFO_FILE_ENCODING + "'");
}
builder.encoding(encoding.toString());
}
builder.setTransient(isTransient(valueInfo));
return builder.create();
}
@Override
public Map<String, Object> getValueInfo(TypedValue typedValue) {
if (!(typedValue instanceof FileValue)) {
throw new IllegalArgumentException("Value not of type FileValue");
}
FileValue fileValue = (FileValue) typedValue;
Map<String, Object> result = new HashMap<String, Object>(2);
result.put(VALUE_INFO_FILE_NAME, fileValue.getFilename());
if (fileValue.getMimeType() != null) {
result.put(VALUE_INFO_FILE_MIME_TYPE, fileValue.getMimeType());
}
if (fileValue.getEncoding() != null) {
result.put(VALUE_INFO_FILE_ENCODING, fileValue.getEncoding());
}
if (fileValue.isTransient()) {
result.put(VALUE_INFO_TRANSIENT, fileValue.isTransient());
}
return result;
}
@Override
public boolean isPrimitiveValueType() {
return true;
}
} | repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\FileValueTypeImpl.java | 1 |
请完成以下Java代码 | public JobQuery orderByJobDuedate() {
return orderBy(JobQueryProperty.DUEDATE);
}
public JobQuery orderByExecutionId() {
return orderBy(JobQueryProperty.EXECUTION_ID);
}
public JobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
public JobQuery orderByProcessInstanceId() {
return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID);
}
public JobQuery orderByProcessDefinitionId() {
return orderBy(JobQueryProperty.PROCESS_DEFINITION_ID);
}
public JobQuery orderByProcessDefinitionKey() {
return orderBy(JobQueryProperty.PROCESS_DEFINITION_KEY);
}
public JobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
public JobQuery orderByJobPriority() {
return orderBy(JobQueryProperty.PRIORITY);
}
public JobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
//results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobManager()
.findJobCountByQueryCriteria(this);
}
@Override
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getJobManager()
.findJobsByQueryCriteria(this, page);
}
@Override
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobManager()
.findDeploymentIdMappingsByQueryCriteria(this);
}
//getters //////////////////////////////////////////
public Set<String> getIds() {
return ids;
}
public String getRootProcessInstanceId() { | return rootProcessInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public String getExecutionId() {
return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public boolean getAcquired() {
return acquired;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ConfigureDataSources {
// first database, booksdb
@Primary
@Bean(name = "configBooksDb")
@ConfigurationProperties("app.datasource.ds1")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
@Primary
@Bean(name = "configFlywayBooksDb")
public FlywayBookProperties firstFlywayProperties() {
return new FlywayBookProperties();
}
@Primary
@Bean(name = "dataSourceBooksDb")
@ConfigurationProperties("app.datasource.ds1")
public HikariDataSource firstDataSource(@Qualifier("configBooksDb") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
@Primary
@FlywayDataSource
@Bean(initMethod = "migrate")
public Flyway firstFlyway(@Qualifier("configFlywayBooksDb") FlywayBookProperties properties,
@Qualifier("dataSourceBooksDb") HikariDataSource dataSource) {
return Flyway.configure()
.dataSource(dataSource)
.locations(properties.getLocation())
.load();
}
// second database, authorsdb
@Bean(name = "configAuthorsDb") | @ConfigurationProperties("app.datasource.ds2")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "configFlywayAuthorsDb")
public FlywayAuthorProperties secondFlywayProperties() {
return new FlywayAuthorProperties();
}
@Bean(name = "dataSourceAuthorsDb")
@ConfigurationProperties("app.datasource.ds2")
public HikariDataSource secondDataSource(@Qualifier("configAuthorsDb") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
@FlywayDataSource
@Bean(initMethod = "migrate")
public Flyway secondFlyway(@Qualifier("configFlywayAuthorsDb") FlywayAuthorProperties properties,
@Qualifier("dataSourceAuthorsDb") HikariDataSource dataSource) {
return Flyway.configure()
.dataSource(dataSource)
.locations(properties.getLocation())
.load();
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayMySQLTwoDatabases\src\main\java\com\bookstore\config\ConfigureDataSources.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class ApplicationConfiguration {
@Autowired ElasticsearchOperations operations;
@Autowired ConferenceRepository repository;
@PreDestroy
public void deleteIndex() {
operations.indexOps(Conference.class).delete();
}
@PostConstruct
public void insertDataSample() {
operations.indexOps(Conference.class).refresh();
// Save data sample | var documents = Arrays.asList(
Conference.builder().date("2014-11-06").name("Spring eXchange 2014 - London")
.keywords(Arrays.asList("java", "spring")).location(new GeoPoint(51.500152D, -0.126236D)).build(), //
Conference.builder().date("2014-12-07").name("Scala eXchange 2014 - London")
.keywords(Arrays.asList("scala", "play", "java")).location(new GeoPoint(51.500152D, -0.126236D)).build(), //
Conference.builder().date("2014-11-20").name("Elasticsearch 2014 - Berlin")
.keywords(Arrays.asList("java", "elasticsearch", "kibana")).location(new GeoPoint(52.5234051D, 13.4113999))
.build(), //
Conference.builder().date("2014-11-12").name("AWS London 2014").keywords(Arrays.asList("cloud", "aws"))
.location(new GeoPoint(51.500152D, -0.126236D)).build(), //
Conference.builder().date("2014-10-04").name("JDD14 - Cracow").keywords(Arrays.asList("java", "spring"))
.location(new GeoPoint(50.0646501D, 19.9449799)).build());
repository.saveAll(documents);
}
} | repos\spring-data-examples-main\elasticsearch\example\src\main\java\example\springdata\elasticsearch\conference\ApplicationConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public InitializingBean registerTaskCandidateGroupAddedEventListener(
RuntimeService runtimeService,
@Autowired(required = false) List<TaskRuntimeEventListener<TaskCandidateGroupAddedEvent>> listeners,
ToAPITaskCandidateGroupAddedEventConverter taskCandidateGroupAddedEventConverter
) {
return () ->
runtimeService.addEventListener(
new TaskCandidateGroupAddedListenerDelegate(
getInitializedTaskRuntimeEventListeners(listeners),
taskCandidateGroupAddedEventConverter
),
ActivitiEventType.ENTITY_CREATED
);
} | @Bean
public InitializingBean registerTaskCandidateGroupRemovedEventListener(
RuntimeService runtimeService,
@Autowired(required = false) List<TaskRuntimeEventListener<TaskCandidateGroupRemovedEvent>> listeners,
APITaskCandidateGroupConverter taskCandidateGroupConverter
) {
return () ->
runtimeService.addEventListener(
new TaskCandidateGroupRemovedListenerDelegate(
getInitializedTaskRuntimeEventListeners(listeners),
new ToTaskCandidateGroupRemovedConverter(taskCandidateGroupConverter)
),
ActivitiEventType.ENTITY_DELETED
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\conf\TaskRuntimeAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void warmUpBPartnerNamesCache(@NonNull final Set<BPartnerId> bpartnerIds)
{
CollectionUtils.getAllOrLoad(bpartnerNamesCache, bpartnerIds, bpartnerService::getBPartnerNames);
}
@Override
public String getBPartnerName(@NonNull final BPartnerId bpartnerId)
{
return bpartnerNamesCache.computeIfAbsent(bpartnerId, bpartnerService::getBPartnerName);
}
@Override
public ZonedDateTime toZonedDateTime(@NonNull final java.sql.Timestamp timestamp, @NonNull final OrgId orgId)
{
final ZoneId zoneId = orgDAO.getTimeZone(orgId);
return TimeUtil.asZonedDateTime(timestamp, zoneId);
}
@Override
public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotIdAndCaptionsCache.computeIfAbsent(pickingSlotId, pickingSlotService::getPickingSlotIdAndCaption);
}
@Override
public String getProductNo(@NonNull final ProductId productId)
{
return getProductInfo(productId).getProductNo();
}
@Override
public Optional<GS1ProductCodes> getGS1ProductCodes(@NonNull final ProductId productId, @Nullable final BPartnerId customerId)
{
return getProductInfo(productId).getGs1ProductCodes().getEffectiveCodes(customerId);
}
@Override
public ProductCategoryId getProductCategoryId(@NonNull final ProductId productId)
{
return getProductInfo(productId).getProductCategoryId();
}
@Override
public ITranslatableString getProductName(@NonNull final ProductId productId)
{
return getProductInfo(productId).getName();
}
private ProductInfo getProductInfo(@NonNull final ProductId productId)
{
return productInfoCache.computeIfAbsent(productId, productService::getById);
}
@Override
public HUPIItemProduct getPackingInfo(@NonNull final HUPIItemProductId huPIItemProductId)
{
return huService.getPackingInfo(huPIItemProductId);
}
@Override
public String getPICaption(@NonNull final HuPackingInstructionsId piId)
{
return huService.getPI(piId).getName(); | }
@Override
public String getLocatorName(@NonNull final LocatorId locatorId)
{
return locatorNamesCache.computeIfAbsent(locatorId, warehouseService::getLocatorNameById);
}
@Override
public HUQRCode getQRCodeByHUId(final HuId huId)
{
return huService.getQRCodeByHuId(huId);
}
@Override
public ScheduledPackageableLocks getLocks(final ShipmentScheduleAndJobScheduleIdSet scheduleIds)
{
return pickingJobLockService.getLocks(scheduleIds);
}
@Override
public int getSalesOrderLineSeqNo(@NonNull final OrderAndLineId orderAndLineId)
{
return orderService.getSalesOrderLineSeqNo(orderAndLineId);
}
//
//
//
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\DefaultPickingJobLoaderSupportingServices.java | 2 |
请完成以下Java代码 | public class M_InOut_AddToTransportationOrderProcess_SingleView extends JavaProcess implements IProcessPrecondition
{
@Param(parameterName = "M_ShipperTransportation_ID", mandatory = true)
private I_M_ShipperTransportation transportationOrder;
public static final AdMessageKey ALL_SELECTED_SHIPMENTS_SHOULD_BE_COMPLETED_MSG = AdMessageKey.of("de.metas.ui.web.inout.process.M_InOut_AddToTransportationOrderProcess.AllSelectedShipmentsShouldBeCompleted");
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
final I_M_InOut inOut = context.getSelectedModel(I_M_InOut.class);
final DocStatus docStatus = DocStatus.ofCode(inOut.getDocStatus());
if (!docStatus.isCompleted())
{
return ProcessPreconditionsResolution.reject(Services.get(IMsgBL.class).getTranslatableMsgText(ALL_SELECTED_SHIPMENTS_SHOULD_BE_COMPLETED_MSG));
}
return ProcessPreconditionsResolution.accept(); | }
@Override
protected String doIt() throws Exception
{
final DocStatus docStatus = DocStatus.ofCode(transportationOrder.getDocStatus());
if (docStatus.isCompleted())
{
// this error should not be thrown since we have AD_Val_Rule for the parameter
throw new AdempiereException("Transportation Order should not be closed");
}
final InOutToTransportationOrderService service = SpringContextHolder.instance.getBean(InOutToTransportationOrderService.class);
service.addShipmentsToTransportationOrder(ShipperTransportationId.ofRepoId(transportationOrder.getM_ShipperTransportation_ID()), ImmutableList.of(InOutId.ofRepoId(this.getRecord_ID())));
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\inout\process\M_InOut_AddToTransportationOrderProcess_SingleView.java | 1 |
请完成以下Java代码 | public void onInit(final InitEvent event) {
initLocales();
initDefaultCredentials();
}
protected void initLocales() {
LinkedHashMap<Locale, String> locales = coreProperties.getAvailableLocales().stream()
.collect(Collectors.toMap(Function.identity(), messageTools::getLocaleDisplayName, (s1, s2) -> s1,
LinkedHashMap::new));
ComponentUtils.setItemsMap(login, locales);
login.setSelectedLocale(VaadinSession.getCurrent().getLocale());
}
protected void initDefaultCredentials() {
if (StringUtils.isNotBlank(defaultUsername)) {
login.setUsername(defaultUsername);
}
if (StringUtils.isNotBlank(defaultPassword)) {
login.setPassword(defaultPassword);
}
}
@Subscribe("login")
public void onLogin(final LoginEvent event) {
try {
loginViewSupport.authenticate(
AuthDetails.of(event.getUsername(), event.getPassword())
.withLocale(login.getSelectedLocale())
.withRememberMe(login.isRememberMe())
);
} catch (final BadCredentialsException | DisabledException | LockedException | AccessDeniedException e) {
log.warn("Login failed for user '{}': {}", event.getUsername(), e.toString());
event.getSource().setError(true);
}
} | @Override
public void localeChange(final LocaleChangeEvent event) {
UI.getCurrent().getPage().setTitle(messageBundle.getMessage("LoginView.title"));
final JmixLoginI18n loginI18n = JmixLoginI18n.createDefault();
final JmixLoginI18n.JmixForm form = new JmixLoginI18n.JmixForm();
form.setTitle(messageBundle.getMessage("loginForm.headerTitle"));
form.setUsername(messageBundle.getMessage("loginForm.username"));
form.setPassword(messageBundle.getMessage("loginForm.password"));
form.setSubmit(messageBundle.getMessage("loginForm.submit"));
form.setForgotPassword(messageBundle.getMessage("loginForm.forgotPassword"));
form.setRememberMe(messageBundle.getMessage("loginForm.rememberMe"));
loginI18n.setForm(form);
final LoginI18n.ErrorMessage errorMessage = new LoginI18n.ErrorMessage();
errorMessage.setTitle(messageBundle.getMessage("loginForm.errorTitle"));
errorMessage.setMessage(messageBundle.getMessage("loginForm.badCredentials"));
errorMessage.setUsername(messageBundle.getMessage("loginForm.errorUsername"));
errorMessage.setPassword(messageBundle.getMessage("loginForm.errorPassword"));
loginI18n.setErrorMessage(errorMessage);
login.setI18n(loginI18n);
}
} | repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\view\login\LoginView.java | 1 |
请完成以下Java代码 | public I_M_HU getM_HU()
{
return get_ValueAsPO(COLUMNNAME_M_HU_ID, I_M_HU.class);
}
@Override
public void setM_HU(final I_M_HU M_HU)
{
set_ValueFromPO(COLUMNNAME_M_HU_ID, I_M_HU.class, M_HU);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_Value (COLUMNNAME_M_HU_ID, null);
else
set_Value (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_HU_QRCode_Assignment_ID (final int M_HU_QRCode_Assignment_ID)
{
if (M_HU_QRCode_Assignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_Assignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_Assignment_ID, M_HU_QRCode_Assignment_ID);
}
@Override
public int getM_HU_QRCode_Assignment_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_HU_QRCode_Assignment_ID);
}
@Override
public I_M_HU_QRCode getM_HU_QRCode()
{
return get_ValueAsPO(COLUMNNAME_M_HU_QRCode_ID, I_M_HU_QRCode.class);
}
@Override
public void setM_HU_QRCode(final I_M_HU_QRCode M_HU_QRCode)
{
set_ValueFromPO(COLUMNNAME_M_HU_QRCode_ID, I_M_HU_QRCode.class, M_HU_QRCode);
}
@Override
public void setM_HU_QRCode_ID (final int M_HU_QRCode_ID)
{
if (M_HU_QRCode_ID < 1)
set_Value (COLUMNNAME_M_HU_QRCode_ID, null);
else
set_Value (COLUMNNAME_M_HU_QRCode_ID, M_HU_QRCode_ID);
}
@Override
public int getM_HU_QRCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_QRCode_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_QRCode_Assignment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/process-instances/5")
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
@ApiModelProperty(example = "oneTaskProcess%3A1%3A4")
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/process-definitions/oneTaskProcess%3A1%3A4")
public String getProcessDefinitionUrl() {
return processDefinitionUrl;
}
public void setProcessDefinitionUrl(String processDefinitionUrl) {
this.processDefinitionUrl = processDefinitionUrl;
}
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
public void addVariable(RestVariable variable) {
variables.add(variable);
}
@ApiModelProperty(example = "12")
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@ApiModelProperty(example = "14")
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@ApiModelProperty(example = "15")
public String getSubScopeId() {
return subScopeId;
} | public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@ApiModelProperty(example = "cmmn")
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@ApiModelProperty(example = "16")
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
@ApiModelProperty(example = "someTenantId")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskResponse.java | 2 |
请完成以下Java代码 | public class SString implements Comparable<SString>, CharSequence
{
public char[] value;
/**
* 开始位置,包含
*/
public int b;
/**
* 结束位置,不包含
*/
public int e;
/**
* 建立一个字符串
*
* @param value
* @param b
* @param e
*/
public SString(char[] value, int b, int e)
{
this.value = value;
this.b = b;
this.e = e;
}
public SString(String s)
{
value = s.toCharArray();
b = 0;
e = s.length();
}
@Override
public boolean equals(Object anObject)
{
if (this == anObject)
{
return true;
}
if (anObject instanceof SString)
{
SString anotherString = (SString) anObject;
int n = value.length;
if (n == anotherString.value.length)
{
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0)
{
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
@Override
public int length()
{
return e - b;
}
@Override
public char charAt(int index)
{
return value[b + index];
}
@Override
public CharSequence subSequence(int start, int end)
{
return new SString(value, b + start, b + end);
}
@Override
public String toString()
{ | return new String(value, b, e - b);
}
@Override
public int compareTo(SString anotherString)
{
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim)
{
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2)
{
return c1 - c2;
}
k++;
}
return len1 - len2;
}
public char[] toCharArray()
{
return Arrays.copyOfRange(value, b, e);
}
public static SString valueOf(char word)
{
SString s = new SString(new char[]{word}, 0, 1);
return s;
}
public SString add(SString other)
{
char[] value = new char[length() + other.length()];
System.arraycopy(this.value, b, value, 0, length());
System.arraycopy(other.value, other.b, value, length(), other.length());
b = 0;
e = length() + other.length();
this.value = value;
return this;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\sequence\SString.java | 1 |
请完成以下Java代码 | public static final <T> IncludeExcludeListPredicate<T> ofExcludes(final T... excludes)
{
final Builder<T> includesExcludesList = builder();
if (excludes != null && excludes.length > 0)
{
for (final T exclude : excludes)
{
if (exclude != null)
{
includesExcludesList.exclude(exclude);
}
}
}
return includesExcludesList.build();
}
public static final <T> Builder<T> builder()
{
return new Builder<>();
}
public static <T> IncludeExcludeListPredicate<T> empty()
{
@SuppressWarnings("unchecked")
final IncludeExcludeListPredicate<T> emptyCasted = (IncludeExcludeListPredicate<T>)EMPTY;
return emptyCasted;
}
private final Set<T> includes;
private final Set<T> excludes;
private IncludeExcludeListPredicate(final Builder<T> builder)
{
super();
this.includes = ImmutableSet.copyOf(builder.includes);
this.excludes = ImmutableSet.copyOf(builder.excludes);
}
/**
* Empty constructor
*/
private IncludeExcludeListPredicate()
{
super();
includes = ImmutableSet.of();
excludes = ImmutableSet.of();
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public boolean test(final T item)
{
if (item == null)
{
return false;
}
// Don't accept it if it's explicitelly excluded
if (excludes.contains(item))
{
return false;
}
// Accept it right away if it explicitelly included
if (includes.contains(item))
{
return true;
}
// | // Accept it ONLY if there are NO particular items to be included.
// Else, we assume the user want's to include ONLY those.
final boolean acceptAllByDefault = includes.isEmpty();
return acceptAllByDefault;
}
public static class Builder<T>
{
private final Set<T> includes = new LinkedHashSet<>();
private final Set<T> excludes = new LinkedHashSet<>();
private IncludeExcludeListPredicate<T> lastBuilt = null;
private Builder()
{
super();
}
public IncludeExcludeListPredicate<T> build()
{
if (lastBuilt != null)
{
return lastBuilt;
}
if (isEmpty())
{
lastBuilt = empty();
}
else
{
lastBuilt = new IncludeExcludeListPredicate<>(this);
}
return lastBuilt;
}
public final boolean isEmpty()
{
return includes.isEmpty() && excludes.isEmpty();
}
public Builder<T> include(final T itemToInclude)
{
Check.assumeNotNull(itemToInclude, "itemToInclude not null");
final boolean added = includes.add(itemToInclude);
// Reset last built, in case of change
if (added)
{
lastBuilt = null;
}
return this;
}
public Builder<T> exclude(final T itemToExclude)
{
// guard against null: tollerate it but do nothing
if (itemToExclude == null)
{
return this;
}
final boolean added = excludes.add(itemToExclude);
// Reset last built, in case of change
if (added)
{
lastBuilt = null;
}
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IncludeExcludeListPredicate.java | 1 |
请完成以下Java代码 | public static ApiResponse ofMessage(String message) {
return of(Status.OK.getCode(), message, null);
}
/**
* 构造一个有状态的API返回
*
* @param status 状态 {@link Status}
* @return ApiResponse
*/
public static ApiResponse ofStatus(Status status) {
return ofStatus(status, null);
}
/**
* 构造一个有状态且带数据的API返回
*
* @param status 状态 {@link Status}
* @param data 返回数据
* @return ApiResponse
*/
public static ApiResponse ofStatus(Status status, Object data) {
return of(status.getCode(), status.getMessage(), data);
}
/**
* 构造一个异常且带数据的API返回
*
* @param t 异常
* @param data 返回数据 | * @param <T> {@link BaseException} 的子类
* @return ApiResponse
*/
public static <T extends BaseException> ApiResponse ofException(T t, Object data) {
return of(t.getCode(), t.getMessage(), data);
}
/**
* 构造一个异常且带数据的API返回
*
* @param t 异常
* @param <T> {@link BaseException} 的子类
* @return ApiResponse
*/
public static <T extends BaseException> ApiResponse ofException(T t) {
return ofException(t, null);
}
} | repos\spring-boot-demo-master\demo-exception-handler\src\main\java\com\xkcoding\exception\handler\model\ApiResponse.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class PooledDataSourceAvailableCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("PooledDataSource");
if (DataSourceBuilder.findType(context.getClassLoader()) != null) {
return ConditionOutcome.match(message.foundExactly("supported DataSource"));
}
return ConditionOutcome.noMatch(message.didNotFind("supported DataSource").atAll());
}
}
/**
* {@link Condition} to detect when an embedded {@link DataSource} type can be used.
* If a pooled {@link DataSource} is available, it will always be preferred to an
* {@code EmbeddedDatabase}.
*/
static class EmbeddedDatabaseCondition extends SpringBootCondition {
private static final String DATASOURCE_URL_PROPERTY = "spring.datasource.url";
private static final String EMBEDDED_DATABASE_TYPE = "org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType";
private final SpringBootCondition pooledCondition = new PooledDataSourceCondition();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("EmbeddedDataSource");
if (hasDataSourceUrlProperty(context)) {
return ConditionOutcome.noMatch(message.because(DATASOURCE_URL_PROPERTY + " is set"));
} | if (anyMatches(context, metadata, this.pooledCondition)) {
return ConditionOutcome.noMatch(message.foundExactly("supported pooled data source"));
}
if (!ClassUtils.isPresent(EMBEDDED_DATABASE_TYPE, context.getClassLoader())) {
return ConditionOutcome
.noMatch(message.didNotFind("required class").items(Style.QUOTE, EMBEDDED_DATABASE_TYPE));
}
EmbeddedDatabaseType type = EmbeddedDatabaseConnection.get(context.getClassLoader()).getType();
if (type == null) {
return ConditionOutcome.noMatch(message.didNotFind("embedded database").atAll());
}
return ConditionOutcome.match(message.found("embedded database").items(type));
}
private boolean hasDataSourceUrlProperty(ConditionContext context) {
Environment environment = context.getEnvironment();
if (environment.containsProperty(DATASOURCE_URL_PROPERTY)) {
try {
return StringUtils.hasText(environment.getProperty(DATASOURCE_URL_PROPERTY));
}
catch (IllegalArgumentException ex) {
// NOTE: This should be PlaceholderResolutionException
// Ignore unresolvable placeholder errors
}
}
return false;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CacheManager gatewayCacheManager(LocalResponseCacheProperties cacheProperties) {
return LocalResponseCacheUtils.createGatewayCacheManager(cacheProperties);
}
@Bean
public LocalResponseCacheGatewayFilterFactory localResponseCacheGatewayFilterFactory(
ResponseCacheManagerFactory responseCacheManagerFactory, LocalResponseCacheProperties properties) {
return new LocalResponseCacheGatewayFilterFactory(responseCacheManagerFactory, properties.getTimeToLive(),
properties.getSize(), properties.getRequest());
}
@Bean
public ResponseCacheManagerFactory responseCacheManagerFactory(CacheKeyGenerator cacheKeyGenerator) {
return new ResponseCacheManagerFactory(cacheKeyGenerator);
}
@Bean
public CacheKeyGenerator cacheKeyGenerator() {
return new CacheKeyGenerator();
}
Cache responseCache(CacheManager cacheManager) {
return cacheManager.getCache(RESPONSE_CACHE_NAME);
}
public static class OnGlobalLocalResponseCacheCondition extends AllNestedConditions {
OnGlobalLocalResponseCacheCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(value = GatewayProperties.PREFIX + ".enabled", havingValue = "true",
matchIfMissing = true)
static class OnGatewayPropertyEnabled { | }
@ConditionalOnProperty(value = GatewayProperties.PREFIX + ".filter.local-response-cache.enabled",
havingValue = "true")
static class OnLocalResponseCachePropertyEnabled {
}
@ConditionalOnProperty(name = GatewayProperties.PREFIX + ".global-filter.local-response-cache.enabled",
havingValue = "true", matchIfMissing = true)
static class OnGlobalLocalResponseCachePropertyEnabled {
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\LocalResponseCacheAutoConfiguration.java | 2 |
请完成以下Java代码 | public Date getDeploymentTime() {
return deploymentTime;
}
@Override
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@Override
public boolean isNew() {
return isNew;
}
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
@Override
public String getEngineVersion() {
return engineVersion;
}
@Override
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
@Override
public String getDerivedFrom() {
return derivedFrom;
}
@Override
public void setDerivedFrom(String derivedFrom) {
this.derivedFrom = derivedFrom;
}
@Override | public String getDerivedFromRoot() {
return derivedFromRoot;
}
@Override
public void setDerivedFromRoot(String derivedFromRoot) {
this.derivedFromRoot = derivedFromRoot;
}
@Override
public String getParentDeploymentId() {
return parentDeploymentId;
}
@Override
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\DeploymentEntityImpl.java | 1 |
请完成以下Java代码 | private int readDecimalPointPosition()
{
char decimalPointIndicator = readChar();
if (decimalPointIndicator < '0' || decimalPointIndicator > '9')
{
throw new IllegalArgumentException("decimal point indicator must be a digit");
}
return decimalPointIndicator - '0';
}
private List<?> readCurrencyAndAmount()
{
int decimalPointPosition = readDecimalPointPosition();
String currencyCode = readNumericDataField(3, 3);
String digits = readDataField(1, 15);
BigDecimal amount = new BigDecimal(digits).movePointLeft(decimalPointPosition);
return Arrays.asList(currencyCode, amount);
}
private List<String> readCountryList()
{
String dataField = readNumericDataField(3, 15);
if (dataField.length() % 3 != 0)
{
throw new IllegalArgumentException("invalid data field length");
}
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < dataField.length(); i += 3)
{
list.add(dataField.substring(i, i + 3));
}
return list;
}
private String readNumericDataField(int minLength, int maxLength)
{
String dataField = readDataField(minLength, maxLength);
if (!StringUtils.isNumber(dataField))
{
throw new AdempiereException("data field must be numeric: " + dataField);
}
return dataField;
}
private String readDataField(int minLength, int maxLength)
{
int length = 0;
int endIndex = position;
while (length < maxLength && endIndex < sequence.length())
{
if (sequence.charAt(endIndex) == SEPARATOR_CHAR)
{
break;
}
endIndex++;
length++;
}
if (length < minLength && minLength == maxLength)
{
throw new IllegalArgumentException("data field must be exactly " + minLength + " characters long");
}
if (length < minLength) | {
throw new IllegalArgumentException("data field must be at least " + minLength + " characters long");
}
String dataField = sequence.substring(position, endIndex);
position = endIndex;
return dataField;
}
private void skipSeparatorIfPresent()
{
if (position < sequence.length() && sequence.charAt(position) == SEPARATOR_CHAR)
{
position++;
}
}
public int remainingLength()
{
return sequence.length() - position;
}
public boolean startsWith(String prefix)
{
return sequence.startsWith(prefix, position);
}
private char readChar()
{
return sequence.charAt(position++);
}
public String read(int length)
{
String s = peek(length);
position += length;
return s;
}
public String peek(int length)
{
return sequence.substring(position, position + length);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1SequenceReader.java | 1 |
请完成以下Java代码 | public class Menu implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@Schema(description = "主键")
@TableId(value = "id", type = IdType.ASSIGN_ID)
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
/**
* 菜单父主键
*/
@Schema(description = "父主键")
@JsonSerialize(using = ToStringSerializer.class)
private Long parentId;
/**
* 菜单编号
*/
@Schema(description = "菜单编号")
private String code;
/**
* 菜单名称
*/
@Schema(description = "菜单名称")
private String name;
/**
* 菜单别名
*/
@Schema(description = "菜单别名")
private String alias;
/**
* 请求地址
*/
@Schema(description = "请求地址")
private String path;
/**
* 菜单资源
*/
@Schema(description = "菜单资源")
private String source;
/**
* 排序
*/
@Schema(description = "排序")
private Integer sort;
/**
* 菜单类型
*/
@Schema(description = "菜单类型")
private Integer category;
/**
* 操作按钮类型
*/
@Schema(description = "操作按钮类型")
private Integer action;
/** | * 是否打开新页面
*/
@Schema(description = "是否打开新页面")
private Integer isOpen;
/**
* 备注
*/
@Schema(description = "备注")
private String remark;
/**
* 是否已删除
*/
@TableLogic
@Schema(description = "是否已删除")
private Integer isDeleted;
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
Menu other = (Menu) obj;
return Func.equals(this.getId(), other.getId());
}
@Override
public int hashCode() {
return Objects.hash(id, parentId, code);
}
} | repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\entity\Menu.java | 1 |
请完成以下Java代码 | public void setDIM_Dimension_Spec_Assignment_ID (int DIM_Dimension_Spec_Assignment_ID)
{
if (DIM_Dimension_Spec_Assignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_Assignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_Assignment_ID, Integer.valueOf(DIM_Dimension_Spec_Assignment_ID));
}
/** Get Dimensionsspezifikationszuordnung.
@return Dimensionsspezifikationszuordnung */
@Override
public int getDIM_Dimension_Spec_Assignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Spec_Assignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.dimension.model.I_DIM_Dimension_Spec getDIM_Dimension_Spec()
{
return get_ValueAsPO(COLUMNNAME_DIM_Dimension_Spec_ID, de.metas.dimension.model.I_DIM_Dimension_Spec.class);
}
@Override
public void setDIM_Dimension_Spec(de.metas.dimension.model.I_DIM_Dimension_Spec DIM_Dimension_Spec)
{
set_ValueFromPO(COLUMNNAME_DIM_Dimension_Spec_ID, de.metas.dimension.model.I_DIM_Dimension_Spec.class, DIM_Dimension_Spec);
}
/** Set Dimensionsspezifikation.
@param DIM_Dimension_Spec_ID Dimensionsspezifikation */ | @Override
public void setDIM_Dimension_Spec_ID (int DIM_Dimension_Spec_ID)
{
if (DIM_Dimension_Spec_ID < 1)
set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_ID, Integer.valueOf(DIM_Dimension_Spec_ID));
}
/** Get Dimensionsspezifikation.
@return Dimensionsspezifikation */
@Override
public int getDIM_Dimension_Spec_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Spec_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec_Assignment.java | 1 |
请完成以下Java代码 | public int getC_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_ID);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
@Override
public void setM_PriceList_Version_ID (final int M_PriceList_Version_ID)
{
if (M_PriceList_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, M_PriceList_Version_ID);
}
@Override
public int getM_PriceList_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_Version_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID); | }
@Override
public void setProductPriceInStockUOM (final BigDecimal ProductPriceInStockUOM)
{
set_ValueNoCheck (COLUMNNAME_ProductPriceInStockUOM, ProductPriceInStockUOM);
}
@Override
public BigDecimal getProductPriceInStockUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ProductPriceInStockUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_ValueNoCheck (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_purchase_prices_in_stock_uom_plv_v.java | 1 |
请完成以下Java代码 | public void setV_Liability_Services_Acct (int V_Liability_Services_Acct)
{
set_Value (COLUMNNAME_V_Liability_Services_Acct, Integer.valueOf(V_Liability_Services_Acct));
}
/** Get Vendor Service Liability.
@return Account for Vender Service Liability
*/
public int getV_Liability_Services_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_V_Liability_Services_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getV_Prepayment_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getV_Prepayment_Acct(), get_TrxName()); }
/** Set Vendor Prepayment.
@param V_Prepayment_Acct
Account for Vendor Prepayments | */
public void setV_Prepayment_Acct (int V_Prepayment_Acct)
{
set_Value (COLUMNNAME_V_Prepayment_Acct, Integer.valueOf(V_Prepayment_Acct));
}
/** Get Vendor Prepayment.
@return Account for Vendor Prepayments
*/
public int getV_Prepayment_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_V_Prepayment_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_BP_Vendor_Acct.java | 1 |
请完成以下Java代码 | public <T> T execute(CommandConfig config, Command<T> command, CommandExecutor commandExecutor) {
long waitTime = waitTimeInMs;
int failedAttempts = 0;
do {
if (failedAttempts > 0) {
LOGGER.info("Waiting for {}ms before retrying the command.", waitTime);
waitBeforeRetry(waitTime);
waitTime *= waitIncreaseFactor;
}
try {
// try to execute the command
return next.execute(config, command, commandExecutor);
} catch (FlowableOptimisticLockingException e) {
LOGGER.info("Caught optimistic locking exception: {}", e.getMessage(), e);
}
failedAttempts++;
} while (failedAttempts <= numOfRetries);
throw new FlowableException(numOfRetries + " retries failed with FlowableOptimisticLockingException. Giving up.");
}
protected void waitBeforeRetry(long waitTime) {
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) { | LOGGER.debug("I am interrupted while waiting for a retry.");
}
}
public void setNumOfRetries(int numOfRetries) {
this.numOfRetries = numOfRetries;
}
public void setWaitIncreaseFactor(int waitIncreaseFactor) {
this.waitIncreaseFactor = waitIncreaseFactor;
}
public void setWaitTimeInMs(int waitTimeInMs) {
this.waitTimeInMs = waitTimeInMs;
}
public int getNumOfRetries() {
return numOfRetries;
}
public int getWaitIncreaseFactor() {
return waitIncreaseFactor;
}
public int getWaitTimeInMs() {
return waitTimeInMs;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\interceptor\RetryInterceptor.java | 1 |
请完成以下Java代码 | public Set<String> getOptions() {
return Collections.singleton(command.getName());
}
@Override
public String getUsageHelp() {
return command.getDescription();
}
});
}
}
return help;
}
private boolean isHelpShown(Command command) {
return !(command instanceof HelpCommand) && !(command instanceof HintCommand);
}
@Override
public ExitStatus run(String... args) throws Exception {
if (args.length == 0) {
throw new NoHelpCommandArgumentsException();
}
String commandName = args[0];
for (Command command : this.commandRunner) {
if (command.getName().equals(commandName)) {
Log.info(this.commandRunner.getName() + command.getName() + " - " + command.getDescription()); | Log.info("");
if (command.getUsageHelp() != null) {
Log.info("usage: " + this.commandRunner.getName() + command.getName() + " "
+ command.getUsageHelp());
Log.info("");
}
if (command.getHelp() != null) {
Log.info(command.getHelp());
}
Collection<HelpExample> examples = command.getExamples();
if (examples != null) {
Log.info((examples.size() != 1) ? "examples:" : "example:");
Log.info("");
for (HelpExample example : examples) {
Log.info(" " + example.getDescription() + ":");
Log.info(" $ " + example.getExample());
Log.info("");
}
Log.info("");
}
return ExitStatus.OK;
}
}
throw new NoSuchCommandException(commandName);
}
} | repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\core\HelpCommand.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.