instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setName(final String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(final String dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } public String getSex() { return sex; } public void setSex(final String sex) { this.sex = sex; } public String getCountry() { return country; } public void setCountry(final String country) { this.country = country; } public String getJob() { return job; } public void setJob(final String job) { this.job = job; } public boolean isReceiveNewsletter() { return receiveNewsletter; } public void setReceiveNewsletter(final boolean receiveNewsletter) { this.receiveNewsletter = receiveNewsletter; } public String[] getHobbies() { return hobbies;
} public void setHobbies(final String[] hobbies) { this.hobbies = hobbies; } public List<String> getFavouriteLanguage() { return favouriteLanguage; } public void setFavouriteLanguage(final List<String> favouriteLanguage) { this.favouriteLanguage = favouriteLanguage; } public String getNotes() { return notes; } public void setNotes(final String notes) { this.notes = notes; } public List<String> getFruit() { return fruit; } public void setFruit(final List<String> fruit) { this.fruit = fruit; } public String getBook() { return book; } public void setBook(final String book) { this.book = book; } public MultipartFile getFile() { return file; } public void setFile(final MultipartFile file) { this.file = file; } }
repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\taglibrary\Person.java
1
请完成以下Java代码
public java.sql.Timestamp getDateInvoiced () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DateInvoiced); } /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ @Override public void setIsSOTrx (boolean IsSOTrx) { set_ValueNoCheck (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ @Override public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */
@Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Einzelpreis. @param PriceActual Effektiver Preis */ @Override public void setPriceActual (java.math.BigDecimal PriceActual) { set_ValueNoCheck (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Effektiver Preis */ @Override public java.math.BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats_Invoice_Online_V.java
1
请完成以下Java代码
public void setExternalTaskIds(List<String> externalTaskIds) { this.externalTaskIds = externalTaskIds; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ExternalTaskQueryDto getExternalTaskQuery() { return externalTaskQuery; } public void setExternalTaskQuery(ExternalTaskQueryDto externalTaskQuery) { this.externalTaskQuery = externalTaskQuery; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQueryDto) { this.processInstanceQuery = processInstanceQueryDto; } public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto) { this.historicProcessInstanceQuery = historicProcessInstanceQueryDto; } public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\SetRetriesForExternalTasksDto.java
1
请完成以下Java代码
public class ObjectWithMap { private String name; @JsonMerge private Map<String, String> stringPairs; public ObjectWithMap(String name, Map<String, String> stringPairs) { this.name = name; this.stringPairs = stringPairs; } public String getName() { return name; } public void setName(String name) {
this.name = name; } public Map<String, String> getStringPairs() { return stringPairs; } public void setStringPairs(Map<String, String> stringPairs) { this.stringPairs = stringPairs; } @Override public String toString() { return "ObjectWithMap{" + "name='" + name + '\'' + ", something=" + stringPairs + '}'; } }
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\jsonmerge\ObjectWithMap.java
1
请完成以下Java代码
public int getC_AcctSchema_ID() { return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID); } @Override public org.compiere.model.I_C_ElementValue getC_ElementValue() { return get_ValueAsPO(COLUMNNAME_C_ElementValue_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setC_ElementValue(final org.compiere.model.I_C_ElementValue C_ElementValue) { set_ValueFromPO(COLUMNNAME_C_ElementValue_ID, org.compiere.model.I_C_ElementValue.class, C_ElementValue); } @Override public void setC_ElementValue_ID (final int C_ElementValue_ID) { if (C_ElementValue_ID < 1) set_Value (COLUMNNAME_C_ElementValue_ID, null); else set_Value (COLUMNNAME_C_ElementValue_ID, C_ElementValue_ID); } @Override public int getC_ElementValue_ID() { return get_ValueAsInt(COLUMNNAME_C_ElementValue_ID); } @Override public void setC_Invoice_Acct_ID (final int C_Invoice_Acct_ID) { if (C_Invoice_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Acct_ID, C_Invoice_Acct_ID); } @Override public int getC_Invoice_Acct_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Acct_ID); } @Override public org.compiere.model.I_C_Invoice getC_Invoice() { return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setC_Invoice(final org.compiere.model.I_C_Invoice C_Invoice) { set_ValueFromPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class, C_Invoice); } @Override public void setC_Invoice_ID (final int C_Invoice_ID) { if (C_Invoice_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, C_Invoice_ID); } @Override
public int getC_Invoice_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_ID); } @Override public org.compiere.model.I_C_InvoiceLine getC_InvoiceLine() { return get_ValueAsPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class); } @Override public void setC_InvoiceLine(final org.compiere.model.I_C_InvoiceLine C_InvoiceLine) { set_ValueFromPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class, C_InvoiceLine); } @Override public void setC_InvoiceLine_ID (final int C_InvoiceLine_ID) { if (C_InvoiceLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, C_InvoiceLine_ID); } @Override public int getC_InvoiceLine_ID() { return get_ValueAsInt(COLUMNNAME_C_InvoiceLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Acct.java
1
请完成以下Java代码
public class StreamAdmin implements SmartLifecycle { private final StreamCreator streamCreator; private final Consumer<StreamCreator> callback; private boolean autoStartup = true; private int phase; private volatile boolean running; /** * Construct with the provided parameters. * @param env the environment. * @param callback the callback to receive the {@link StreamCreator}. */ public StreamAdmin(Environment env, Consumer<StreamCreator> callback) { Assert.notNull(env, "Environment cannot be null"); Assert.notNull(callback, "'callback' cannot be null"); this.streamCreator = env.streamCreator(); this.callback = callback; } @Override public int getPhase() { return this.phase; } /** * Set the phase; default is 0. * @param phase the phase. */ public void setPhase(int phase) { this.phase = phase; } /** * Set to false to prevent automatic startup. * @param autoStartup the autoStartup. */ public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup;
} @Override public void start() { this.callback.accept(this.streamCreator); this.running = true; } @Override public void stop() { this.running = false; } @Override public boolean isRunning() { return this.running; } @Override public boolean isAutoStartup() { return this.autoStartup; } }
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\support\StreamAdmin.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductBOMVersionsId implements RepoIdAware { int repoId; @JsonCreator public static ProductBOMVersionsId ofRepoId(final int repoId) { return new ProductBOMVersionsId(repoId); } @Nullable public static ProductBOMVersionsId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new ProductBOMVersionsId(repoId) : null; }
private ProductBOMVersionsId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Product_BOMVersions_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable ProductBOMVersionsId id) {return id != null ? id.getRepoId() : -1;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\ProductBOMVersionsId.java
2
请完成以下Java代码
public synchronized void mark(int readLimit) { try { in().mark(readLimit); } catch (IOException ex) { // Ignore } } @Override public synchronized void reset() throws IOException { in().reset(); } private InputStream in() throws IOException { InputStream in = this.in; if (in == null) { synchronized (this) { in = this.in; if (in == null) { in = getDelegateInputStream(); this.in = in; } } } return in;
} @Override public void close() throws IOException { InputStream in = this.in; if (in != null) { synchronized (this) { in = this.in; if (in != null) { in.close(); } } } } protected abstract InputStream getDelegateInputStream() throws IOException; }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\LazyDelegatingInputStream.java
1
请完成以下Java代码
public int getAD_Process_CustomQuery_ID() { return get_ValueAsInt(COLUMNNAME_AD_Process_CustomQuery_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsAdditionalCustomQuery (final boolean IsAdditionalCustomQuery) { set_Value (COLUMNNAME_IsAdditionalCustomQuery, IsAdditionalCustomQuery); } @Override public boolean isAdditionalCustomQuery() { return get_ValueAsBoolean(COLUMNNAME_IsAdditionalCustomQuery); } @Override public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID) { if (LeichMehl_PluFile_ConfigGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID); }
@Override public int getLeichMehl_PluFile_ConfigGroup_ID() { return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_ConfigGroup.java
1
请完成以下Java代码
public int compare(final IProductStorage productStorage1, final IProductStorage productStorage2) { final String productName1 = getProductName(productStorage1); final String productName2 = getProductName(productStorage2); return productName1.compareTo(productName2); } private final String getProductName(final IProductStorage productStorage) { if (productStorage == null) { return ""; } return Services.get(IProductBL.class).getProductName(productStorage.getProductId()); } }; ProductId getProductId(); I_C_UOM getC_UOM(); BigDecimal getQtyFree(); Quantity getQty(); default BigDecimal getQtyAsBigDecimal() { return getQty().toBigDecimal(); } default Quantity getQty(@NonNull final UomId uomId) {
final I_C_UOM uomRecord = Services.get(IUOMDAO.class).getById(uomId); return getQty(uomRecord); } /** * Gets storage Qty, converted to given UOM. * * @return Qty converted to given UOM. */ Quantity getQty(I_C_UOM uom); /** * @return storage capacity */ BigDecimal getQtyCapacity(); IAllocationRequest removeQty(IAllocationRequest request); IAllocationRequest addQty(IAllocationRequest request); void markStaled(); boolean isEmpty(); /** * @return true if this storage allows negative storages */ boolean isAllowNegativeStorage(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\IProductStorage.java
1
请在Spring Boot框架中完成以下Java代码
public class ClientSecurityProperties { private String accessor; private String accessorPostProcessor; private String authenticationInitializer; private String authenticator; private String diffieHellmanAlgorithm; public String getAccessor() { return this.accessor; } public void setAccessor(String accessor) { this.accessor = accessor; } public String getAccessorPostProcessor() { return this.accessorPostProcessor; } public void setAccessorPostProcessor(String accessorPostProcessor) { this.accessorPostProcessor = accessorPostProcessor; } public String getAuthenticationInitializer() { return this.authenticationInitializer; } public void setAuthenticationInitializer(String authenticationInitializer) {
this.authenticationInitializer = authenticationInitializer; } public String getAuthenticator() { return this.authenticator; } public void setAuthenticator(String authenticator) { this.authenticator = authenticator; } public String getDiffieHellmanAlgorithm() { return this.diffieHellmanAlgorithm; } public void setDiffieHellmanAlgorithm(String diffieHellmanAlgorithm) { this.diffieHellmanAlgorithm = diffieHellmanAlgorithm; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ClientSecurityProperties.java
2
请完成以下Java代码
private VendorProductInfo createVendorProductInfo( @NonNull final BPartnerId vendorId, @NonNull final ProductAndCategoryAndManufacturerId product, @NonNull final PricingConditionsId pricingConditionsId, @Nullable final I_C_BPartner_Product bpartnerProductRecord) { final I_C_BPartner vendorRecord = bpartnersRepo.getById(vendorId); final boolean aggregatePOs = vendorRecord.isAggregatePO(); final Percent vendorFlatDiscount = Percent.of(vendorRecord.getFlatDiscount()); final PricingConditions pricingConditions = pricingConditionsRepo.getPricingConditionsById(pricingConditionsId); final ProductId productId = product.getProductId(); final String vendorProductNo = CoalesceUtil.coalesceSuppliers( () -> bpartnerProductRecord != null ? bpartnerProductRecord.getVendorProductNo() : null, () -> bpartnerProductRecord != null ? bpartnerProductRecord.getProductNo() : null, () -> productBL.getProductValue(productId)); final String vendorProductName = CoalesceUtil.coalesceSuppliers(
() -> bpartnerProductRecord != null ? bpartnerProductRecord.getProductName() : null, () -> productBL.getProductName(productId)); final boolean defaultVendor = bpartnerProductRecord != null ? bpartnerProductRecord.isCurrentVendor() : false; return VendorProductInfo.builder() .vendorId(vendorId) .defaultVendor(defaultVendor) .product(product) .attributeSetInstanceId(AttributeSetInstanceId.NONE) // this might change when we incorporate attribute based pricing .vendorProductNo(vendorProductNo) .vendorProductName(vendorProductName) .aggregatePOs(aggregatePOs) .vendorFlatDiscount(vendorFlatDiscount) .pricingConditions(pricingConditions) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\VendorProductInfoService.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerAttachmentsRouteBuilder extends RouteBuilder { public static final String ATTACH_FILE_TO_BPARTNER_ROUTE_ID = "GRSSignum-bpartnerAttachFile"; public static final String ATTACH_FILE_TO_BPARTNER_PROCESSOR_ID = "GRSSignum-attachFileProcessorID"; @Override public void configure() throws Exception { errorHandler(defaultErrorHandler()); onException(Exception.class) .to(direct(MF_ERROR_ROUTE_ID)); from(direct(ATTACH_FILE_TO_BPARTNER_ROUTE_ID)) .routeId(ATTACH_FILE_TO_BPARTNER_ROUTE_ID) .log("Route invoked!") .unmarshal(setupJacksonDataFormatFor(getContext(), JsonBPartnerAttachment.class)) .process(this::buildAndAttachContext) .process(RetrieveExternalSystemRequestBuilder::buildAndAttachRetrieveExternalSystemRequest) .to("{{" + ExternalSystemCamelConstants.MF_GET_EXTERNAL_SYSTEM_INFO + "}}") .unmarshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), JsonExternalSystemInfo.class)) .process(this::processExternalSystemInfo) .process(new BPartnerAttachmentsProcessor()).id(ATTACH_FILE_TO_BPARTNER_PROCESSOR_ID) .to(direct(ExternalSystemCamelConstants.MF_ATTACHMENT_ROUTE_ID)); } private void buildAndAttachContext(@NonNull final Exchange exchange) { final JsonBPartnerAttachment jsonBPartnerAttachment = exchange.getIn().getBody(JsonBPartnerAttachment.class); final BPartnerAttachmentsRouteContext routeContext = BPartnerAttachmentsRouteContext
.builder() .jsonBPartnerAttachment(jsonBPartnerAttachment) .build(); exchange.setProperty(GRSSignumConstants.ROUTE_PROPERTY_ATTACH_FILE_CONTEXT, routeContext); } private void processExternalSystemInfo(@NonNull final Exchange exchange) { final JsonExternalSystemInfo jsonExternalSystemInfo = exchange.getIn().getBody(JsonExternalSystemInfo.class); if (jsonExternalSystemInfo == null) { throw new RuntimeException("Missing external system info!"); } final String exportDirectoriesBasePath = jsonExternalSystemInfo.getParameters().get(PARAM_BasePathForExportDirectories); if (Check.isBlank(exportDirectoriesBasePath)) { throw new RuntimeException(PARAM_BasePathForExportDirectories + " not set for ExternalSystem_Config_ID: " + jsonExternalSystemInfo.getExternalSystemConfigId()); } final BPartnerAttachmentsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_ATTACH_FILE_CONTEXT, BPartnerAttachmentsRouteContext.class); context.setExportDirectoriesBasePath(exportDirectoriesBasePath); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\attachment\BPartnerAttachmentsRouteBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public class BpmnInterface { protected String id; protected String name; protected BpmnInterfaceImplementation implementation; /** * Mapping of the operations of this interface. The key of the map is the id of the operation, for easy retrieval. */ protected Map<String, Operation> operations = new HashMap<String, Operation>(); public BpmnInterface() {} public BpmnInterface(String id, String name) { setId(id); setName(name); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public void addOperation(Operation operation) { operations.put(operation.getId(), operation); } public Operation getOperation(String operationId) { return operations.get(operationId); } public Collection<Operation> getOperations() { return operations.values(); } public BpmnInterfaceImplementation getImplementation() { return implementation; } public void setImplementation(BpmnInterfaceImplementation implementation) { this.implementation = implementation; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\webservice\BpmnInterface.java
2
请在Spring Boot框架中完成以下Java代码
public Object getZIP() { return zip; } /** * Sets the value of the zip property. * * @param value * allowed object is * {@link Object } * */ public void setZIP(Object value) { this.zip = value; } /** * Gets the value of the town property. * * @return * possible object is * {@link Object } * */ public Object getTown() { return town; } /** * Sets the value of the town property. * * @param value * allowed object is * {@link Object } * */ public void setTown(Object value) { this.town = value; } /** * Gets the value of the country property.
* * @return * possible object is * {@link Object } * */ public Object getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link Object } * */ public void setCountry(Object value) { this.country = 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\ShipFromType.java
2
请在Spring Boot框架中完成以下Java代码
protected byte[] getDeploymentResourceData(String deploymentId, String resourceName, HttpServletResponse response) { if (deploymentId == null) { throw new FlowableIllegalArgumentException("No deployment id provided"); } if (resourceName == null) { throw new FlowableIllegalArgumentException("No resource name provided"); } // Check if deployment exists CmmnDeployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); if (deployment == null) { throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", CmmnDeployment.class); } if (restApiInterceptor != null) { restApiInterceptor.accessDeploymentById(deployment); } List<String> resourceList = repositoryService.getDeploymentResourceNames(deploymentId);
if (resourceList.contains(resourceName)) { String contentType = contentTypeResolver.resolveContentType(resourceName); response.setContentType(contentType); try (final InputStream resourceStream = repositoryService.getResourceAsStream(deploymentId, resourceName)) { return IOUtils.toByteArray(resourceStream); } catch (Exception e) { throw new FlowableException("Error converting resource stream", e); } } else { // Resource not found in deployment throw new FlowableObjectNotFoundException("Could not find a resource with name '" + resourceName + "' in deployment '" + deploymentId + "'.", String.class); } } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\BaseDeploymentResourceDataResource.java
2
请完成以下Java代码
public String getDescription() { return description; } public String getExecutionId() { return executionId; } public String getOwner() { return owner; } public String getParentTaskId() { return parentTaskId; } public int getPriority() { return priority; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public String getTaskDefinitionKey() { return taskDefinitionKey; } public Date getFollowUp() { return followUp; } public String getCaseDefinitionId() { return caseDefinitionId; }
public String getCaseExecutionId() { return caseExecutionId; } public String getCaseInstanceId() { return caseInstanceId; } public boolean isSuspended() { return suspended; } public String getFormKey() { return formKey; } public CamundaFormRef getCamundaFormRef() { return camundaFormRef; } public String getTenantId() { return tenantId; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\task\HalTask.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; }
public Library getLibrary() { return library; } public void setLibrary(Library library) { this.library = library; } public List<Author> getAuthors() { return authors; } public void setAuthors(List<Author> authors) { this.authors = authors; } }
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\books\models\Book.java
1
请在Spring Boot框架中完成以下Java代码
public String getContact() { return contact; } /** * Sets the value of the contact property. * * @param value * allowed object is * {@link String } * */ public void setContact(String value) { this.contact = value; } /** * Gets the value of the phone property. * * @return * possible object is * {@link String } * */ public String getPhone() { return phone; } /** * Sets the value of the phone property. * * @param value * allowed object is * {@link String } * */ public void setPhone(String value) { this.phone = value; } /** * Gets the value of the fax property. * * @return * possible object is * {@link String } * */ public String getFax() { return fax; } /** * Sets the value of the fax property. * * @param value * allowed object is * {@link String } * */ public void setFax(String value) { this.fax = value; } /** * Gets the value of the email property. * * @return * possible object is * {@link String } * */ public String getEmail() { return email; } /** * Sets the value of the email property. * * @param value * allowed object is
* {@link String } * */ public void setEmail(String value) { this.email = value; } /** * Gets the value of the comment property. * * @return * possible object is * {@link String } * */ public String getComment() { return comment; } /** * Sets the value of the comment property. * * @param value * allowed object is * {@link String } * */ public void setComment(String value) { this.comment = value; } /** * Gets the value of the iaccount property. * * @return * possible object is * {@link String } * */ public String getIaccount() { return iaccount; } /** * Sets the value of the iaccount property. * * @param value * allowed object is * {@link String } * */ public void setIaccount(String value) { this.iaccount = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Address.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } if (!I_C_BPartner_CreditLimit.Table_Name.equals(context.getTableName())) { return ProcessPreconditionsResolution.rejectWithInternalReason("not running on C_BPartner_CreditLimit table"); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx protected String doIt() { final UserId approvedByUserId = UserId.ofRepoIdOrNull(approvedByUserRepoId); if (approvedByUserId == null) {
throw new FillMandatoryException(PARAM_ApprovedBy_ID); } final I_C_BPartner_CreditLimit bpCreditLimit = getRecord(I_C_BPartner_CreditLimit.class); final TableRecordReference bpartnerRef = TableRecordReference.of(I_C_BPartner.Table_Name, bpCreditLimit.getC_BPartner_ID()); Services.get(INotificationBL.class) .send(UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC) .recipientUserId(approvedByUserId) .contentADMessage(MSG_Event_RequestApproval) .contentADMessageParam(bpartnerRef) .targetAction(TargetRecordAction.of(bpartnerRef)) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\process\BPartnerCreditLimit_RequestApproval.java
1
请完成以下Java代码
public class User extends GenericJson { @Key private String login; @Key private long id; @Key private String url; @Key private String company; @Key private String blog; @Key private String email; @Key("subscriptions_url") private String subscriptionsUrl; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getCompany() { return company; }
public void setCompany(String company) { this.company = company; } public String getBlog() { return blog; } public void setBlog(String blog) { this.blog = blog; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; } }
repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\googlehttpclientguide\User.java
1
请完成以下Java代码
public String getPassword() { return password; } @Override public String getUsername() { return username; } public void setUsername(final String username) { this.username = username; } public Boolean getActive() { return active; } public void setActive(final Boolean active) { this.active = active; } public void setPassword(final String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? authorities : Collections.emptyList(); } @Override public void setAuthorities(final Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; } @Override public boolean isAccountNonExpired() { return true;
} @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return Boolean.TRUE.equals(active); } @InstanceName @DependsOnProperties({"firstName", "lastName", "username"}) public String getDisplayName() { return String.format("%s %s [%s]", (firstName != null ? firstName : ""), (lastName != null ? lastName : ""), username).trim(); } @Override public String getTimeZoneId() { return timeZoneId; } public void setTimeZoneId(final String timeZoneId) { this.timeZoneId = timeZoneId; } }
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\User.java
1
请完成以下Java代码
public void setMSV3_BestellungPosition_ID (int MSV3_BestellungPosition_ID) { if (MSV3_BestellungPosition_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_BestellungPosition_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_BestellungPosition_ID, Integer.valueOf(MSV3_BestellungPosition_ID)); } /** Get MSV3_BestellungPosition. @return MSV3_BestellungPosition */ @Override public int getMSV3_BestellungPosition_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungPosition_ID); if (ii == null) return 0; return ii.intValue(); } /** * MSV3_Liefervorgabe AD_Reference_ID=540821 * Reference name: MSV3_Liefervorgabe */ public static final int MSV3_LIEFERVORGABE_AD_Reference_ID=540821; /** Normal = Normal */ public static final String MSV3_LIEFERVORGABE_Normal = "Normal"; /** MaxVerbund = MaxVerbund */ public static final String MSV3_LIEFERVORGABE_MaxVerbund = "MaxVerbund"; /** MaxNachlieferung = MaxNachlieferung */ public static final String MSV3_LIEFERVORGABE_MaxNachlieferung = "MaxNachlieferung"; /** MaxDispo = MaxDispo */ public static final String MSV3_LIEFERVORGABE_MaxDispo = "MaxDispo"; /** Set Liefervorgabe. @param MSV3_Liefervorgabe Liefervorgabe */ @Override public void setMSV3_Liefervorgabe (java.lang.String MSV3_Liefervorgabe) { set_Value (COLUMNNAME_MSV3_Liefervorgabe, MSV3_Liefervorgabe); } /** Get Liefervorgabe. @return Liefervorgabe */ @Override public java.lang.String getMSV3_Liefervorgabe () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Liefervorgabe); }
/** Set MSV3_Menge. @param MSV3_Menge MSV3_Menge */ @Override public void setMSV3_Menge (int MSV3_Menge) { set_Value (COLUMNNAME_MSV3_Menge, Integer.valueOf(MSV3_Menge)); } /** Get MSV3_Menge. @return MSV3_Menge */ @Override public int getMSV3_Menge () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Menge); if (ii == null) return 0; return ii.intValue(); } /** Set MSV3_Pzn. @param MSV3_Pzn MSV3_Pzn */ @Override public void setMSV3_Pzn (java.lang.String MSV3_Pzn) { set_Value (COLUMNNAME_MSV3_Pzn, MSV3_Pzn); } /** Get MSV3_Pzn. @return MSV3_Pzn */ @Override public java.lang.String getMSV3_Pzn () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Pzn); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungPosition.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, String> getProperties() { return this.properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public List<String> getMappingResources() { return this.mappingResources; } public @Nullable String getDatabasePlatform() { return this.databasePlatform; } public void setDatabasePlatform(@Nullable String databasePlatform) { this.databasePlatform = databasePlatform; } public @Nullable Database getDatabase() { return this.database; } public void setDatabase(@Nullable Database database) { this.database = database; } public boolean isGenerateDdl() { return this.generateDdl; }
public void setGenerateDdl(boolean generateDdl) { this.generateDdl = generateDdl; } public boolean isShowSql() { return this.showSql; } public void setShowSql(boolean showSql) { this.showSql = showSql; } public @Nullable Boolean getOpenInView() { return this.openInView; } public void setOpenInView(@Nullable Boolean openInView) { this.openInView = openInView; } }
repos\spring-boot-4.0.1\module\spring-boot-jpa\src\main\java\org\springframework\boot\jpa\autoconfigure\JpaProperties.java
2
请完成以下Java代码
public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_MKTG_Channels_ID (final int AD_User_MKTG_Channels_ID) { if (AD_User_MKTG_Channels_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_MKTG_Channels_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_MKTG_Channels_ID, AD_User_MKTG_Channels_ID); } @Override public int getAD_User_MKTG_Channels_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_MKTG_Channels_ID); } @Override public de.metas.marketing.base.model.I_MKTG_Channel getMKTG_Channel() { return get_ValueAsPO(COLUMNNAME_MKTG_Channel_ID, de.metas.marketing.base.model.I_MKTG_Channel.class);
} @Override public void setMKTG_Channel(final de.metas.marketing.base.model.I_MKTG_Channel MKTG_Channel) { set_ValueFromPO(COLUMNNAME_MKTG_Channel_ID, de.metas.marketing.base.model.I_MKTG_Channel.class, MKTG_Channel); } @Override public void setMKTG_Channel_ID (final int MKTG_Channel_ID) { if (MKTG_Channel_ID < 1) set_Value (COLUMNNAME_MKTG_Channel_ID, null); else set_Value (COLUMNNAME_MKTG_Channel_ID, MKTG_Channel_ID); } @Override public int getMKTG_Channel_ID() { return get_ValueAsInt(COLUMNNAME_MKTG_Channel_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_AD_User_MKTG_Channels.java
1
请完成以下Java代码
public String getInfo() { return "StringFilter"; } /** this method actually performs the filtering. */ public String process(String to_process) { System.out.println("\nString to Process in StringFilter = "+to_process); String[] value = split(to_process); StringBuffer new_value = new StringBuffer(); for(int x = 0; x < value.length; x++) { if(hasAttribute(value[x])) new_value.append((String)get(value[x])); else new_value.append(value[x]); if(x != value.length - 1) new_value.append(" "); } return(new_value.toString()); } /** Put a filter somewhere we can get to it. */ public Filter addAttribute(String attribute,Object entity) { put(attribute,entity); return(this); } /** Get rid of a current filter. */ public Filter removeAttribute(String attribute) { try { remove(attribute); } catch(NullPointerException exc) { // don't really care if this throws a null pointer exception } return(this); } /** Does the filter filter this? */ public boolean hasAttribute(String attribute) { return(containsKey(attribute)); } /** Need a way to parse the stream so we can do string comparisons instead of character comparisons. */ private String[] split(String to_split) { if ( to_split == null || to_split.length() == 0 ) { String[] array = new String[0]; return array; } StringBuffer sb = new StringBuffer(to_split.length()+50); StringCharacterIterator sci = new StringCharacterIterator(to_split); int length = 0;
for (char c = sci.first(); c != CharacterIterator.DONE; c = sci.next()) { if(String.valueOf(c).equals(" ")) length++; else if(sci.getEndIndex()-1 == sci.getIndex()) length++; } String[] array = new String[length]; length = 0; String tmp = new String(); for (char c = sci.first(); c!= CharacterIterator.DONE; c = sci.next()) { if(String.valueOf(c).equals(" ")) { array[length] = tmp; tmp = new String(); length++; } else if(sci.getEndIndex()-1 == sci.getIndex()) { tmp = tmp+String.valueOf(sci.last()); array[length] = tmp; tmp = new String(); length++; } else tmp += String.valueOf(c); } return(array); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\StringFilter.java
1
请完成以下Java代码
public void setBytes(byte[] bytes) { this.bytes = bytes; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; }
public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", name=" + name + ", deploymentId=" + deploymentId + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java
1
请完成以下Java代码
private String extractName(String line) { if (line.startsWith("- \"") && line.endsWith("\"")) { return line.substring(3, line.length() - 1); } throw new IllegalStateException("Malformed classpath index line [" + line + "]"); } int size() { return this.lines.size(); } boolean containsEntry(String name) { if (name == null || name.isEmpty()) { return false; } return this.lines.contains(name); } List<URL> getUrls() { return this.lines.stream().map(this::asUrl).toList(); } private URL asUrl(String line) { try { return new File(this.root, line).toURI().toURL(); } catch (MalformedURLException ex) { throw new IllegalStateException(ex); } }
static ClassPathIndexFile loadIfPossible(File root, String location) throws IOException { return loadIfPossible(root, new File(root, location)); } private static ClassPathIndexFile loadIfPossible(File root, File indexFile) throws IOException { if (indexFile.exists() && indexFile.isFile()) { List<String> lines = Files.readAllLines(indexFile.toPath()) .stream() .filter(ClassPathIndexFile::lineHasText) .toList(); return new ClassPathIndexFile(root, lines); } return null; } private static boolean lineHasText(String line) { return !line.trim().isEmpty(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\ClassPathIndexFile.java
1
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * Severity AD_Reference_ID=541949 * Reference name: Severity */ public static final int SEVERITY_AD_Reference_ID=541949; /** Notice = N */ public static final String SEVERITY_Notice = "N"; /** Error = E */ public static final String SEVERITY_Error = "E"; @Override public void setSeverity (final java.lang.String Severity) { set_Value (COLUMNNAME_Severity, Severity); } @Override public java.lang.String getSeverity() { return get_ValueAsString(COLUMNNAME_Severity); } @Override public org.compiere.model.I_AD_Val_Rule getValidation_Rule() { return get_ValueAsPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class); } @Override public void setValidation_Rule(final org.compiere.model.I_AD_Val_Rule Validation_Rule) { set_ValueFromPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, Validation_Rule);
} @Override public void setValidation_Rule_ID (final int Validation_Rule_ID) { if (Validation_Rule_ID < 1) set_Value (COLUMNNAME_Validation_Rule_ID, null); else set_Value (COLUMNNAME_Validation_Rule_ID, Validation_Rule_ID); } @Override public int getValidation_Rule_ID() { return get_ValueAsInt(COLUMNNAME_Validation_Rule_ID); } @Override public void setWarning_Message_ID (final int Warning_Message_ID) { if (Warning_Message_ID < 1) set_Value (COLUMNNAME_Warning_Message_ID, null); else set_Value (COLUMNNAME_Warning_Message_ID, Warning_Message_ID); } @Override public int getWarning_Message_ID() { return get_ValueAsInt(COLUMNNAME_Warning_Message_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule.java
1
请完成以下Java代码
private Connection getConnection() throws SQLException { return ds.getConnection(); } public long runQuery(Boolean autoCommit, Boolean readOnly) { try { return execQuery(count -> runSql(count, autoCommit, readOnly)); } finally { ds.close(); } } private void runSql(AtomicLong count, Boolean autoCommit, Boolean readOnly) { if (Thread.interrupted()) { return; } try (Connection connect = getConnection(); PreparedStatement statement = connect.prepareStatement("select * from transactions where id = ?")) { if (autoCommit != null)
connect.setAutoCommit(autoCommit); if (readOnly != null) connect.setReadOnly(readOnly); statement.setLong(1, 1L + random.nextLong(0, 100000)); ResultSet resultSet = statement.executeQuery(); if (autoCommit != null && !autoCommit) connect.commit(); count.incrementAndGet(); resultSet.close(); } catch (Exception ignored) { } } }
repos\tutorials-master\persistence-modules\read-only-transactions\src\main\java\com\baeldung\readonlytransactions\mysql\dao\MyRepoJdbc.java
1
请完成以下Java代码
public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Passenger passenger = (Passenger) object; return getSeatNumber() == passenger.getSeatNumber() && Objects.equals(getFirstName(), passenger.getFirstName()) && Objects.equals(getLastName(), passenger.getLastName()); } @Override public int hashCode() { return Objects.hash(getFirstName(), getLastName(), getSeatNumber()); } @Override public String toString() { final StringBuilder toStringBuilder = new StringBuilder(getClass().getSimpleName()); toStringBuilder.append("{ id=").append(id); toStringBuilder.append(", firstName='").append(firstName).append('\''); toStringBuilder.append(", lastName='").append(lastName).append('\''); toStringBuilder.append(", seatNumber=").append(seatNumber); toStringBuilder.append('}'); return toStringBuilder.toString();
} Long getId() { return id; } String getFirstName() { return firstName; } String getLastName() { return lastName; } Integer getSeatNumber() { return seatNumber; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\boot\passenger\Passenger.java
1
请在Spring Boot框架中完成以下Java代码
public List<Organization> findAll() { LOGGER.info("Organization find"); return repository.findAll(); } @GetMapping("/{id}") public Organization findById(@PathVariable("id") Long id) { LOGGER.info("Organization find: id={}", id); return repository.findById(id); } @GetMapping("/{id}/with-departments") public Organization findByIdWithDepartments(@PathVariable("id") Long id) { LOGGER.info("Organization with departments find: id={}", id); Organization organization = repository.findById(id); organization.setDepartments(departmentClient.findByOrganization(organization.getId())); return organization; } @GetMapping("/{id}/with-departments-and-employees") public Organization findByIdWithDepartmentsAndEmployees(@PathVariable("id") Long id) {
LOGGER.info("Organization with departments and employees find: id={}", id); Organization organization = repository.findById(id); organization.setDepartments(departmentClient.findByOrganizationWithEmployees(organization.getId())); return organization; } @GetMapping("/{id}/with-employees") public Organization findByIdWithEmployees(@PathVariable("id") Long id) { LOGGER.info("Organization with employees find: id={}", id); Organization organization = repository.findById(id); organization.setEmployees(employeeClient.findByOrganization(organization.getId())); return organization; } }
repos\sample-spring-microservices-new-master\organization-service\src\main\java\pl\piomin\services\organization\controller\OrganizationController.java
2
请在Spring Boot框架中完成以下Java代码
public String getInputText() { return inputText; } public void setInputText(String inputText) { this.inputText = inputText; } public String getOutputText() { return outputText; } public void setOutputText(String outputText) { this.outputText = outputText; } public class Technology { private String name; private String currentVersion; public String getName() { return name;
} public void setName(String name) { this.name = name; } public String getCurrentVersion() { return currentVersion; } public void setCurrentVersion(String currentVersion) { this.currentVersion = currentVersion; } } }
repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\HelloPFBean.java
2
请完成以下Java代码
public class StampedLockDemo { private Map<String, String> map = new HashMap<>(); private Logger logger = LoggerFactory.getLogger(StampedLockDemo.class); private final StampedLock lock = new StampedLock(); public void put(String key, String value) throws InterruptedException { long stamp = lock.writeLock(); try { logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp); map.put(key, value); } finally { lock.unlockWrite(stamp); logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp); } } public String get(String key) throws InterruptedException { long stamp = lock.readLock(); logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp); try { sleep(5000); return map.get(key); } finally { lock.unlockRead(stamp); logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp); } } private String readWithOptimisticLock(String key) throws InterruptedException { long stamp = lock.tryOptimisticRead(); String value = map.get(key); if (!lock.validate(stamp)) { stamp = lock.readLock(); try { sleep(5000); return map.get(key); } finally { lock.unlock(stamp); logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp); } } return value; } public static void main(String[] args) { final int threadCount = 4; final ExecutorService service = Executors.newFixedThreadPool(threadCount); StampedLockDemo object = new StampedLockDemo();
Runnable writeTask = () -> { try { object.put("key1", "value1"); } catch (InterruptedException e) { e.printStackTrace(); } }; Runnable readTask = () -> { try { object.get("key1"); } catch (InterruptedException e) { e.printStackTrace(); } }; Runnable readOptimisticTask = () -> { try { object.readWithOptimisticLock("key1"); } catch (InterruptedException e) { e.printStackTrace(); } }; service.submit(writeTask); service.submit(writeTask); service.submit(readTask); service.submit(readOptimisticTask); service.shutdown(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\StampedLockDemo.java
1
请完成以下Java代码
private FacetsFilterLookupDescriptor createFacetsFilterLookupDescriptor(final DocumentFieldDescriptor field) { final String columnName = field.getDataBinding() .orElseThrow(() -> new AdempiereException("No data binding defined for " + field)) .getColumnName(); final String filterId = FACET_FILTER_ID_PREFIX + columnName; final DocumentFieldDefaultFilterDescriptor fieldFilteringInfo = field.getDefaultFilterInfo(); final DocumentFieldWidgetType fieldWidgetType = extractFilterWidgetType(field); final LookupDescriptor fieldLookupDescriptor = field.getLookupDescriptorForFiltering().orElse(null); final boolean numericKey; if (fieldWidgetType.isLookup() && fieldLookupDescriptor != null) { numericKey = fieldLookupDescriptor.isNumericKey(); } else { numericKey = fieldWidgetType.isNumeric(); }
return FacetsFilterLookupDescriptor.builder() .viewsRepository(viewsRepository) .filterId(filterId) .fieldName(columnName) .fieldWidgetType(fieldWidgetType) .numericKey(numericKey) .maxFacetsToFetch(fieldFilteringInfo.getMaxFacetsToFetch().orElse(getMaxFacetsToFetch())) .fieldLookupDescriptor(fieldLookupDescriptor) .build(); } private int getMaxFacetsToFetch() { return sysConfigs.getIntValue(SYSCONFIG_MAX_FACETS_TO_FETCH, SYSCONFIG_FACETS_TO_FETCH_DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\standard\StandardDocumentFilterDescriptorsProviderFactory.java
1
请完成以下Java代码
public class SimpleFormatter extends Formatter { private static final String DEFAULT_FORMAT = "[%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL] - %8$s %4$s [%7$s] --- %3$s: %5$s%6$s%n"; private final String format = getOrUseDefault("LOG_FORMAT", DEFAULT_FORMAT); private final String pid = getOrUseDefault(LoggingSystemProperty.PID.getEnvironmentVariableName(), "????"); @Override public String format(LogRecord record) { Date date = new Date(record.getMillis()); String source = record.getLoggerName(); String loggerName = record.getLoggerName(); String level = record.getLevel().getLocalizedName(); String message = formatMessage(record); String throwable = getThrowable(record); String thread = getThreadName(); String pid = this.pid; return String.format(this.format, date, source, loggerName, level, message, throwable, thread, pid); } private String getThrowable(LogRecord record) { if (record.getThrown() == null) { return ""; } StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); printWriter.println(); record.getThrown().printStackTrace(printWriter); printWriter.close(); return stringWriter.toString(); } private String getThreadName() {
String name = Thread.currentThread().getName(); return (name != null) ? name : ""; } private static String getOrUseDefault(String key, String defaultValue) { String value = null; try { value = System.getenv(key); } catch (Exception ex) { // ignore } if (value == null) { value = defaultValue; } return System.getProperty(key, value); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\java\SimpleFormatter.java
1
请完成以下Java代码
public void handleEvent(@NonNull final DDOrderCandidateRequestedEvent event) { final DDOrderCandidate ddOrderCandidate = createAndSaveDDOrderCandidate(event); updateMDCandidatesFromDDOrderCandidate(ddOrderCandidate); if (event.isCreateDDOrder()) { ddOrderCandidateService.enqueueToProcess(ddOrderCandidate.getIdNotNull()); } else { Loggables.addLog("Skip creating DD_Order because isCreateDDOrder=false (maybe because PP_Product_Planning.IsCreatePlan=false?)"); } } private void updateMDCandidatesFromDDOrderCandidate(final DDOrderCandidate ddOrderCandidate) { final DDOrderCandidateId ddOrderCandidateId = ddOrderCandidate.getIdNotNull(); if (ddOrderCandidate.getMaterialDispoGroupId() != null) { candidateRepositoryWriteService.updateCandidatesByQuery( CandidatesQuery.builder() .groupId(ddOrderCandidate.getMaterialDispoGroupId()) .businessCase(CandidateBusinessCase.DISTRIBUTION) .build(), candidate -> candidate.withBusinessCaseDetail(DistributionDetail.class, dispoDetail -> dispoDetail.withDdOrderCandidateId(ddOrderCandidateId.getRepoId())) ); } } private DDOrderCandidate createAndSaveDDOrderCandidate(@NonNull final DDOrderCandidateRequestedEvent event) { final DDOrderCandidate ddOrderCandidate = toDDOrderCandidate(event); ddOrderCandidateService.save(ddOrderCandidate); Loggables.withLogger(logger, Level.DEBUG).addLog("Created DD Order candidate: {}", ddOrderCandidate); return ddOrderCandidate; } private DDOrderCandidate toDDOrderCandidate(@NonNull final DDOrderCandidateRequestedEvent event)
{ final PPOrderId forwardPPOrderId = findForwardPPOrderId(event); final DDOrderCandidateData ddOrderCandidateData = event.getDdOrderCandidateData().withPPOrderId(forwardPPOrderId); return DDOrderCandidate.from(ddOrderCandidateData) .dateOrdered(event.getDateOrdered()) .traceId(event.getTraceId()) .build(); } @Nullable private PPOrderId findForwardPPOrderId(@NonNull final DDOrderCandidateRequestedEvent event) { return findForwardPPOrderId(event.getDdOrderCandidateData().getForwardPPOrderRef()); } @Nullable private PPOrderId findForwardPPOrderId(@Nullable final PPOrderRef forwardPPOrderRef) { if (forwardPPOrderRef == null) { return null; } if (forwardPPOrderRef.getPpOrderId() != null) { return forwardPPOrderRef.getPpOrderId(); } if (forwardPPOrderRef.getPpOrderCandidateId() != null) { final PPOrderCandidateId ppOrderCandidateId = forwardPPOrderRef.getPpOrderCandidateId(); final ImmutableSet<PPOrderId> forwardPPOrderIds = ppOrderCandidateDAO.getPPOrderIds(ppOrderCandidateId); return forwardPPOrderIds.size() == 1 ? forwardPPOrderIds.iterator().next() : null; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\material_dispo\DDOrderCandidateRequestedEventHandler.java
1
请在Spring Boot框架中完成以下Java代码
protected void setOwner(TenantId tenantId, NotificationTemplate notificationTemplate, IdProvider idProvider) { notificationTemplate.setTenantId(tenantId); } @Override protected NotificationTemplate prepare(EntitiesImportCtx ctx, NotificationTemplate notificationTemplate, NotificationTemplate oldEntity, EntityExportData<NotificationTemplate> exportData, IdProvider idProvider) { return notificationTemplate; } @Override protected NotificationTemplate saveOrUpdate(EntitiesImportCtx ctx, NotificationTemplate notificationTemplate, EntityExportData<NotificationTemplate> exportData, IdProvider idProvider, CompareResult compareResult) { ConstraintValidator.validateFields(notificationTemplate); return notificationTemplateService.saveNotificationTemplate(ctx.getTenantId(), notificationTemplate); } @Override protected void onEntitySaved(User user, NotificationTemplate savedEntity, NotificationTemplate oldEntity) throws ThingsboardException {
entityActionService.logEntityAction(user, savedEntity.getId(), savedEntity, null, oldEntity == null ? ActionType.ADDED : ActionType.UPDATED, null); } @Override protected NotificationTemplate deepCopy(NotificationTemplate notificationTemplate) { return new NotificationTemplate(notificationTemplate); } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_TEMPLATE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\NotificationTemplateImportService.java
2
请完成以下Java代码
public abstract class AbstractClientUIInstance implements IClientUIInstance { protected final Logger logger = LogManager.getLogger(getClass()); @Override public void warn(final int WindowNo, final Throwable e) { final String AD_Message = "Error"; final String message = buildErrorMessage(e); logger.warn(message, e); warn(WindowNo, AD_Message, message); } @Override public void error(final int WindowNo, final Throwable e) { final String AD_Message = "Error"; final String message = buildErrorMessage(e); // Log the error to console // NOTE: we need to do that because in case something went wrong we need the stacktrace to debug the actual issue // Before removing this please consider that you need to provide an alternative from where the support guys can grab their detailed exception info. logger.warn(message, e); error(WindowNo, AD_Message, message); } protected final String buildErrorMessage(final Throwable e) { String message = e == null ? "@UnknownError@" : e.getLocalizedMessage(); if (Check.isEmpty(message, true) && e != null) { message = e.toString(); } return message; } @Override public Thread createUserThread(final Runnable runnable, final String threadName) { final Thread thread; if (threadName == null) { thread = new Thread(runnable); } else { thread = new Thread(runnable, threadName); } thread.setDaemon(true); return thread; } @Override public final void executeLongOperation(final Object component, final Runnable runnable) {
invoke() .setParentComponent(component) .setLongOperation(true) .setOnFail(OnFail.ThrowException) // backward compatibility .invoke(runnable); } @Override public void invokeLater(final int windowNo, final Runnable runnable) { invoke() .setParentComponentByWindowNo(windowNo) .setInvokeLater(true) .setOnFail(OnFail.ThrowException) // backward compatibility .invoke(runnable); } /** * This method does nothing. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}. */ @Deprecated @Override public void hideBusyDialog() { // nothing } /** * This method does nothing. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#disableServerPush()}. */ @Deprecated @Override public void disableServerPush() { // nothing } /** * This method throws an UnsupportedOperationException. * * @deprecated please check out the deprecation notice in {@link IClientUIInstance#infoNoWait(int, String)}. * @throws UnsupportedOperationException */ @Deprecated @Override public void infoNoWait(int WindowNo, String AD_Message) { throw new UnsupportedOperationException("not implemented"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUIInstance.java
1
请在Spring Boot框架中完成以下Java代码
public String entryDemo() { Entry entry = null; try { // 访问资源 entry = SphU.entry("entry_demo"); // ... 执行业务逻辑 return "执行成功"; } catch (BlockException ex) { return "被拒绝"; } finally { // 释放资源 if (entry != null) { entry.exit(); } } } // 测试 @SentinelResource 注解 @GetMapping("/annotations_demo")
@SentinelResource(value = "annotations_demo_resource", blockHandler = "blockHandler", fallback = "fallback") public String annotationsDemo(@RequestParam(required = false) Integer id) throws InterruptedException { if (id == null) { throw new IllegalArgumentException("id 参数不允许为空"); } return "success..."; } // BlockHandler 处理函数,参数最后多一个 BlockException,其余与原函数一致. public String blockHandler(Integer id, BlockException ex) { return "block:" + ex.getClass().getSimpleName(); } // Fallback 处理函数,函数签名与原函数一致或加一个 Throwable 类型的参数. public String fallback(Integer id, Throwable throwable) { return "fallback:" + throwable.getMessage(); } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\controller\DemoController.java
2
请完成以下Java代码
public class MqttSslClient { private static final String MQTT_URL = "ssl://localhost:1883"; private static final String CLIENT_ID = "MQTT_SSL_JAVA_CLIENT"; private static final String KEY_STORE_FILE = "mqttclient.jks"; private static final String JKS="JKS"; private static final String TLS="TLS"; public static void main(String[] args) { try { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore trustStore = KeyStore.getInstance(JKS); char[] ksPwd = new char[]{0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x5F, 0x6B, 0x73, 0x5F, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64}; trustStore.load(ResourceUtils.getInputStream(MqttSslClient.class.getClassLoader(), KEY_STORE_FILE), ksPwd); tmf.init(trustStore); KeyStore ks = KeyStore.getInstance(JKS); ks.load(ResourceUtils.getInputStream(MqttSslClient.class.getClassLoader(), KEY_STORE_FILE), ksPwd); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); char[] clientPwd = new char[]{0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x5F, 0x6B, 0x65, 0x79, 0x5F, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64}; kmf.init(ks, clientPwd);
KeyManager[] km = kmf.getKeyManagers(); TrustManager[] tm = tmf.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance(TLS); sslContext.init(km, tm, null); MqttConnectOptions options = new MqttConnectOptions(); options.setSocketFactory(sslContext.getSocketFactory()); MqttAsyncClient client = new MqttAsyncClient(MQTT_URL, CLIENT_ID, new MemoryPersistence()); client.connect(options); Thread.sleep(3000); MqttMessage message = new MqttMessage(); message.setPayload("{\"key1\":\"value1\", \"key2\":true, \"key3\": 3.0, \"key4\": 4}".getBytes()); client.publish("v1/devices/me/telemetry", message); client.disconnect(); log.info("Disconnected"); System.exit(0); } catch (Exception e) { log.error("Unexpected exception occurred in MqttSslClient", e); } } }
repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\MqttSslClient.java
1
请完成以下Java代码
public void createPaymentRequestFromTemplate(@NonNull final org.compiere.model.I_C_Invoice invoice, @Nullable final I_C_Payment_Request template) { if (template == null) { throw new AdempiereException(MSG_COULD_NOT_CREATE_PAYMENT_REQUEST).markAsUserValidationError(); } // // Get the selected invoice if (paymentRequestDAO.hasPaymentRequests(invoice)) { throw new AdempiereException(MSG_PAYMENT_REQUEST_FOR_INVOICE_ALREADY_EXISTS_EXCEPTION).markAsUserValidationError(); } paymentRequestBL.createPaymentRequest(invoice, template); } public I_C_Payment_Request createPaymentRequestTemplate(final I_C_BP_BankAccount bankAccount, final BigDecimal amount, final PaymentString paymentString) { final IContextAware contextProvider = PlainContextAware.newOutOfTrx(Env.getCtx());
// // Create it, but do not save it! final I_C_Payment_Request paymentRequestTemplate = InterfaceWrapperHelper.newInstance(I_C_Payment_Request.class, contextProvider); InterfaceWrapperHelper.setSaveDeleteDisabled(paymentRequestTemplate, true); paymentRequestTemplate.setC_BP_BankAccount(bankAccount); paymentRequestTemplate.setAmount(amount); if (paymentString != null) { paymentRequestTemplate.setReference(paymentString.getReferenceNoComplete()); paymentRequestTemplate.setFullPaymentString(paymentString.getRawPaymentString()); } return paymentRequestTemplate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\process\paymentdocumentform\PaymentStringProcessService.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set RMA Type. @param M_RMAType_ID Return Material Authorization Type */ public void setM_RMAType_ID (int M_RMAType_ID) { if (M_RMAType_ID < 1) set_ValueNoCheck (COLUMNNAME_M_RMAType_ID, null); else set_ValueNoCheck (COLUMNNAME_M_RMAType_ID, Integer.valueOf(M_RMAType_ID)); } /** Get RMA Type. @return Return Material Authorization Type */ public int getM_RMAType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_RMAType_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RMAType.java
1
请完成以下Java代码
public void usingDocumentBuilderFactory(String name) { logDebug("001", "Using document builder factory '{}'", name); } public void createdDocumentBuilder() { logDebug("002", "Successfully created new document builder"); } public void documentBuilderFactoryConfiguration(String property, String value) { logDebug("003", "DocumentBuilderFactory configuration '{}' '{}'", property, value); } public void parsingInput() { logDebug("004", "Parsing input into DOM document."); } public DataFormatException unableToCreateParser(Exception cause) { return new DataFormatException(exceptionMessage("005", "Unable to create DocumentBuilder"), cause); } public DataFormatException unableToParseInput(Exception e) { return new DataFormatException(exceptionMessage("006", "Unable to parse input into DOM document"), e); } public DataFormatException unableToCreateTransformer(Exception cause) { return new DataFormatException(exceptionMessage("007", "Unable to create a transformer to write element"), cause); } public DataFormatException unableToTransformElement(Node element, Exception cause) { return new DataFormatException(exceptionMessage("008", "Unable to transform element '{}:{}'", element.getNamespaceURI(), element.getNodeName()), cause); } public DataFormatException unableToWriteInput(Object parameter, Throwable cause) { return new DataFormatException(exceptionMessage("009", "Unable to write object '{}' to xml element", parameter.toString()), cause); }
public DataFormatException unableToDeserialize(Object node, String canonicalClassName, Throwable cause) { return new DataFormatException( exceptionMessage("010", "Cannot deserialize '{}...' to java class '{}'", node.toString(), canonicalClassName), cause); } public DataFormatException unableToCreateMarshaller(Throwable cause) { return new DataFormatException(exceptionMessage("011", "Cannot create marshaller"), cause); } public DataFormatException unableToCreateContext(Throwable cause) { return new DataFormatException(exceptionMessage("012", "Cannot create context"), cause); } public DataFormatException unableToCreateUnmarshaller(Throwable cause) { return new DataFormatException(exceptionMessage("013", "Cannot create unmarshaller"), cause); } public DataFormatException classNotFound(String classname, ClassNotFoundException cause) { return new DataFormatException(exceptionMessage("014", "Class {} not found ", classname), cause); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\xml\DomXmlLogger.java
1
请完成以下Java代码
public void setBudgetStatus (String BudgetStatus) { set_Value (COLUMNNAME_BudgetStatus, BudgetStatus); } /** Get Budget Status. @return Indicates the current status of this budget */ public String getBudgetStatus () { return (String)get_Value(COLUMNNAME_BudgetStatus); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Budget. @param GL_Budget_ID General Ledger Budget */ public void setGL_Budget_ID (int GL_Budget_ID) { if (GL_Budget_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Budget_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Budget_ID, Integer.valueOf(GL_Budget_ID)); } /** Get Budget. @return General Ledger Budget */ public int getGL_Budget_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Primary. @param IsPrimary Indicates if this is the primary budget */ public void setIsPrimary (boolean IsPrimary) { set_Value (COLUMNNAME_IsPrimary, Boolean.valueOf(IsPrimary)); } /** Get Primary. @return Indicates if this is the primary budget */ public boolean isPrimary () { Object oo = get_Value(COLUMNNAME_IsPrimary); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Budget.java
1
请完成以下Java代码
private Method write(Object base) { if (this.write == null) { this.write = Util.getMethod(this.owner, base, getWriteMethod()); } return this.write; } private Method read(Object base) { if (this.read == null) { this.read = Util.getMethod(this.owner, base, getReadMethod()); } return this.read; } abstract Method getWriteMethod(); abstract Method getReadMethod(); abstract String getName(); } private BeanProperty property(Object base, Object property) { Class<?> type = base.getClass(); String prop = property.toString(); BeanProperties props = this.cache.get(type.getName()); if (props == null || type != props.getType()) { props = BeanSupport.getInstance().getBeanProperties(type); this.cache.put(type.getName(), props); } return props.get(prop); } private static final class ConcurrentCache<K, V> { private final int size; private final Map<K, V> eden;
private final Map<K, V> longterm; ConcurrentCache(int size) { this.size = size; this.eden = new ConcurrentHashMap<>(size); this.longterm = new WeakHashMap<>(size); } public V get(K key) { V value = this.eden.get(key); if (value == null) { synchronized (longterm) { value = this.longterm.get(key); } if (value != null) { this.eden.put(key, value); } } return value; } public void put(K key, V value) { if (this.eden.size() >= this.size) { synchronized (longterm) { this.longterm.putAll(this.eden); } this.eden.clear(); } this.eden.put(key, value); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\BeanELResolver.java
1
请在Spring Boot框架中完成以下Java代码
public static class Xa { /** * XA datasource fully qualified name. */ private @Nullable String dataSourceClassName; /** * Properties to pass to the XA data source. */ private Map<String, String> properties = new LinkedHashMap<>(); public @Nullable String getDataSourceClassName() { return this.dataSourceClassName; } public void setDataSourceClassName(@Nullable String dataSourceClassName) { this.dataSourceClassName = dataSourceClassName; } public Map<String, String> getProperties() { return this.properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; }
} static class DataSourceBeanCreationException extends BeanCreationException { private final DataSourceProperties properties; private final EmbeddedDatabaseConnection connection; DataSourceBeanCreationException(String message, DataSourceProperties properties, EmbeddedDatabaseConnection connection) { super(message); this.properties = properties; this.connection = connection; } DataSourceProperties getProperties() { return this.properties; } EmbeddedDatabaseConnection getConnection() { return this.connection; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class PickingPlanLine { @NonNull PickingPlanLineType type; @NonNull SourceDocumentInfo sourceDocumentInfo; // // What to pick? @NonNull ProductId productId; @NonNull Quantity qty; // // From where to pick? // ... or where to issue? @With @Nullable PickFromHU pickFromHU; @Nullable PickFromPickingOrder pickFromPickingOrder; @Nullable IssueToBOMLine issueToBOMLine; @Builder(toBuilder = true) private PickingPlanLine( @NonNull final PickingPlanLineType type, @NonNull final SourceDocumentInfo sourceDocumentInfo, // @NonNull final ProductId productId, @NonNull final Quantity qty, // @Nullable final PickFromHU pickFromHU, @Nullable final PickFromPickingOrder pickFromPickingOrder, @Nullable final IssueToBOMLine issueToBOMLine) { this.type = type; this.sourceDocumentInfo = sourceDocumentInfo; this.productId = productId; this.qty = qty; switch (type) { case PICK_FROM_HU: { this.pickFromHU = pickFromHU; this.pickFromPickingOrder = null; this.issueToBOMLine = null; break; } case PICK_FROM_PICKING_ORDER: { this.pickFromHU = null; this.pickFromPickingOrder = pickFromPickingOrder; this.issueToBOMLine = null; break;
} case ISSUE_COMPONENTS_TO_PICKING_ORDER: { this.pickFromHU = null; this.pickFromPickingOrder = null; this.issueToBOMLine = issueToBOMLine; break; } case UNALLOCABLE: { this.pickFromHU = null; this.pickFromPickingOrder = null; this.issueToBOMLine = null; break; } default: { throw new AdempiereException("Unknown type: " + type); } } } public PickingPlanLine withQty(@NonNull final Quantity qty) { return Objects.equals(this.qty, qty) ? this : toBuilder().qty(qty).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\model\PickingPlanLine.java
2
请完成以下Java代码
public class PP_Order_Candidate_AlreadyMaturedForOrdering extends PP_Order_Candidate_EnqueueSelectionForOrdering { @Override protected int createSelection() { final IQueryBuilder<I_PP_Order_Candidate> queryBuilder = createOCQueryBuilder(); final PInstanceId adPInstanceId = getPinstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited); return queryBuilder .create() .createSelection(adPInstanceId); }
@Override protected IQueryBuilder<I_PP_Order_Candidate> createOCQueryBuilder() { return queryBL .createQueryBuilder(I_PP_Order_Candidate.class) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_Processed, false) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsClosed, false) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsMaturing, true) .addCompareFilter(I_PP_Order_Candidate.COLUMNNAME_QtyToProcess, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO) .addCompareFilter(I_PP_Order_Candidate.COLUMNNAME_DatePromised, CompareQueryFilter.Operator.LESS_OR_EQUAL, Env.getDate()) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .orderBy(I_PP_Order_Candidate.COLUMNNAME_SeqNo) .orderBy(I_PP_Order_Candidate.COLUMNNAME_PP_Order_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\process\PP_Order_Candidate_AlreadyMaturedForOrdering.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Person getAuthor() { return author;
} public void setAuthor(Person author) { this.author = author; } @Override public String toString() { return "Post{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + '}'; } }
repos\tutorials-master\persistence-modules\blaze-persistence\src\main\java\com\baeldung\model\Post.java
1
请完成以下Java代码
public String getRace() { return race; } public void setRace(String race) { this.race = race; } public void setCharacterClass(String characterClass) { this.characterClass = characterClass; } public void setBio(String bio) { this.bio = bio; }
public String getCityOfOrigin() { return cityOfOrigin; } public void setCityOfOrigin(String cityOfOrigin) { this.cityOfOrigin = cityOfOrigin; } public String getFavoriteWeapon() { return favoriteWeapon; } public void setFavoriteWeapon(String favoriteWeapon) { this.favoriteWeapon = favoriteWeapon; } }
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springaistructuredoutput\dto\Character.java
1
请完成以下Java代码
public java.lang.String getShipper_CountryISO2Code() { return get_ValueAsString(COLUMNNAME_Shipper_CountryISO2Code); } @Override public void setShipper_EORI (final @Nullable java.lang.String Shipper_EORI) { set_Value (COLUMNNAME_Shipper_EORI, Shipper_EORI); } @Override public java.lang.String getShipper_EORI() { return get_ValueAsString(COLUMNNAME_Shipper_EORI); } @Override public void setShipper_Name1 (final @Nullable java.lang.String Shipper_Name1) { set_Value (COLUMNNAME_Shipper_Name1, Shipper_Name1); } @Override public java.lang.String getShipper_Name1() { return get_ValueAsString(COLUMNNAME_Shipper_Name1); } @Override public void setShipper_Name2 (final @Nullable java.lang.String Shipper_Name2) { set_Value (COLUMNNAME_Shipper_Name2, Shipper_Name2); } @Override public java.lang.String getShipper_Name2() { return get_ValueAsString(COLUMNNAME_Shipper_Name2); } @Override public void setShipper_StreetName1 (final @Nullable java.lang.String Shipper_StreetName1) { set_Value (COLUMNNAME_Shipper_StreetName1, Shipper_StreetName1); } @Override public java.lang.String getShipper_StreetName1()
{ return get_ValueAsString(COLUMNNAME_Shipper_StreetName1); } @Override public void setShipper_StreetName2 (final @Nullable java.lang.String Shipper_StreetName2) { set_Value (COLUMNNAME_Shipper_StreetName2, Shipper_StreetName2); } @Override public java.lang.String getShipper_StreetName2() { return get_ValueAsString(COLUMNNAME_Shipper_StreetName2); } @Override public void setShipper_StreetNumber (final @Nullable java.lang.String Shipper_StreetNumber) { set_Value (COLUMNNAME_Shipper_StreetNumber, Shipper_StreetNumber); } @Override public java.lang.String getShipper_StreetNumber() { return get_ValueAsString(COLUMNNAME_Shipper_StreetNumber); } @Override public void setShipper_ZipCode (final @Nullable java.lang.String Shipper_ZipCode) { set_Value (COLUMNNAME_Shipper_ZipCode, Shipper_ZipCode); } @Override public java.lang.String getShipper_ZipCode() { return get_ValueAsString(COLUMNNAME_Shipper_ZipCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder.java
1
请完成以下Java代码
public void postConstruct() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @Override public void onNew(@NonNull final ICalloutRecord calloutRecord) { final I_M_CostRevaluation costRevaluation = calloutRecord.getModel(I_M_CostRevaluation.class); setDocTypeId(costRevaluation); } @CalloutMethod(columnNames = I_M_CostRevaluation.COLUMNNAME_C_DocType_ID) public void onDocTypeChanged(@NonNull final I_M_CostRevaluation costRevaluation) { setDocumentNo(costRevaluation); } private void setDocTypeId(final I_M_CostRevaluation costRevaluation) { final DocTypeId docTypeId = docTypeDAO.getDocTypeIdOrNull(DocTypeQuery.builder() .docBaseType(DocBaseType.CostRevaluation) .docSubType(DocTypeQuery.DOCSUBTYPE_Any) .adClientId(costRevaluation.getAD_Client_ID()) .adOrgId(costRevaluation.getAD_Org_ID()) .build()); if (docTypeId == null) { return; } costRevaluation.setC_DocType_ID(docTypeId.getRepoId()); } private void setDocumentNo(final I_M_CostRevaluation costRevaluation) {
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(costRevaluation.getC_DocType_ID()); if (docTypeId == null) { return; } final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class) .createPreliminaryDocumentNoBuilder() .setNewDocType(docTypeDAO.getById(docTypeId)) .setOldDocumentNo(costRevaluation.getDocumentNo()) .setDocumentModel(costRevaluation) .buildOrNull(); if (documentNoInfo != null && documentNoInfo.isDocNoControlled()) { costRevaluation.setDocumentNo(documentNoInfo.getDocumentNo()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\callout\M_CostRevaluation.java
1
请在Spring Boot框架中完成以下Java代码
public String apiToken() { return obtain(DynatraceProperties::getApiToken, DynatraceConfig.super::apiToken); } @Override public String deviceId() { return obtain(v1(V1::getDeviceId), DynatraceConfig.super::deviceId); } @Override public String technologyType() { return obtain(v1(V1::getTechnologyType), DynatraceConfig.super::technologyType); } @Override public String uri() { return obtain(DynatraceProperties::getUri, DynatraceConfig.super::uri); } @Override public @Nullable String group() { return get(v1(V1::getGroup), DynatraceConfig.super::group); } @Override public DynatraceApiVersion apiVersion() { return obtain((properties) -> (properties.getV1().getDeviceId() != null) ? DynatraceApiVersion.V1 : DynatraceApiVersion.V2, DynatraceConfig.super::apiVersion); } @Override public String metricKeyPrefix() { return obtain(v2(V2::getMetricKeyPrefix), DynatraceConfig.super::metricKeyPrefix); } @Override public Map<String, String> defaultDimensions() { return obtain(v2(V2::getDefaultDimensions), DynatraceConfig.super::defaultDimensions); }
@Override public boolean enrichWithDynatraceMetadata() { return obtain(v2(V2::isEnrichWithDynatraceMetadata), DynatraceConfig.super::enrichWithDynatraceMetadata); } @Override public boolean useDynatraceSummaryInstruments() { return obtain(v2(V2::isUseDynatraceSummaryInstruments), DynatraceConfig.super::useDynatraceSummaryInstruments); } @Override public boolean exportMeterMetadata() { return obtain(v2(V2::isExportMeterMetadata), DynatraceConfig.super::exportMeterMetadata); } private <V> Getter<DynatraceProperties, V> v1(Getter<V1, V> getter) { return (properties) -> getter.get(properties.getV1()); } private <V> Getter<DynatraceProperties, V> v2(Getter<V2, V> getter) { return (properties) -> getter.get(properties.getV2()); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatracePropertiesConfigAdapter.java
2
请完成以下Java代码
public CaseInstanceQuery withoutTenantId() { tenantIds = null; isTenantIdSet = true; return this; } public CaseInstanceQuery active() { state = CaseExecutionState.ACTIVE; return this; } public CaseInstanceQuery completed() { state = CaseExecutionState.COMPLETED; return this; } public CaseInstanceQuery terminated() { state = CaseExecutionState.TERMINATED; return this; } //ordering ///////////////////////////////////////////////////////////////// public CaseInstanceQuery orderByCaseInstanceId() { orderBy(CaseInstanceQueryProperty.CASE_INSTANCE_ID); return this; } public CaseInstanceQuery orderByCaseDefinitionKey() { orderBy(new QueryOrderingProperty(QueryOrderingProperty.RELATION_CASE_DEFINITION, CaseInstanceQueryProperty.CASE_DEFINITION_KEY)); return this; } public CaseInstanceQuery orderByCaseDefinitionId() { orderBy(CaseInstanceQueryProperty.CASE_DEFINITION_ID); return this; } public CaseInstanceQuery orderByTenantId() { orderBy(CaseInstanceQueryProperty.TENANT_ID); return this; } //results ///////////////////////////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getCaseExecutionManager() .findCaseInstanceCountByQueryCriteria(this); } public List<CaseInstance> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getCaseExecutionManager() .findCaseInstanceByQueryCriteria(this, page); } //getters ///////////////////////////////////////////////////////////////// public String getCaseInstanceId() { return caseExecutionId; } public String getCaseExecutionId() { return caseExecutionId; } public String getActivityId() { return null; } public String getBusinessKey() { return businessKey;
} public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getDeploymentId() { return deploymentId; } public CaseExecutionState getState() { return state; } public boolean isCaseInstancesOnly() { return true; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public Boolean isRequired() { return required; } public Boolean isRepeatable() { return repeatable; } public Boolean isRepetition() { return repetition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseInstanceQueryImpl.java
1
请完成以下Java代码
public int getDLM_Referenced_Table_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referenced_Table_ID); if (ii == null) { return 0; } return ii.intValue(); } @Override public org.compiere.model.I_AD_Column getDLM_Referencing_Column() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DLM_Referencing_Column_ID, org.compiere.model.I_AD_Column.class); } @Override public void setDLM_Referencing_Column(final org.compiere.model.I_AD_Column DLM_Referencing_Column) { set_ValueFromPO(COLUMNNAME_DLM_Referencing_Column_ID, org.compiere.model.I_AD_Column.class, DLM_Referencing_Column); } /** * Set Referenzierende Spalte. * * @param DLM_Referencing_Column_ID Referenzierende Spalte */ @Override public void setDLM_Referencing_Column_ID(final int DLM_Referencing_Column_ID) { if (DLM_Referencing_Column_ID < 1) { set_Value(COLUMNNAME_DLM_Referencing_Column_ID, null); } else { set_Value(COLUMNNAME_DLM_Referencing_Column_ID, Integer.valueOf(DLM_Referencing_Column_ID)); } } /** * Get Referenzierende Spalte. * * @return Referenzierende Spalte */ @Override public int getDLM_Referencing_Column_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Column_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Partitionsgrenze.
* * @param IsPartitionBoundary * Falls ja, dann gehören Datensatze, die über die jeweilige Referenz verknüpft sind nicht zur selben Partition. */ @Override public void setIsPartitionBoundary(final boolean IsPartitionBoundary) { set_Value(COLUMNNAME_IsPartitionBoundary, Boolean.valueOf(IsPartitionBoundary)); } /** * Get Partitionsgrenze. * * @return Falls ja, dann gehören Datensatze, die über die jeweilige Referenz verknüpft sind nicht zur selben Partition. */ @Override public boolean isPartitionBoundary() { final Object oo = get_Value(COLUMNNAME_IsPartitionBoundary); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Reference.java
1
请完成以下Java代码
private void addExceptionMapping(Class<? extends Throwable> exceptionType, Method method) { Method oldMethod = mappedMethods.put(exceptionType, method); if (oldMethod != null && !oldMethod.equals(method)) { throw new IllegalStateException("Ambiguous @GrpcExceptionHandler method mapped for [" + exceptionType + "]: {" + oldMethod + ", " + method + "}"); } } /** * When given exception type is subtype of already provided mapped exception, this returns a valid mapped method to * be later executed. * * @param exceptionType exception to check * @param <E> type of exception * @return mapped method instance with its method */ @NonNull public <E extends Throwable> Map.Entry<Object, Method> resolveMethodWithInstance(Class<E> exceptionType) { Method value = extractExtendedThrowable(exceptionType); if (value == null) { return new SimpleImmutableEntry<>(null, null); } Class<?> methodClass = value.getDeclaringClass(); Object key = grpcAdviceDiscoverer.getAnnotatedBeans() .values() .stream() .filter(obj -> methodClass.isAssignableFrom(obj.getClass())) .findFirst() .orElse(null);
return new SimpleImmutableEntry<>(key, value); } /** * Lookup if a method is mapped to given exception. * * @param exception exception to check * @param <E> type of exception * @return true if mapped to valid method */ public <E extends Throwable> boolean isMethodMappedForException(Class<E> exception) { return extractExtendedThrowable(exception) != null; } @Nullable private <E extends Throwable> Method extractExtendedThrowable(Class<E> exceptionType) { return mappedMethods.keySet() .stream() .filter(ex -> ex.isAssignableFrom(exceptionType)) .min(new ExceptionDepthComparator(exceptionType)) .map(mappedMethods::get) .orElse(null); } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\advice\GrpcExceptionHandlerMethodResolver.java
1
请完成以下Java代码
public int getC_Element_ID() { return get_ValueAsInt(COLUMNNAME_C_Element_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * ElementType AD_Reference_ID=116 * Reference name: C_Element Type */ public static final int ELEMENTTYPE_AD_Reference_ID=116; /** Account = A */ public static final String ELEMENTTYPE_Account = "A"; /** UserDefined = U */ public static final String ELEMENTTYPE_UserDefined = "U"; @Override public void setElementType (final java.lang.String ElementType) { set_ValueNoCheck (COLUMNNAME_ElementType, ElementType); } @Override public java.lang.String getElementType() { return get_ValueAsString(COLUMNNAME_ElementType); } @Override public void setIsBalancing (final boolean IsBalancing) { set_Value (COLUMNNAME_IsBalancing, IsBalancing); } @Override public boolean isBalancing() { return get_ValueAsBoolean(COLUMNNAME_IsBalancing); } @Override public void setIsNaturalAccount (final boolean IsNaturalAccount) { set_Value (COLUMNNAME_IsNaturalAccount, IsNaturalAccount); }
@Override public boolean isNaturalAccount() { return get_ValueAsBoolean(COLUMNNAME_IsNaturalAccount); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setVFormat (final @Nullable java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } @Override public java.lang.String getVFormat() { return get_ValueAsString(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Element.java
1
请完成以下Java代码
/* package */boolean saveIfValidAndHasChanges(final boolean throwEx) { final Document parametersDocument = getParametersDocument(); final DocumentSaveStatus parametersSaveStatus = parametersDocument.saveIfValidAndHasChanges(); final boolean saved = parametersSaveStatus.isSaved(); if (!saved && throwEx) { throw new ProcessExecutionException(parametersSaveStatus.getReason()); } return saved; } /* package */ IAutoCloseable lockForReading() { final ReadLock readLock = readwriteLock.readLock(); logger.debug("Acquiring read lock for {}: {}", this, readLock); readLock.lock(); logger.debug("Acquired read lock for {}: {}", this, readLock); return () -> { readLock.unlock(); logger.debug("Released read lock for {}: {}", this, readLock); }; } /* package */ IAutoCloseable lockForWriting() { final WriteLock writeLock = readwriteLock.writeLock(); logger.debug("Acquiring write lock for {}: {}", this, writeLock); writeLock.lock(); logger.debug("Acquired write lock for {}: {}", this, writeLock); return () -> { writeLock.unlock(); logger.debug("Released write lock for {}: {}", this, writeLock); }; } /** * Try to get the target output type from the specific process param {@link de.metas.report.server.ReportConstants#REPORT_PARAM_REPORT_FORMAT}, * if the parameter is missing, the default output type is returned. *
* @see OutputType#getDefault() */ private OutputType getTargetOutputType() { final IDocumentFieldView formatField = parameters.getFieldViewOrNull(REPORT_PARAM_REPORT_FORMAT); if (formatField != null) { final LookupValue outputTypeParamValue = formatField.getValueAs(LookupValue.class); if (outputTypeParamValue != null) { final Optional<OutputType> targetOutputType = OutputType.getOutputTypeByFileExtension(String.valueOf(formatField.getValueAs(LookupValue.class).getId())); if (targetOutputType.isPresent()) { return targetOutputType.get(); } } } return OutputType.getDefault(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessInstanceController.java
1
请在Spring Boot框架中完成以下Java代码
public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getIdPrefix() { // id prefix is empty because sequence is used instead of id prefix return ""; } @Override public void setLogNumber(long logNumber) { this.logNumber = logNumber; } @Override public long getLogNumber() { return logNumber; } @Override public String getType() { return type; } @Override public String getTaskId() { return taskId; } @Override public Date getTimeStamp() { return timeStamp; }
@Override public String getUserId() { return userId; } @Override public String getData() { return data; } @Override public String getExecutionId() { return executionId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String toString() { return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")"; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java
2
请完成以下Java代码
public final class SecurityUtils { private SecurityUtils() { } /** * Get the login of the current user. * * @return the login of the current user */ public static Optional<String> getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { return (String) authentication.getPrincipal(); } return null; }); } /** * Get the JWT of the current user. * * @return the JWT of the current user */ public static Optional<String> getCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .filter(authentication -> authentication.getCredentials() instanceof String) .map(authentication -> (String) authentication.getCredentials()); } /** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise */
public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> authentication.getAuthorities().stream() .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS))) .orElse(false); } /** * If the current user has a specific authority (security role). * <p> * The name of this method comes from the isUserInRole() method in the Servlet API * * @param authority the authority to check * @return true if the current user has the authority, false otherwise */ public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> authentication.getAuthorities().stream() .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority))) .orElse(false); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\security\SecurityUtils.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isFallbackToSystemLocale() { return this.fallbackToSystemLocale; } public void setFallbackToSystemLocale(boolean fallbackToSystemLocale) { this.fallbackToSystemLocale = fallbackToSystemLocale; } public boolean isAlwaysUseMessageFormat() { return this.alwaysUseMessageFormat; } public void setAlwaysUseMessageFormat(boolean alwaysUseMessageFormat) { this.alwaysUseMessageFormat = alwaysUseMessageFormat; } public boolean isUseCodeAsDefaultMessage() {
return this.useCodeAsDefaultMessage; } public void setUseCodeAsDefaultMessage(boolean useCodeAsDefaultMessage) { this.useCodeAsDefaultMessage = useCodeAsDefaultMessage; } public @Nullable List<Resource> getCommonMessages() { return this.commonMessages; } public void setCommonMessages(@Nullable List<Resource> commonMessages) { this.commonMessages = commonMessages; } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\context\MessageSourceProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class LoggingAspect { private static Logger logger = Logger.getLogger(LoggingAspect.class.getName()); private ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("[yyyy-mm-dd hh:mm:ss:SSS]"); } }; @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.pointcutadvice.dao.FooDao.*(..))") public void repositoryMethods() { } @Pointcut("within(com.baeldung..*) && @annotation(com.baeldung.pointcutadvice.annotations.Loggable)") public void loggableMethods() { } @Pointcut("within(com.baeldung..*) && @args(com.baeldung.pointcutadvice.annotations.Entity)") public void methodsAcceptingEntities() { }
@Before("repositoryMethods()") public void logMethodCall(JoinPoint jp) { String methodName = jp.getSignature().getName(); logger.info(sdf.get().format(new Date()) + methodName); } @Before("loggableMethods()") public void logMethod(JoinPoint jp) { String methodName = jp.getSignature().getName(); logger.info("Executing method: " + methodName); } @Before("methodsAcceptingEntities()") public void logMethodAcceptionEntityAnnotatedBean(JoinPoint jp) { logger.info("Accepting beans with @Entity annotation: " + jp.getArgs()[0]); } }
repos\tutorials-master\spring-aop\src\main\java\com\baeldung\pointcutadvice\LoggingAspect.java
2
请完成以下Java代码
public FilterRestService getFilterRestService() { return super.getFilterRestService(null); } @Path(MetricsRestService.PATH) public MetricsRestService getMetricsRestService() { return super.getMetricsRestService(null); } @Path(DecisionDefinitionRestService.PATH) public DecisionDefinitionRestService getDecisionDefinitionRestService() { return super.getDecisionDefinitionRestService(null); } @Path(DecisionRequirementsDefinitionRestService.PATH) public DecisionRequirementsDefinitionRestService getDecisionRequirementsDefinitionRestService() { return super.getDecisionRequirementsDefinitionRestService(null); } @Path(ExternalTaskRestService.PATH) public ExternalTaskRestService getExternalTaskRestService() { return super.getExternalTaskRestService(null); } @Path(MigrationRestService.PATH) public MigrationRestService getMigrationRestService() { return super.getMigrationRestService(null); } @Path(ModificationRestService.PATH) public ModificationRestService getModificationRestService() { return super.getModificationRestService(null); } @Path(BatchRestService.PATH) public BatchRestService getBatchRestService() { return super.getBatchRestService(null); } @Path(TenantRestService.PATH) public TenantRestService getTenantRestService() { return super.getTenantRestService(null); } @Path(SignalRestService.PATH) public SignalRestService getSignalRestService() { return super.getSignalRestService(null); } @Path(ConditionRestService.PATH) public ConditionRestService getConditionRestService() { return super.getConditionRestService(null);
} @Path(OptimizeRestService.PATH) public OptimizeRestService getOptimizeRestService() { return super.getOptimizeRestService(null); } @Path(VersionRestService.PATH) public VersionRestService getVersionRestService() { return super.getVersionRestService(null); } @Path(SchemaLogRestService.PATH) public SchemaLogRestService getSchemaLogRestService() { return super.getSchemaLogRestService(null); } @Path(EventSubscriptionRestService.PATH) public EventSubscriptionRestService getEventSubscriptionRestService() { return super.getEventSubscriptionRestService(null); } @Path(TelemetryRestService.PATH) public TelemetryRestService getTelemetryRestService() { return super.getTelemetryRestService(null); } @Override protected URI getRelativeEngineUri(String engineName) { // the default engine return URI.create("/"); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DefaultProcessEngineRestServiceImpl.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Integer getHidden() { return hidden; } public void setHidden(Integer hidden) { this.hidden = hidden; } @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(", parentId=").append(parentId); sb.append(", createTime=").append(createTime); sb.append(", title=").append(title); sb.append(", level=").append(level); sb.append(", sort=").append(sort); sb.append(", name=").append(name); sb.append(", icon=").append(icon); sb.append(", hidden=").append(hidden); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMenu.java
1
请在Spring Boot框架中完成以下Java代码
public Converter<List<AuthorityRuleCorrectEntity>, String> authorityRuleRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<AuthorityRuleCorrectEntity>> authorityRuleRuleEntityDecoder() { return s -> JSON.parseArray(s, AuthorityRuleCorrectEntity.class); } /** * 网关API * * @return * @throws Exception */ @Bean public Converter<List<ApiDefinitionEntity>, String> apiDefinitionEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<ApiDefinitionEntity>> apiDefinitionEntityDecoder() { return s -> JSON.parseArray(s, ApiDefinitionEntity.class); } /** * 网关flowRule * * @return * @throws Exception */ @Bean public Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() {
return JSON::toJSONString; } @Bean public Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() { return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class); } @Bean public ConfigService nacosConfigService() throws Exception { Properties properties=new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR,nacosConfigProperties.getServerAddr()); if(StringUtils.isNotBlank(nacosConfigProperties.getUsername())){ properties.put(PropertyKeyConst.USERNAME,nacosConfigProperties.getUsername()); } if(StringUtils.isNotBlank(nacosConfigProperties.getPassword())){ properties.put(PropertyKeyConst.PASSWORD,nacosConfigProperties.getPassword()); } if(StringUtils.isNotBlank(nacosConfigProperties.getNamespace())){ properties.put(PropertyKeyConst.NAMESPACE,nacosConfigProperties.getNamespace()); } return ConfigFactory.createConfigService(properties); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\SentinelConfig.java
2
请完成以下Java代码
public class MAssetUse extends X_A_Asset_Use { /** * */ private static final long serialVersionUID = -1247516669047870893L; public MAssetUse (Properties ctx, int A_Asset_Use_ID, String trxName) { super (ctx, A_Asset_Use_ID, trxName); if (A_Asset_Use_ID == 0) { // empty block } } // MAssetUse /** * Load Constructor * @param ctx context * @param rs result set record */ public MAssetUse (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MAssetUse /** * After Save * @param newRecord new * @return true */ protected boolean afterSave (boolean newRecord,boolean success) { log.info("afterSave"); int p_A_Asset_ID = 0; int total_unitsused = 0;
p_A_Asset_ID = getA_Asset_ID(); String sql = "SELECT SUM(USEUNITS) FROM A_Asset_use WHERE A_Asset_ID=? and usedate <= now()"; total_unitsused = DB.getSQLValue(null, sql, getA_Asset_ID()); MAsset asset = new MAsset (getCtx(), p_A_Asset_ID, null); asset.setUseUnits(total_unitsused); asset.setProcessing(false); asset.save(); MAssetChange change = new MAssetChange (getCtx(), 0,null); change.setA_Asset_ID(p_A_Asset_ID); change.setChangeType("USE"); MRefList RefList = new MRefList (getCtx(), 0, null); change.setTextDetails(RefList.getListDescription (getCtx(),"A_Update_Type" , "USE")); change.setUseUnits(getUseUnits()); change.save(); return true; } // afterSave }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MAssetUse.java
1
请完成以下Java代码
private static ArrayList<MaterialCockpitRow> extractRows( @NonNull final ImmutableMap<DocumentId, MaterialCockpitRow> documentId2TopLevelRows, @NonNull final DocumentIdsSelection rowIds) { final ArrayList<MaterialCockpitRow> rowsToInvalidate = new ArrayList<>(); if (rowIds.isAll()) { rowsToInvalidate.addAll(RowsDataTool.extractAllRows(documentId2TopLevelRows.values()).values()); } else { for (final DocumentId documentId : rowIds.toSet()) { // we can be sure the documentId is in this map, because those ids were returned by our own getDocumentIdsToInvalidate() method. final MaterialCockpitRow row = documentId2TopLevelRows.get(documentId); rowsToInvalidate.add(row); } } return rowsToInvalidate; } private List<I_MD_Cockpit> loadCockpitRecords(@NonNull final Set<Integer> ids) { return InterfaceWrapperHelper.loadByIds(ids, I_MD_Cockpit.class); } private List<I_MD_Stock> loadStockRecords(@NonNull final Set<Integer> ids) { return InterfaceWrapperHelper.loadByIds(ids, I_MD_Stock.class); }
private CreateRowsRequestBuilder createNewBuilder(@NonNull final LocalDate localDate) { return MaterialCockpitRowFactory.CreateRowsRequest.builder() .date(localDate) .detailsRowAggregation(detailsRowAggregation); } @NonNull private ProductWithDemandSupplyCollection loadQuantitiesRecords(@NonNull final Collection<MaterialCockpitRow> rows) { final ImmutableSet<ProductId> productIds = rows.stream() .map(MaterialCockpitRow::getProductId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); return qtyDemandSupplyRepository.getByProductIds(productIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRowsData.java
1
请完成以下Java代码
public static DegradeRuleEntity fromDegradeRule(String app, String ip, Integer port, DegradeRule rule) { DegradeRuleEntity entity = new DegradeRuleEntity(); entity.setApp(app); entity.setIp(ip); entity.setPort(port); entity.setResource(rule.getResource()); entity.setLimitApp(rule.getLimitApp()); entity.setCount(rule.getCount()); entity.setTimeWindow(rule.getTimeWindow()); entity.setGrade(rule.getGrade()); return entity; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public Double getCount() { return count; } public void setCount(Double count) { this.count = count; }
public Integer getTimeWindow() { return timeWindow; } public void setTimeWindow(Integer timeWindow) { this.timeWindow = timeWindow; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public DegradeRule toRule() { DegradeRule rule = new DegradeRule(); rule.setResource(resource); rule.setLimitApp(limitApp); rule.setCount(count); rule.setTimeWindow(timeWindow); rule.setGrade(grade); return rule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\DegradeRuleEntity.java
1
请完成以下Java代码
public Set<String> getColumnNames() { return document.getFieldNames(); } @Override public int getColumnIndex(final String columnName) { throw new UnsupportedOperationException("DocumentInterfaceWrapper has no supported for column indexes"); } @Override public boolean isVirtualColumn(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isReadonlyVirtualField(); } @Override public boolean isKeyColumnName(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isKey(); } @Override public boolean isCalculated(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isCalculated(); } @Override public boolean setValueNoCheck(final String columnName, final Object value) { return setValue(columnName, value); }
@Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value) { // TODO: implement throw new UnsupportedOperationException(); } @Override public boolean invokeEquals(final Object[] methodArgs) { // TODO: implement throw new UnsupportedOperationException(); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapper.java
1
请完成以下Spring Boot application配置
zuul: routes: serviceSimple: path: /greeting/simple url: forward:/ serviceAdvanced: path: /greeting/advanced url: forward:/ ratelimit: enabled: true repository: JPA policy-list: serviceSimple: - limit: 5 refresh-interval: 60 type:
- origin serviceAdvanced: - limit: 1 refresh-interval: 2 type: - origin strip-prefix: true
repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul\spring-zuul-rate-limiting\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class StockEstimateEventService { @NonNull private final CandidateRepositoryRetrieval candidateRepositoryRetrieval; public StockEstimateEventService(@NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval) { this.candidateRepositoryRetrieval = candidateRepositoryRetrieval; } @Nullable public Candidate retrieveExistingStockEstimateCandidateOrNull(@NonNull final AbstractStockEstimateEvent event) { final CandidatesQuery query = createCandidatesQuery(event); return candidateRepositoryRetrieval.retrieveLatestMatchOrNull(query); } @Nullable public Candidate retrievePreviousStockCandidateOrNull(@NonNull final AbstractStockEstimateEvent event) { final CandidatesQuery query = createPreviousStockCandidatesQuery(event); return candidateRepositoryRetrieval.retrieveLatestMatchOrNull(query); } @NonNull private CandidatesQuery createCandidatesQuery(@NonNull final AbstractStockEstimateEvent event) { final StockChangeDetailQuery stockChangeDetailQuery = StockChangeDetailQuery.builder() .freshQuantityOnHandLineRepoId(event.getFreshQtyOnHandLineId()) .build(); return CandidatesQuery.builder()
.businessCase(CandidateBusinessCase.STOCK_CHANGE) .materialDescriptorQuery(MaterialDescriptorQuery.forDescriptor(event.getMaterialDescriptor())) .stockChangeDetailQuery(stockChangeDetailQuery) .build(); } @NonNull private CandidatesQuery createPreviousStockCandidatesQuery(@NonNull final AbstractStockEstimateEvent event) { final MaterialDescriptorQuery materialDescriptorQuery = MaterialDescriptorQuery.forDescriptor(event.getMaterialDescriptor()) .toBuilder() .timeRangeEnd(DateAndSeqNo.builder() .date(event.getDate()) .operator(DateAndSeqNo.Operator.EXCLUSIVE) .build()) .build(); return CandidatesQuery.builder() .materialDescriptorQuery(materialDescriptorQuery) .type(CandidateType.STOCK) .matchExactStorageAttributesKey(true) .parentId(CandidateId.UNSPECIFIED) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\stockchange\StockEstimateEventService.java
2
请完成以下Java代码
class Area{ String id; String text; String pid; // 用于存储上级文本数据,区的上级文本 是市的数据 String aheadText; public Area(String id,String text,String pid){ this.id = id; this.text = text; this.pid = pid; } public String getId() { return id; } public String getText() {
return text; } public String getPid() { return pid; } public String getAheadText() { return aheadText; } public void setAheadText(String aheadText) { this.aheadText = aheadText; } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\ProvinceCityArea.java
1
请完成以下Java代码
public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getDetailAddress() { return detailAddress; } public void setDetailAddress(String detailAddress) { this.detailAddress = detailAddress; }
@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(", addressName=").append(addressName); sb.append(", sendStatus=").append(sendStatus); sb.append(", receiveStatus=").append(receiveStatus); sb.append(", name=").append(name); sb.append(", phone=").append(phone); sb.append(", province=").append(province); sb.append(", city=").append(city); sb.append(", region=").append(region); sb.append(", detailAddress=").append(detailAddress); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCompanyAddress.java
1
请完成以下Java代码
public Set<String> getProcessApplicationNames() { List<JmxManagedProcessApplication> processApplications = serviceContainer.getServiceValuesByType(ServiceTypes.PROCESS_APPLICATION); Set<String> processApplicationNames = new HashSet<String>(); for (JmxManagedProcessApplication jmxManagedProcessApplication : processApplications) { processApplicationNames.add(jmxManagedProcessApplication.getProcessApplicationName()); } return processApplicationNames; } @Override public ProcessApplicationInfo getProcessApplicationInfo(String processApplicationName) { JmxManagedProcessApplication processApplicationService = serviceContainer.getServiceValue(ServiceTypes.PROCESS_APPLICATION, processApplicationName); if (processApplicationService == null) { return null; } else { return processApplicationService.getProcessApplicationInfo(); } } @Override public ProcessApplicationReference getDeployedProcessApplication(String processApplicationName) {
JmxManagedProcessApplication processApplicationService = serviceContainer.getServiceValue(ServiceTypes.PROCESS_APPLICATION, processApplicationName); if (processApplicationService == null) { return null; } else { return processApplicationService.getProcessApplicationReference(); } } // Getter / Setter //////////////////////////////////////////////////////////// public PlatformServiceContainer getServiceContainer() { return serviceContainer; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\RuntimeContainerDelegateImpl.java
1
请完成以下Java代码
private static final ArrayKey mkCalloutKey(final String columnName, final ICalloutInstance callout) { return ArrayKey.of(columnName, callout.getId()); } public static final class Builder { private final ListMultimap<String, ICalloutInstance> calloutsByColumn = ArrayListMultimap.create(); private final Set<ArrayKey> seenCalloutKeys = new HashSet<>(); private Builder() { super(); } public TableCalloutsMap build() { if (calloutsByColumn.isEmpty()) { return EMPTY; } final ImmutableListMultimap<String, ICalloutInstance> map = ImmutableListMultimap.copyOf(calloutsByColumn); final ImmutableSet<ArrayKey> calloutsKeys = ImmutableSet.copyOf(seenCalloutKeys); return new TableCalloutsMap(map, calloutsKeys); } public Builder put(final String columnName, final ICalloutInstance callout) { if (callout == null) { logger.warn("Skip adding callout for ColumnName={} to map because it's null", columnName); return this; } final ArrayKey calloutKey = mkCalloutKey(columnName, callout); if (!seenCalloutKeys.add(calloutKey)) { logger.warn("Skip adding callout {} with key '{}' to map because was already added", callout, calloutKey); return this; } calloutsByColumn.put(columnName, callout); return this; } public Builder putAll(final ListMultimap<String, ICalloutInstance> calloutsByColumn) { if (calloutsByColumn == null || calloutsByColumn.isEmpty()) { return this; } for (final Entry<String, ICalloutInstance> entry : calloutsByColumn.entries()) { put(entry.getKey(), entry.getValue()); } return this; } public Builder putAll(final Map<String, List<ICalloutInstance>> calloutsByColumn)
{ if (calloutsByColumn == null || calloutsByColumn.isEmpty()) { return this; } for (final Entry<String, List<ICalloutInstance>> entry : calloutsByColumn.entrySet()) { final List<ICalloutInstance> callouts = entry.getValue(); if (callouts == null || callouts.isEmpty()) { continue; } final String columnName = entry.getKey(); for (final ICalloutInstance callout : callouts) { put(columnName, callout); } } return this; } public Builder putAll(final TableCalloutsMap callouts) { if (callouts == null || callouts.isEmpty()) { return this; } putAll(callouts.calloutsByColumn); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\TableCalloutsMap.java
1
请完成以下Java代码
public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null);
} protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsPrefrenceAreaProductRelationExample.java
1
请完成以下Java代码
public Rpc findById(TenantId tenantId, RpcId rpcId) { log.trace("Executing findById, tenantId [{}], rpcId [{}]", tenantId, rpcId); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); validateId(rpcId, id -> INCORRECT_RPC_ID + id); return rpcDao.findById(tenantId, rpcId.getId()); } @Override public ListenableFuture<Rpc> findRpcByIdAsync(TenantId tenantId, RpcId rpcId) { log.trace("Executing findRpcByIdAsync, tenantId [{}], rpcId: [{}]", tenantId, rpcId); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); validateId(rpcId, id -> INCORRECT_RPC_ID + id); return rpcDao.findByIdAsync(tenantId, rpcId.getId()); } @Override public PageData<Rpc> findAllByDeviceIdAndStatus(TenantId tenantId, DeviceId deviceId, RpcStatus rpcStatus, PageLink pageLink) { log.trace("Executing findAllByDeviceIdAndStatus, tenantId [{}], deviceId [{}], rpcStatus [{}], pageLink [{}]", tenantId, deviceId, rpcStatus, pageLink); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); validatePageLink(pageLink); return rpcDao.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink); } @Override public PageData<Rpc> findAllByDeviceId(TenantId tenantId, DeviceId deviceId, PageLink pageLink) { log.trace("Executing findAllByDeviceIdAndStatus, tenantId [{}], deviceId [{}], pageLink [{}]", tenantId, deviceId, pageLink); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); validatePageLink(pageLink); return rpcDao.findAllByDeviceId(tenantId, deviceId, pageLink); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findById(tenantId, new RpcId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findRpcByIdAsync(tenantId, new RpcId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); }
@Override public EntityType getEntityType() { return EntityType.RPC; } private final PaginatedRemover<TenantId, Rpc> tenantRpcRemover = new PaginatedRemover<>() { @Override protected PageData<Rpc> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return rpcDao.findAllRpcByTenantId(id, pageLink); } @Override protected void removeEntity(TenantId tenantId, Rpc entity) { deleteRpc(tenantId, entity.getId()); } }; }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\rpc\BaseRpcService.java
1
请完成以下Java代码
public String getAsString() { lineEnd(); return result.toString(); } public void appendCell(final String value, int width) { final String valueNorm = CoalesceUtil.coalesceNotNull(value, ""); if (line == null) { line = new StringBuilder(); } if (line.length() == 0) { line.append(identString); line.append("|");
} line.append(" ").append(Strings.padEnd(valueNorm, width, ' ')).append(" |"); } public void lineEnd() { if (line != null) { if (result.length() > 0) { result.append("\n"); } result.append(line); } line = null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\TabularStringWriter.java
1
请在Spring Boot框架中完成以下Java代码
public MessageClient getClient(RSocketServiceProxyFactory factory) { return factory.createClient(MessageClient.class); } @Bean public ApplicationRunner runRequestResponseModel(MessageClient client) { return args -> { client.sendMessage(Mono.just("Request-Response test ")) .doOnNext(message -> { System.out.println("Response is :" + message); }) .subscribe(); }; } @Bean public ApplicationRunner runStreamModel(MessageClient client) { return args -> { client.Counter() .doOnNext(t -> { System.out.println("message is :" + t); }) .subscribe(); }; } @Bean
public ApplicationRunner runFireAndForget(MessageClient client) { return args -> { client.Warning(Mono.just("Important Warning")) .subscribe(); }; } @Bean public ApplicationRunner runChannel(MessageClient client) { return args -> { client.channel(Flux.just("a", "b", "c", "d", "e")) .doOnNext(i -> { System.out.println(i); }) .subscribe(); }; } }
repos\tutorials-master\spring-reactive-modules\spring-6-rsocket\src\main\java\com\baeldung\rsocket\responder\RSocketApplication.java
2
请完成以下Java代码
private int encryptedColumnLength(final int colLength) { String str = ""; for (int i = 0; i < colLength; i++) { str += "1"; } str = SecureEngine.encrypt(str); return str.length(); } // encryptedColumnLength /** * Change the column length. * * @param adColumnId * ID of the column * @param tableName * The name of the table which owns the column * @param length * New length of the column * @return The number of rows effected, 1 upon success and -1 for failure. */ private int changeFieldLength(final int adColumnId, final String columnName, final int length, final String tableName) { int rowsEffected = -1; final String selectSql = "SELECT FieldLength FROM AD_Column WHERE AD_Column_ID=" + adColumnId; final String alterSql = "ALTER TABLE " + tableName + " MODIFY " + columnName + " NVARCHAR2(" + length + ") "; final String updateSql = "UPDATE AD_Column SET FieldLength=" + length + " WHERE AD_Column_ID=" + adColumnId; PreparedStatement selectStmt = null; ResultSet rs = null; try { selectStmt = DB.prepareStatement(selectSql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE, ITrx.TRXNAME_ThreadInherited); rs = selectStmt.executeQuery(); if (rs.next()) {
// Change the column size physically. DB.executeUpdateAndThrowExceptionOnFail(alterSql, ITrx.TRXNAME_ThreadInherited); // Change the column size in AD. DB.executeUpdateAndThrowExceptionOnFail(updateSql, ITrx.TRXNAME_ThreadInherited); } } catch (final SQLException ex) { throw new DBException(ex, selectSql); } finally { DB.close(rs, selectStmt); } // Update number of rows effected. rowsEffected++; return rowsEffected; } // changeFieldLength } // EncryptionTest
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\ColumnEncryption.java
1
请完成以下Java代码
private static byte[] doLongerCipherFinal(int opMode,Cipher cipher, byte[] source) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (opMode == Cipher.DECRYPT_MODE) { out.write(cipher.doFinal(source)); } else { int offset = 0; int totalSize = source.length; while (totalSize - offset > 0) { int size = Math.min(cipher.getOutputSize(0) - 11, totalSize - offset); out.write(cipher.doFinal(source, offset, size)); offset += size; } } out.close(); return out.toByteArray(); } /** * 构建RSA密钥对 * * @return / * @throws NoSuchAlgorithmException / */ public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded()); String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
return new RsaKeyPair(publicKeyString, privateKeyString); } /** * RSA密钥对对象 */ public static class RsaKeyPair { private final String publicKey; private final String privateKey; public RsaKeyPair(String publicKey, String privateKey) { this.publicKey = publicKey; this.privateKey = privateKey; } public String getPublicKey() { return publicKey; } public String getPrivateKey() { return privateKey; } } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\RsaUtils.java
1
请在Spring Boot框架中完成以下Java代码
public DataImportConfig getById(@NonNull final DataImportConfigId id) { return getCollection().getById(id); } public Optional<DataImportConfig> getByInternalName(@NonNull final String internalName) { return getCollection().getByInternalName(internalName); } private DataImportConfigsCollection getCollection() { return cache.getOrLoad(0, this::retrieveCollection); } private DataImportConfigsCollection retrieveCollection() { final ImmutableList<DataImportConfig> configs = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_DataImport.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(record -> toDataImportConfig(record)) .collect(ImmutableList.toImmutableList()); return new DataImportConfigsCollection(configs); } private static DataImportConfig toDataImportConfig(@NonNull final I_C_DataImport record) { return DataImportConfig.builder() .id(DataImportConfigId.ofRepoId(record.getC_DataImport_ID())) .internalName(StringUtils.trimBlankToNull(record.getInternalName())) .impFormatId(ImpFormatId.ofRepoId(record.getAD_ImpFormat_ID())) .build(); } private static class DataImportConfigsCollection { private final ImmutableMap<DataImportConfigId, DataImportConfig> configsById; private final ImmutableMap<String, DataImportConfig> configsByInternalName; public DataImportConfigsCollection(final Collection<DataImportConfig> configs) { configsById = Maps.uniqueIndex(configs, DataImportConfig::getId);
configsByInternalName = configs.stream() .filter(config -> config.getInternalName() != null) .collect(GuavaCollectors.toImmutableMapByKey(DataImportConfig::getInternalName)); } public DataImportConfig getById(@NonNull final DataImportConfigId id) { final DataImportConfig config = configsById.get(id); if (config == null) { throw new AdempiereException("@NotFound@ @C_DataConfig_ID@: " + id); } return config; } public Optional<DataImportConfig> getByInternalName(final String internalName) { Check.assumeNotEmpty(internalName, "internalName is not empty"); return Optional.ofNullable(configsByInternalName.get(internalName)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\config\DataImportConfigRepository.java
2
请完成以下Java代码
public static class JSONCloseView extends JSONResultAction { public static final JSONCloseView instance = new JSONCloseView(); private JSONCloseView() { super("closeView"); } } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Getter public static class JSONSelectViewRowsAction extends JSONResultAction { private final WindowId windowId; private final String viewId; private final Set<String> rowIds; public JSONSelectViewRowsAction(final ViewId viewId, final DocumentIdsSelection rowIds) { super("selectViewRows"); this.windowId = viewId.getWindowId(); this.viewId = viewId.getViewId(); this.rowIds = rowIds.toJsonSet(); } } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Getter public static class JSONDisplayQRCodeAction extends JSONResultAction { private final String code; protected JSONDisplayQRCodeAction(@NonNull final String code) { super("displayQRCode"); this.code = code; } }
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Getter public static class JSONNewRecordAction extends JSONResultAction { @NonNull private final WindowId windowId; @NonNull private final Map<String, String> fieldValues; @NonNull private final String targetTab; public JSONNewRecordAction( @NonNull final WindowId windowId, @Nullable final Map<String, String> fieldValues, @NonNull final ProcessExecutionResult.WebuiNewRecord.TargetTab targetTab) { super("newRecord"); this.windowId = windowId; this.fieldValues = fieldValues != null && !fieldValues.isEmpty() ? new HashMap<>(fieldValues) : ImmutableMap.of(); this.targetTab = targetTab.name(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONProcessInstanceResult.java
1
请在Spring Boot框架中完成以下Java代码
public List<Todo> retrieveTodos(@PathVariable String username) { //return todoService.findByUsername(username); return todoRepository.findByUsername(username); } @GetMapping("/users/{username}/todos/{id}") public Todo retrieveTodo(@PathVariable String username, @PathVariable int id) { //return todoService.findById(id); return todoRepository.findById(id).get(); } @DeleteMapping("/users/{username}/todos/{id}") public ResponseEntity<Void> deleteTodo(@PathVariable String username, @PathVariable int id) { //todoService.deleteById(id); todoRepository.deleteById(id); return ResponseEntity.noContent().build(); }
@PutMapping("/users/{username}/todos/{id}") public Todo updateTodo(@PathVariable String username, @PathVariable int id, @RequestBody Todo todo) { //todoService.updateTodo(todo); todoRepository.save(todo); return todo; } @PostMapping("/users/{username}/todos") public Todo createTodo(@PathVariable String username, @RequestBody Todo todo) { todo.setUsername(username); todo.setId(null); return todoRepository.save(todo); // Todo createdTodo = todoService.addTodo(username, todo.getDescription(), // todo.getTargetDate(),todo.isDone() ); // return createdTodo; } }
repos\master-spring-and-spring-boot-main\13-full-stack\02-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\todo\TodoJpaResource.java
2
请完成以下Java代码
private char getMnemonic(String text, final Component source) { if (text == null || text.length() == 0) { return 0; } final String oText = text; text = text.trim().toUpperCase(); char mnemonic = text.charAt(0); if (m_mnemonics.contains(mnemonic)) { mnemonic = 0; // Beginning new word int index = text.indexOf(' '); while (index != -1 && text.length() > index) { final char c = text.charAt(index + 1); if (Character.isLetterOrDigit(c) && !m_mnemonics.contains(c)) { mnemonic = c; break; } index = text.indexOf(' ', index + 1); } // Any character if (mnemonic == 0) { for (int i = 1; i < text.length(); i++) { final char c = text.charAt(i); if (Character.isLetterOrDigit(c) && !m_mnemonics.contains(c)) { mnemonic = c; break; } } } // Nothing found if (mnemonic == 0) { log.trace("None for: {}", oText); return 0; // if first char would be returned, the first occurrence is invalid. } } m_mnemonics.add(mnemonic); m_fields.add(source); if (log.isTraceEnabled()) { log.trace(mnemonic + " - " + source.getName()); } return mnemonic; } // getMnemonic /** * Set Window level Mnemonics * * @param set true if set otherwise unregister */
public void setMnemonics(final boolean set) { final int size = m_fields.size(); for (int i = 0; i < size; i++) { final Component c = m_fields.get(i); if (c instanceof CLabel) { final CLabel l = (CLabel)c; if (set) { l.setDisplayedMnemonic(l.getSavedMnemonic()); } else { l.setDisplayedMnemonic(0); } } else if (c instanceof VCheckBox) { final VCheckBox cb = (VCheckBox)c; if (set) { cb.setMnemonic(cb.getSavedMnemonic()); } else { cb.setMnemonic(0); } } else if (c instanceof VButton) { final VButton b = (VButton)c; if (set) { b.setMnemonic(b.getSavedMnemonic()); } else { b.setMnemonic(0); } } } } // setMnemonics }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelMnemonics.java
1
请完成以下Java代码
static class JsonBody { String name; int score; public JsonBody() {} public JsonBody(String name, int score) { this.name = name; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } static class UppercasingRequestConverter implements RequestConverterFunction { @Override public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType, ParameterizedType expectedParameterizedResultType) throws Exception { if (expectedResultType.isAssignableFrom(String.class)) {
return request.content(StandardCharsets.UTF_8).toUpperCase(); } return RequestConverterFunction.fallthrough(); } } static class UppercasingResponseConverter implements ResponseConverterFunction { @Override public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers, @Nullable Object result, HttpHeaders trailers) { if (result instanceof String) { return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, ((String) result).toUpperCase(), trailers); } return ResponseConverterFunction.fallthrough(); } } static class ConflictExceptionHandler implements ExceptionHandlerFunction { @Override public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) { if (cause instanceof IllegalStateException) { return HttpResponse.of(HttpStatus.CONFLICT); } return ExceptionHandlerFunction.fallthrough(); } } } }
repos\tutorials-master\server-modules\armeria\src\main\java\com\baeldung\armeria\AnnotatedServer.java
1
请完成以下Java代码
public Map<Characteristic, DocumentFieldDescriptor.Builder> getSpecialField_DocSatusAndDocAction() { return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocStatusAndDocAction(); } private WidgetTypeStandardNumberPrecision getStandardNumberPrecision() { WidgetTypeStandardNumberPrecision standardNumberPrecision = this._standardNumberPrecision; if (standardNumberPrecision == null) { standardNumberPrecision = this._standardNumberPrecision = WidgetTypeStandardNumberPrecision.builder() .quantityPrecision(getPrecisionFromSysConfigs(SYSCONFIG_QUANTITY_DEFAULT_PRECISION)) .build() .fallbackTo(WidgetTypeStandardNumberPrecision.DEFAULT); } return standardNumberPrecision; } @SuppressWarnings("SameParameterValue") private OptionalInt getPrecisionFromSysConfigs(@NonNull final String sysconfigName)
{ final int precision = sysConfigBL.getIntValue(sysconfigName, -1); return precision > 0 ? OptionalInt.of(precision) : OptionalInt.empty(); } private boolean isSkipField(@NonNull final String fieldName) { switch (fieldName) { case FIELDNAME_AD_Org_ID: return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_ORG_ID_IS_DISPLAYED, true); case FIELDNAME_AD_Client_ID: return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_CLIENT_ID_IS_DISPLAYED, true); default: return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\GridTabVOBasedDocumentEntityDescriptorFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyAuthenticationSucessHandler authenticationSucessHandler; @Autowired private MyAuthenticationFailureHandler authenticationFailureHandler; @Autowired private ValidateCodeFilter validateCodeFilter; @Autowired private SmsCodeFilter smsCodeFilter; @Autowired private SmsAuthenticationConfig smsAuthenticationConfig; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
.addFilterBefore(smsCodeFilter,UsernamePasswordAuthenticationFilter.class) // 添加短信验证码校验过滤器 .formLogin() // 表单登录 // http.httpBasic() // HTTP Basic .loginPage("/authentication/require") // 登录跳转 URL .loginProcessingUrl("/login") // 处理表单登录 URL .successHandler(authenticationSucessHandler) // 处理登录成功 .failureHandler(authenticationFailureHandler) // 处理登录失败 .and() .authorizeRequests() // 授权配置 .antMatchers("/authentication/require", "/login.html", "/code/image","/code/sms").permitAll() // 无需认证的请求路径 .anyRequest() // 所有请求 .authenticated() // 都需要认证 .and() .csrf().disable() .apply(smsAuthenticationConfig); // 将短信验证码认证配置加到 Spring Security 中 } }
repos\SpringAll-master\38.Spring-Security-SmsCode\src\main\java\cc\mrbird\security\browser\BrowserSecurityConfig.java
2
请完成以下Java代码
public void removeEventListener(ActivitiEventListener listenerToRemove) { eventListeners.remove(listenerToRemove); for (List<ActivitiEventListener> listeners : typedListeners.values()) { listeners.remove(listenerToRemove); } } public void dispatchEvent(ActivitiEvent event) { if (event == null) { throw new ActivitiIllegalArgumentException("Event cannot be null."); } if (event.getType() == null) { throw new ActivitiIllegalArgumentException("Event type cannot be null."); } // Call global listeners if (!eventListeners.isEmpty()) { for (ActivitiEventListener listener : eventListeners) { dispatchEvent(event, listener); } } // Call typed listeners, if any List<ActivitiEventListener> typed = typedListeners.get(event.getType()); if (typed != null && !typed.isEmpty()) { for (ActivitiEventListener listener : typed) { dispatchEvent(event, listener); } } } protected void dispatchEvent(ActivitiEvent event, ActivitiEventListener listener) { try { listener.onEvent(event); } catch (Throwable t) { if (listener.isFailOnException()) { throw new ActivitiException("Exception while executing event-listener", t); } else { // Ignore the exception and continue notifying remaining listeners. The listener
// explicitly states that the exception should not bubble up LOG.warn("Exception while executing event-listener, which was ignored", t); } } } protected synchronized void addTypedEventListener(ActivitiEventListener listener, ActivitiEventType type) { List<ActivitiEventListener> listeners = typedListeners.get(type); if (listeners == null) { // Add an empty list of listeners for this type listeners = new CopyOnWriteArrayList<ActivitiEventListener>(); typedListeners.put(type, listeners); } if (!listeners.contains(listener)) { listeners.add(listener); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventSupport.java
1
请完成以下Java代码
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView) { // 36.0/137.015625, Clip=java.awt.Rectangle[x=0,y=0,width=639,height=804], Translate=1.0/56.0, Scale=1.0/1.0, Shear=0.0/0.0 // log.trace( "HTMLElement.paint", p_pageLocation.x + "/" + p_pageLocation.y // + ", Clip=" + g2D.getClip() // + ", Translate=" + g2D.getTransform().getTranslateX() + "/" + g2D.getTransform().getTranslateY() // + ", Scale=" + g2D.getTransform().getScaleX() + "/" + g2D.getTransform().getScaleY() // + ", Shear=" + g2D.getTransform().getShearX() + "/" + g2D.getTransform().getShearY()); // Point2D.Double location = getAbsoluteLocation(pageStart); // log.trace( "HTMLElement.paint - PageStart=" + pageStart + ", Location=" + location); // Rectangle allocation = m_renderer.getAllocation(); g2D.translate(location.x, location.y); m_renderer.paint(g2D, allocation); g2D.translate(-location.x, -location.y); } // paint /** * String Representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer("HTMLElement["); sb.append("Bounds=").append(getBounds())
.append(",Height=").append(p_height).append("(").append(p_maxHeight) .append("),Width=").append(p_width).append("(").append(p_maxHeight) .append("),PageLocation=").append(p_pageLocation).append(" - "); sb.append("]"); return sb.toString(); } // toString /************************************************************************** * Is content HTML * @param content content * @return true if HTML */ public static boolean isHTML (Object content) { if (content == null) return false; String s = content.toString(); if (s.length() < 20) // assumption return false; s = s.trim().toUpperCase(); if (s.startsWith("<HTML>")) return true; return false; } // isHTML } // HTMLElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\HTMLElement.java
1
请完成以下Java代码
public void setNetDays (final int NetDays) { set_Value (COLUMNNAME_NetDays, NetDays); } @Override public int getNetDays() { return get_ValueAsInt(COLUMNNAME_NetDays); } @Override public void setsinglevat (final @Nullable BigDecimal singlevat) { set_Value (COLUMNNAME_singlevat, singlevat); } @Override public BigDecimal getsinglevat() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_singlevat);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void settaxfree (final boolean taxfree) { set_Value (COLUMNNAME_taxfree, taxfree); } @Override public boolean istaxfree() { return get_ValueAsBoolean(COLUMNNAME_taxfree); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_120_v.java
1
请完成以下Java代码
public int getPosition() { return get_ValueAsInt(COLUMNNAME_Position); } /** * Type AD_Reference_ID=53241 * Reference name: EXP_Line_Type */ public static final int TYPE_AD_Reference_ID=53241; /** XML Element = E */ public static final String TYPE_XMLElement = "E"; /** XML Attribute = A */ public static final String TYPE_XMLAttribute = "A"; /** Embedded EXP Format = M */ public static final String TYPE_EmbeddedEXPFormat = "M"; /** Referenced EXP Format = R */ public static final String TYPE_ReferencedEXPFormat = "R"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override
public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_FormatLine.java
1
请完成以下Java代码
public String getF_ISAUDIT() { return F_ISAUDIT; } public void setF_ISAUDIT(String f_ISAUDIT) { F_ISAUDIT = f_ISAUDIT; } public Timestamp getF_EDITTIME() { return F_EDITTIME; } public void setF_EDITTIME(Timestamp f_EDITTIME) { F_EDITTIME = f_EDITTIME; }
public Integer getF_PLATFORM_ID() { return F_PLATFORM_ID; } public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) { F_PLATFORM_ID = f_PLATFORM_ID; } public String getF_ISPRINTBILL() { return F_ISPRINTBILL; } public void setF_ISPRINTBILL(String f_ISPRINTBILL) { F_ISPRINTBILL = f_ISPRINTBILL; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java
1
请完成以下Java代码
public Set<HuId> retrieveMatchingSourceHUIds(@NonNull final MatchingSourceHusQuery query) { return sourceHuDAO.retrieveActiveSourceHUIds(query); } public boolean isSourceHu(final HuId huId) { return sourceHuDAO.isSourceHu(huId); } public void addSourceHUMarkerIfCarringComponents(@NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId) { addSourceHUMarkerIfCarringComponents(ImmutableSet.of(huId), productId, warehouseId); } /** * Creates an M_Source_HU record for the given HU, if it carries component products and the target warehouse has * the org.compiere.model.I_M_Warehouse#isReceiveAsSourceHU() flag. */ public void addSourceHUMarkerIfCarringComponents(@NonNull final Set<HuId> huIds, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId) { if (huIds.isEmpty()) {return;} final I_M_Warehouse warehouse = warehousesRepo.getById(warehouseId); if (!warehouse.isReceiveAsSourceHU()) { return; } final boolean referencedInComponentOrVariant = productBOMDAO.isComponent(productId); if (!referencedInComponentOrVariant) { return; } huIds.forEach(this::addSourceHuMarker); } /** * Specifies which source HUs (products and warehouse) to retrieve in particular */ @lombok.Value @lombok.Builder @Immutable public static class MatchingSourceHusQuery {
/** * Query for HUs that have any of the given product IDs. Empty means that no HUs will be found. */ @Singular ImmutableSet<ProductId> productIds; @Singular ImmutableSet<WarehouseId> warehouseIds; public static MatchingSourceHusQuery fromHuId(final HuId huId) { final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final I_M_HU hu = handlingUnitsBL.getById(huId); final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); final IHUStorage storage = storageFactory.getStorage(hu); final ImmutableSet<ProductId> productIds = storage.getProductStorages().stream() .filter(productStorage -> !productStorage.isEmpty()) .map(IProductStorage::getProductId) .collect(ImmutableSet.toImmutableSet()); final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseId(hu); return new MatchingSourceHusQuery(productIds, ImmutableSet.of(warehouseId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\SourceHUsService.java
1
请完成以下Java代码
public class WatchPodsUsingBookmarks { private static Logger log = LoggerFactory.getLogger(WatchPodsUsingBookmarks.class); public static void main(String[] args) throws Exception { ApiClient client = Config.defaultClient(); // Optional, put helpful during tests: disable client timeout and enable // HTTP wire-level logs HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message)); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient newClient = client.getHttpClient() .newBuilder() .addInterceptor(interceptor) .readTimeout(0, TimeUnit.SECONDS) .build(); client.setHttpClient(newClient); CoreV1Api api = new CoreV1Api(client); String resourceVersion = null; while (true) { // Get a fresh list only we need to resync if ( resourceVersion == null ) { log.info("[I48] Creating initial POD list..."); V1PodList podList = api.listPodForAllNamespaces(true, null, null, null, null, "false", resourceVersion, null, null, null); resourceVersion = podList.getMetadata().getResourceVersion(); } while (true) { log.info("[I54] Creating watch: resourceVersion={}", resourceVersion); try (Watch<V1Pod> watch = Watch.createWatch( client, api.listPodForAllNamespacesCall(true, null, null, null, null, "false", resourceVersion, null, 10, true, null),
new TypeToken<Response<V1Pod>>(){}.getType())) { log.info("[I60] Receiving events:"); for (Response<V1Pod> event : watch) { V1Pod pod = event.object; V1ObjectMeta meta = pod.getMetadata(); switch (event.type) { case "BOOKMARK": resourceVersion = meta.getResourceVersion(); log.info("[I67] event.type: {}, resourceVersion={}", event.type,resourceVersion); break; case "ADDED": case "MODIFIED": case "DELETED": log.info("event.type: {}, namespace={}, name={}", event.type, meta.getNamespace(), meta.getName()); break; default: log.warn("[W76] Unknown event type: {}", event.type); } } } catch (ApiException ex) { log.error("[E80] ApiError", ex); resourceVersion = null; } } } } }
repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\WatchPodsUsingBookmarks.java
1
请完成以下Java代码
private IAllocationResult allocateRemainingOnNewHUs( @NonNull final I_M_HU_Item item, @NonNull final IAllocationRequest request) { // // Create initial result final IMutableAllocationResult result = AllocationUtils.createMutableAllocationResult(request); // // Start creating and loading new HUs as much as we can while (!result.isCompleted()) { final I_M_HU includedHU = createNewIncludedHU(item, request); if (includedHU == null) { // we cannot create more HUs break; } final IAllocationRequest includedRequest = AllocationUtils.createQtyRequestForRemaining(request, result); final IAllocationResult includedResult = allocateOnIncludedHU(includedHU, includedRequest); if (includedResult.isZeroAllocated()) { destroyIncludedHU(includedHU); // if we cannot allocate on this HU, we won't be able to allocate on any of these break; } AllocationUtils.mergeAllocationResult(result, includedResult); } return result; } /** * Creates a new included HU * * @return newly created HU or null if we cannot create HUs anymore
*/ @Nullable private final I_M_HU createNewIncludedHU( @NonNull final I_M_HU_Item item, @NonNull final IAllocationRequest request) { final IHUItemStorage storage = getHUItemStorage(item, request); if (!storage.requestNewHU()) { return null; } final I_M_HU_PI includedHUDef; if (X_M_HU_Item.ITEMTYPE_HUAggregate.equals(item.getItemType())) { // if we are to create an HU below an HUAggregate item, then we always create a VHU. includedHUDef = services.getVirtualPI(request.getHuContext().getCtx()); } else { includedHUDef = services.getIncluded_HU_PI(item); } // we cannot create an instance which has no included handling unit definition Check.errorIf(includedHUDef == null, "Unable to get a M_HU_PI for the given request and item; request={}; item={}", request, item); return AllocationUtils.createHUBuilder(request) .setM_HU_Item_Parent(item) .create(includedHUDef); } private final void destroyIncludedHU(final I_M_HU hu) { services.deleteHU(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\FIFOAllocationStrategy.java
1
请在Spring Boot框架中完成以下Java代码
public String getStartActivityId() { return startActivityId; } public void setStartActivityId(String startActivityId) { this.startActivityId = startActivityId; } @ApiModelProperty(example = "endEvent") public String getEndActivityId() { return endActivityId; } public void setEndActivityId(String endActivityId) { this.endActivityId = endActivityId; } @ApiModelProperty(example = "null") public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } @ApiModelProperty(example = "3") public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } 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 = "3") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn") public String getCallbackType() { return callbackType; }
public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-bpmn-2.0-process") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } @ApiModelProperty(value = "The stage plan item instance id this process instance belongs to or null, if it is not part of a case at all or is not a child element of a stage") public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } @ApiModelProperty(example = "someTenantId") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceResponse.java
2
请完成以下Java代码
public ExtensionElements getExtensionElements() { return extensionElementsChild.getChild(this); } public void setExtensionElements(ExtensionElements extensionElements) { extensionElementsChild.setChild(this, extensionElements); } public Collection<Relationship> getRelationships() { return relationshipCollection.get(this); } public Collection<Artifact> getArtifacts() { return artifactCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Definitions.class, CMMN_ELEMENT_DEFINITIONS) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<Definitions>() { public Definitions newInstance(ModelTypeInstanceContext instanceContext) { return new DefinitionsImpl(instanceContext); } }); idAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ID) .idAttribute() .build(); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); targetNamespaceAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_NAMESPACE) .required() .build(); expressionLanguageAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPRESSION_LANGUAGE) .defaultValue(XPATH_NS) .build(); exporterAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER) .build(); exporterVersionAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER_VERSION) .build(); authorAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_AUTHOR) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); importCollection = sequenceBuilder.elementCollection(Import.class)
.build(); caseFileItemDefinitionCollection = sequenceBuilder.elementCollection(CaseFileItemDefinition.class) .build(); caseCollection = sequenceBuilder.elementCollection(Case.class) .build(); processCollection = sequenceBuilder.elementCollection(Process.class) .build(); decisionCollection = sequenceBuilder.elementCollection(Decision.class) .build(); extensionElementsChild = sequenceBuilder.element(ExtensionElements.class) .minOccurs(0) .maxOccurs(1) .build(); relationshipCollection = sequenceBuilder.elementCollection(Relationship.class) .build(); artifactCollection = sequenceBuilder.elementCollection(Artifact.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DefinitionsImpl.java
1
请完成以下Java代码
public CmmnCaseDefinition getCaseDefinition() { return caseDefinition; } public void setCaseDefinition(CmmnCaseDefinition caseDefinition) { this.caseDefinition = caseDefinition; } public CmmnActivity getParent() { return parent; } public void setParent(CmmnActivity parent) { this.parent = parent; } public Deployment getDeployment() {
return deployment; } public void setDeployment(Deployment deployment) { this.deployment = deployment; } public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\CmmnHandlerContext.java
1