instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void deleteChildRecords(@NonNull final I_DataEntry_Section dataEntrySectionRecord) { Services.get(IQueryBL.class) .createQueryBuilder(I_DataEntry_Line.class) .addEqualsFilter(I_DataEntry_Line.COLUMN_DataEntry_Section_ID, dataEntrySectionRecord.getDataEntry_Section_ID()) .create() .delete(); } @CalloutMethod(columnNames = I_DataEntry_Section.COLUMNNAME_DataEntry_SubTab_ID) public void setSeqNo(@NonNull final I_DataEntry_Section dataEntrySectionRecord) { if (dataEntrySectionRecord.getDataEntry_SubTab_ID() <= 0) { return;
} dataEntrySectionRecord.setSeqNo(maxSeqNo(dataEntrySectionRecord) + 10); } private int maxSeqNo(@NonNull final I_DataEntry_Section dataEntrySectionRecord) { return Services .get(IQueryBL.class) .createQueryBuilder(I_DataEntry_Section.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DataEntry_Section.COLUMN_DataEntry_SubTab_ID, dataEntrySectionRecord.getDataEntry_SubTab_ID()) .create() .maxInt(I_DataEntry_Tab.COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\layout\interceptor\DataEntry_Section.java
1
请在Spring Boot框架中完成以下Java代码
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String issuer = this.issuerResolver.resolve(request); AuthorizationServerContext authorizationServerContext = new DefaultAuthorizationServerContext(issuer, this.authorizationServerSettings); AuthorizationServerContextHolder.setContext(authorizationServerContext); filterChain.doFilter(request, response); } finally { AuthorizationServerContextHolder.resetContext(); } } private static final class IssuerResolver { private final String issuer; private final Set<String> endpointUris; private IssuerResolver(AuthorizationServerSettings authorizationServerSettings) { if (authorizationServerSettings.getIssuer() != null) { this.issuer = authorizationServerSettings.getIssuer(); this.endpointUris = Collections.emptySet(); } else { this.issuer = null; this.endpointUris = new HashSet<>(); this.endpointUris.add("/.well-known/oauth-authorization-server"); this.endpointUris.add("/.well-known/openid-configuration"); for (Map.Entry<String, Object> setting : authorizationServerSettings.getSettings().entrySet()) { if (setting.getKey().endsWith("-endpoint")) { this.endpointUris.add((String) setting.getValue()); } } } } private String resolve(HttpServletRequest request) { if (this.issuer != null) { return this.issuer; } // Resolve Issuer Identifier dynamically from request String path = request.getRequestURI(); if (!StringUtils.hasText(path)) { path = ""; } else { for (String endpointUri : this.endpointUris) { if (path.contains(endpointUri)) { path = path.replace(endpointUri, ""); break; } } } // @formatter:off return UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request))
.replacePath(path) .replaceQuery(null) .fragment(null) .build() .toUriString(); // @formatter:on } } private static final class DefaultAuthorizationServerContext implements AuthorizationServerContext { private final String issuer; private final AuthorizationServerSettings authorizationServerSettings; private DefaultAuthorizationServerContext(String issuer, AuthorizationServerSettings authorizationServerSettings) { this.issuer = issuer; this.authorizationServerSettings = authorizationServerSettings; } @Override public String getIssuer() { return this.issuer; } @Override public AuthorizationServerSettings getAuthorizationServerSettings() { return this.authorizationServerSettings; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\AuthorizationServerContextFilter.java
2
请在Spring Boot框架中完成以下Java代码
public CalculatedField findById(CalculatedFieldId calculatedFieldId, SecurityUser user) { return calculatedFieldService.findById(user.getTenantId(), calculatedFieldId); } @Override public PageData<CalculatedField> findByTenantIdAndEntityId(TenantId tenantId, EntityId entityId, CalculatedFieldType type, PageLink pageLink) { checkEntity(tenantId, entityId, type); return calculatedFieldService.findCalculatedFieldsByEntityId(tenantId, entityId, type, pageLink); } @Override @Transactional public void delete(CalculatedField calculatedField, SecurityUser user) { ActionType actionType = ActionType.DELETED; TenantId tenantId = calculatedField.getTenantId(); CalculatedFieldId calculatedFieldId = calculatedField.getId(); try { calculatedFieldService.deleteCalculatedField(tenantId, calculatedFieldId); logEntityActionService.logEntityAction(tenantId, calculatedFieldId, calculatedField, actionType, user, calculatedFieldId.toString()); } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.CALCULATED_FIELD), actionType, user, e, calculatedFieldId.toString()); throw e; } } private void checkForEntityChange(CalculatedField oldCalculatedField, CalculatedField newCalculatedField) { if (!oldCalculatedField.getEntityId().equals(newCalculatedField.getEntityId())) { throw new IllegalArgumentException("Changing the calculated field target entity after initialization is prohibited.");
} } private void checkEntity(TenantId tenantId, EntityId entityId, CalculatedFieldType type) { EntityType entityType = entityId.getEntityType(); Set<CalculatedFieldType> supportedTypes = CalculatedField.SUPPORTED_ENTITIES.get(entityType); if (supportedTypes == null || supportedTypes.isEmpty()) { throw new IllegalArgumentException("Entity type '" + entityType + "' does not support calculated fields"); } else if (type != null && !supportedTypes.contains(type)) { throw new IllegalArgumentException("Entity type '" + entityType + "' does not support '" + type + "' calculated fields"); } else if (entityService.fetchEntity(tenantId, entityId).isEmpty()) { throw new IllegalArgumentException(entityType.getNormalName() + " with id [" + entityId.getId() + "] does not exist."); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\cf\DefaultTbCalculatedFieldService.java
2
请完成以下Java代码
public void setProjectName (final java.lang.String ProjectName) { set_ValueNoCheck (COLUMNNAME_ProjectName, ProjectName); } @Override public java.lang.String getProjectName() { return get_ValueAsString(COLUMNNAME_ProjectName); } @Override public void setProjectPhaseName (final @Nullable java.lang.String ProjectPhaseName) { set_ValueNoCheck (COLUMNNAME_ProjectPhaseName, ProjectPhaseName); } @Override public java.lang.String getProjectPhaseName() { return get_ValueAsString(COLUMNNAME_ProjectPhaseName); } @Override public void setProjectTypeName (final @Nullable java.lang.String ProjectTypeName) { set_ValueNoCheck (COLUMNNAME_ProjectTypeName, ProjectTypeName); } @Override public java.lang.String getProjectTypeName() { return get_ValueAsString(COLUMNNAME_ProjectTypeName); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_ValueNoCheck (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null); else set_ValueNoCheck (COLUMNNAME_SalesRep_ID, SalesRep_ID); }
@Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setSalesRep_Name (final @Nullable java.lang.String SalesRep_Name) { set_ValueNoCheck (COLUMNNAME_SalesRep_Name, SalesRep_Name); } @Override public java.lang.String getSalesRep_Name() { return get_ValueAsString(COLUMNNAME_SalesRep_Name); } @Override public void setTaxID (final java.lang.String TaxID) { set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (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_C_Project_Header_v.java
1
请完成以下Java代码
protected void initializeDefaultPrivileges(String restAdminId) { initializePrivilege(restAdminId, SecurityConstants.PRIVILEGE_ACCESS_REST_API); initializePrivilege(restAdminId, SecurityConstants.ACCESS_ADMIN); } protected void initializePrivilege(String restAdminId, String privilegeName) { boolean restApiPrivilegeMappingExists = false; Privilege privilege = idmIdentityService.createPrivilegeQuery().privilegeName(privilegeName).singleResult(); if (privilege != null) { restApiPrivilegeMappingExists = restApiPrivilegeMappingExists(restAdminId, privilege); } else { try { privilege = idmIdentityService.createPrivilege(privilegeName); } catch (Exception e) { // Could be created by another server, retrying fetch privilege = idmIdentityService.createPrivilegeQuery().privilegeName(privilegeName).singleResult(); } } if (privilege == null) { throw new FlowableException("Could not find or create " + privilegeName + " privilege"); } if (!restApiPrivilegeMappingExists) { idmIdentityService.addUserPrivilegeMapping(privilege.getId(), restAdminId); } } protected boolean restApiPrivilegeMappingExists(String restAdminId, Privilege privilege) { return idmIdentityService.createPrivilegeQuery() .userId(restAdminId) .privilegeId(privilege.getId()) .singleResult() != null; } protected void initDemoProcessDefinitions() {
String deploymentName = "Demo processes"; List<Deployment> deploymentList = repositoryService.createDeploymentQuery().deploymentName(deploymentName).list(); if (deploymentList == null || deploymentList.isEmpty()) { repositoryService.createDeployment().name(deploymentName) .addClasspathResource("createTimersProcess.bpmn20.xml") .addClasspathResource("oneTaskProcess.bpmn20.xml") .addClasspathResource("VacationRequest.bpmn20.xml") .addClasspathResource("VacationRequest.png") .addClasspathResource("FixSystemFailureProcess.bpmn20.xml") .addClasspathResource("FixSystemFailureProcess.png") .addClasspathResource("Helpdesk.bpmn20.xml") .addClasspathResource("Helpdesk.png") .addClasspathResource("reviewSalesLead.bpmn20.xml") .deploy(); } } @Override public void setEnvironment(Environment environment) { this.environment = environment; } }
repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\conf\BootstrapConfiguration.java
1
请完成以下Java代码
private static void execute() { ResponseEntity<Book> response = restTemplate.execute( "https://api.bookstore.com", HttpMethod.POST, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest request) throws IOException { // Create or decorate the request object as needed } }, new ResponseExtractor<ResponseEntity<Book>>() { @Override public ResponseEntity<Book> extractData(ClientHttpResponse response) throws IOException { // extract required data from response return null; } } ); // Could also use some factory methods in RestTemplate for // the request callback and/or response extractor Book book = new Book( "Reactive Spring", "Josh Long", 2020); response = restTemplate.execute( "https://api.bookstore.com",
HttpMethod.POST, restTemplate.httpEntityCallback(book), restTemplate.responseEntityExtractor(Book.class) ); } private static class Book { String title; String author; int yearPublished; public Book(String title, String author, int yearPublished) { this.title = title; this.author = author; this.yearPublished = yearPublished; } } }
repos\tutorials-master\spring-web-modules\spring-resttemplate-2\src\main\java\com\baeldung\resttemplate\json\methods\RestTemplateMethodsApplication.java
1
请在Spring Boot框架中完成以下Java代码
public void onOpen(@PathParam("key") String key, Session session) { long startTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis(); SESSION_POOLS.put(key, session); log.info("[WebSocket] 连接成功,当前连接人数为:={}", SESSION_POOLS.size()); try { session.getBasicRemote().sendText("Web socket 消息"); } catch (Exception e) { log.error(e.getMessage(), e); } } /** * WebSocket请求关闭 */ @OnClose public void onClose(@PathParam("key") String key) { SESSION_POOLS.remove(key); log.info("WebSocket请求关闭"); }
@OnError public void onError(Throwable thr) { log.info("WebSocket 异常"); } /** * 收到客户端信息 */ @OnMessage public void onMessage(@PathParam("key") String key, String message, Session session) throws IOException { message = "客户端:" + message + ",已收到"; log.info(message); } }
repos\spring-boot-student-master\spring-boot-student-skywalking\src\main\java\com\xiaolyuh\controller\RunningLogEndpoint.java
2
请完成以下Java代码
public void setBestellPzn(long value) { this.bestellPzn = value; } /** * Gets the value of the bestellMenge property. * */ public int getBestellMenge() { return bestellMenge; } /** * Sets the value of the bestellMenge property. * */ public void setBestellMenge(int value) { this.bestellMenge = value; } /** * Gets the value of the bestellLiefervorgabe property. * * @return * possible object is * {@link Liefervorgabe } * */ public Liefervorgabe getBestellLiefervorgabe() { return bestellLiefervorgabe; } /** * Sets the value of the bestellLiefervorgabe property. * * @param value * allowed object is * {@link Liefervorgabe } * */ public void setBestellLiefervorgabe(Liefervorgabe value) { this.bestellLiefervorgabe = value; } /** * Gets the value of the substitution property. * * @return * possible object is * {@link BestellungSubstitution } * */
public BestellungSubstitution getSubstitution() { return substitution; } /** * Sets the value of the substitution property. * * @param value * allowed object is * {@link BestellungSubstitution } * */ public void setSubstitution(BestellungSubstitution value) { this.substitution = value; } /** * Gets the value of the anteile property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the anteile property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAnteile().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BestellungAnteil } * * */ public List<BestellungAnteil> getAnteile() { if (anteile == null) { anteile = new ArrayList<BestellungAnteil>(); } return this.anteile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungAntwortPosition.java
1
请在Spring Boot框架中完成以下Java代码
private void initialize(MongoConfig mongo) { SampleUuidEntityRepository samplesUuidRepository = new SampleUuidEntityRepository(mongo.getClient(), mongo.getDbName()); SampleUuidEntityService sampleUuidService = new SampleUuidEntityService(samplesUuidRepository); sampleUuidController = new SampleUuidEntityController(sampleUuidService); SampleOidEntityRepository samplesOidRepository = new SampleOidEntityRepository(mongo.getClient(), mongo.getDbName()); SampleOidEntityService sampleOidService = new SampleOidEntityService(samplesOidRepository); sampleOidController = new SampleOidEntityController(sampleOidService); } public int getPort() { return port; } public String getBaseUrl() { return baseUrl; }
public int getExecutorThreadPoolSize() { return executorThreadPoolSize; } public MetricsConfig getMetricsConfig() { return metricsSettings; } public SampleUuidEntityController getSampleUuidEntityController() { return sampleUuidController; } public SampleOidEntityController getSampleOidEntityController() { return sampleOidController; } }
repos\tutorials-master\microservices-modules\rest-express\src\main\java\com\baeldung\restexpress\Configuration.java
2
请完成以下Java代码
public ResponseEntity<StreamingResponseBody> getAttachmentById( @PathVariable("windowId") final String windowIdStr // , @PathVariable("documentId") final String documentId // , @PathVariable("id") final String entryIdStr) { userSession.assertLoggedIn(); final DocumentId entryId = DocumentId.of(entryIdStr.toUpperCase()); final IDocumentAttachmentEntry entry = getDocumentAttachments(windowIdStr, documentId) .getEntry(entryId); return toResponseBody(entry); } @NonNull private static ResponseEntity<StreamingResponseBody> toResponseBody(@NonNull final IDocumentAttachmentEntry entry) { final AttachmentEntryType type = entry.getType(); switch (type) { case Data: return DocumentAttachmentRestControllerHelper.extractResponseEntryFromData(entry); case URL: return DocumentAttachmentRestControllerHelper.extractResponseEntryFromURL(entry); case LocalFileURL: return DocumentAttachmentRestControllerHelper.extractResponseEntryFromLocalFileURL(entry); default: throw new AdempiereException("Invalid attachment entry")
.setParameter("reason", "invalid type") .setParameter("type", type) .setParameter("entry", entry); } } @DeleteMapping("/{id}") public void deleteAttachmentById( @PathVariable("windowId") final String windowIdStr // , @PathVariable("documentId") final String documentId // , @PathVariable("id") final String entryIdStr // ) { userSession.assertLoggedIn(); if (!isAllowDeletingAttachments()) { throw new AdempiereException("Delete not allowed"); } final DocumentId entryId = DocumentId.of(entryIdStr); getDocumentAttachments(windowIdStr, documentId) .deleteEntry(entryId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachmentsRestController.java
1
请完成以下Java代码
public class ProcessEngineServicesProducer { @Produces @Named @ApplicationScoped public ProcessEngine processEngine() { ProcessEngine processEngine = BpmPlatform.getProcessEngineService().getDefaultProcessEngine(); if(processEngine != null) { return processEngine; } else { List<ProcessEngine> processEngines = BpmPlatform.getProcessEngineService().getProcessEngines(); if (processEngines != null && processEngines.size() == 1) { return processEngines.get(0); } else { return ProcessEngines.getDefaultProcessEngine(false); } } } @Produces @Named @ApplicationScoped public RuntimeService runtimeService() { return processEngine().getRuntimeService(); } @Produces @Named @ApplicationScoped public TaskService taskService() { return processEngine().getTaskService(); } @Produces @Named @ApplicationScoped public RepositoryService repositoryService() { return processEngine().getRepositoryService(); } @Produces @Named @ApplicationScoped public FormService formService() { return processEngine().getFormService(); }
@Produces @Named @ApplicationScoped public HistoryService historyService() { return processEngine().getHistoryService(); } @Produces @Named @ApplicationScoped public IdentityService identityService() { return processEngine().getIdentityService(); } @Produces @Named @ApplicationScoped public ManagementService managementService() { return processEngine().getManagementService(); } @Produces @Named @ApplicationScoped public AuthorizationService authorizationService() { return processEngine().getAuthorizationService(); } @Produces @Named @ApplicationScoped public FilterService filterService() { return processEngine().getFilterService(); } @Produces @Named @ApplicationScoped public ExternalTaskService externalTaskService() { return processEngine().getExternalTaskService(); } @Produces @Named @ApplicationScoped public CaseService caseService() { return processEngine().getCaseService(); } @Produces @Named @ApplicationScoped public DecisionService decisionService() { return processEngine().getDecisionService(); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\ProcessEngineServicesProducer.java
1
请完成以下Java代码
private static JsonDeliveryAdvisorResponse buildJsonDeliveryAdvisorResponse(@NonNull final JsonShipAdvisorResponse response, @NonNull final String requestId) { Check.assumeEquals(response.getProducts().size(), 1, "response should only contain 1 shipperProduct, pls check defined shipment rules"); final JsonShipAdvisorResponseProduct product = response.getProducts().get(0); final JsonDeliveryAdvisorResponse.JsonDeliveryAdvisorResponseBuilder responseBuilder = JsonDeliveryAdvisorResponse.builder() .requestId(requestId) .shipperProduct(JsonShipperProduct.builder() .name(product.getProdName()) .code(String.valueOf(product.getProdConceptID())) .build()); final JsonShipAdvisorResponseGoodsType productGoodsType = Check.assumeNotNull(product.getProductGoodsType(), "response should contain a GoodsType, pls check defined shipment rules"); responseBuilder.goodsType(JsonGoodsType.builder() .id(String.valueOf(productGoodsType.getGoodsTypeId())) .name(productGoodsType.getGoodsTypeName()) .build()); responseBuilder.shipperProductServices(product.getServices()
.stream() .map(NShiftShipAdvisorService::toJsonCarrierService) .collect(ImmutableList.toImmutableList()) ); return responseBuilder.build(); } private static JsonCarrierService toJsonCarrierService(@NonNull final JsonShipAdvisorResponseService jsonShipAdvisorResponseService) { return JsonCarrierService.builder() .name(jsonShipAdvisorResponseService.getName()) .id(String.valueOf(jsonShipAdvisorResponseService.getServiceId())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftShipAdvisorService.java
1
请在Spring Boot框架中完成以下Java代码
public Order create() { Order order = new Order(); order.setOrderStatus(OrderStatusEnum.WAIT_PAYMENT); order.setOrderId(id++); orders.put(order.getOrderId(), order); System.out.println("order create success:" + order.toString()); return order; } @Override public Order pay(long id) { Order order = orders.get(id); System.out.println("try to pay,order no:" + id); Message message = MessageBuilder.withPayload(OrderStatusChangeEventEnum.PAYED). setHeader("order", order).build(); if (!sendEvent(message)) { System.out.println(" pay fail, error,order no:" + id); } return orders.get(id); } @Override public Order deliver(long id) { Order order = orders.get(id); System.out.println(" try to deliver,order no:" + id); if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEventEnum.DELIVERY) .setHeader("order", order).build())) { System.out.println(" deliver fail,error,order no:" + id); } return orders.get(id); } @Override public Order receive(long id) { Order order = orders.get(id); System.out.println(" try to receiver,order no:" + id); if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEventEnum.RECEIVED) .setHeader("order", order).build())) { System.out.println(" deliver fail,error,order no:" + id); } return orders.get(id); }
@Override public Map<Long, Order> getOrders() { return orders; } /** * send transient event * @param message * @return */ private synchronized boolean sendEvent(Message<OrderStatusChangeEventEnum> message) { boolean result = false; try { orderStateMachine.start(); result = orderStateMachine.sendEvent(message); } catch (Exception e) { e.printStackTrace(); } finally { if (Objects.nonNull(message)) { Order order = (Order) message.getHeaders().get("order"); if (Objects.nonNull(order) && Objects.equals(order.getOrderStatus(), OrderStatusEnum.FINISH)) { orderStateMachine.stop(); } } } return result; } }
repos\springboot-demo-master\Statemachine\src\main\java\com\et\statemachine\service\OrderServiceImpl.java
2
请完成以下Java代码
public void springBeanPointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Pointcut that matches all Spring beans in the application's main packages. */ @Pointcut("within(com.baeldung.jhipster6.repository..*)"+ " || within(com.baeldung.jhipster6.service..*)"+ " || within(com.baeldung.jhipster6.web.rest..*)") public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); } }
/** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice * @return result * @throws Throwable throws IllegalArgumentException */ @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e; } } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\aop\logging\LoggingAspect.java
1
请完成以下Java代码
public static void listSupportedLanguagesWithSpecificLanguage() { try { List<Language> languages = translate.listSupportedLanguages(Translate.LanguageListOption.targetLanguage("es")); for (Language language : languages) { logger.info(String.format("Name: %s, Code: %s", language.getName(), language.getCode())); } } catch (Exception e) { // handle exception } } public static String translateText(String text, String targetLanguage) { String s = ""; try { Translation translation = translate.translate(text, Translate.TranslateOption.targetLanguage(targetLanguage)); s = translation.getTranslatedText(); } catch (Exception e) { e.printStackTrace(); // handle exception } return s; } public static String detectLanguage(String text) { return translate.detect(text) .getLanguage(); } public static List<String> translateBatch(List<String> texts, String targetLanguage) { List<String> translationList = null; try { List<Translation> translations = translate.translate(texts, Translate.TranslateOption.targetLanguage(targetLanguage)); translationList = translations.stream() .map(Translation::getTranslatedText) .collect(Collectors.toList()); } catch (Exception e) { // handle exception
} return translationList; } public static String translateWithGlossary(String projectId, String location, String text, String targetLanguage, String glossaryId) { String translatedText = ""; try (TranslationServiceClient client = TranslationServiceClient.create()) { LocationName parent = LocationName.of(projectId, location); GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); TranslateTextRequest request = TranslateTextRequest.newBuilder() .setParent(parent.toString()) .setTargetLanguageCode(targetLanguage) .addContents(text) .setGlossaryConfig(TranslateTextGlossaryConfig.newBuilder() .setGlossary(glossaryName.toString()).build()) // Attach glossary .build(); TranslateTextResponse response = client.translateText(request); translatedText = response.getTranslations(0).getTranslatedText(); } catch (IOException e) { // handle exception } return translatedText; } }
repos\tutorials-master\google-cloud\src\main\java\com\baeldung\google\cloud\translator\Translator.java
1
请完成以下Java代码
public String getAcctOwnrTxId() { return acctOwnrTxId; } /** * Sets the value of the acctOwnrTxId property. * * @param value * allowed object is * {@link String } * */ public void setAcctOwnrTxId(String value) { this.acctOwnrTxId = value; } /** * Gets the value of the acctSvcrTxId property. * * @return * possible object is * {@link String } * */ public String getAcctSvcrTxId() { return acctSvcrTxId; } /** * Sets the value of the acctSvcrTxId property. * * @param value * allowed object is * {@link String } * */ public void setAcctSvcrTxId(String value) { this.acctSvcrTxId = value; } /** * Gets the value of the mktInfrstrctrTxId property. * * @return * possible object is * {@link String } * */ public String getMktInfrstrctrTxId() { return mktInfrstrctrTxId; } /** * Sets the value of the mktInfrstrctrTxId property. * * @param value * allowed object is * {@link String } * */ public void setMktInfrstrctrTxId(String value) { this.mktInfrstrctrTxId = value; } /** * Gets the value of the prcgId property. * * @return * possible object is * {@link String } * */ public String getPrcgId() { return prcgId;
} /** * Sets the value of the prcgId property. * * @param value * allowed object is * {@link String } * */ public void setPrcgId(String value) { this.prcgId = value; } /** * Gets the value of the prtry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryReference1 } * * */ public List<ProprietaryReference1> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryReference1>(); } return this.prtry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionReferences3.java
1
请完成以下Java代码
protected List<Intervalable> checkForOverlaps(Intervalable interval, Direction direction) { List<Intervalable> overlaps = new ArrayList<Intervalable>(); for (Intervalable currentInterval : this.intervals) { switch (direction) { case LEFT: if (currentInterval.getStart() <= interval.getEnd()) { overlaps.add(currentInterval); } break; case RIGHT: if (currentInterval.getEnd() >= interval.getStart()) { overlaps.add(currentInterval); } break; } } return overlaps; }
/** * 是对IntervalNode.findOverlaps(Intervalable)的一个包装,防止NPE * @see IntervalNode#findOverlaps(Intervalable) * @param node * @param interval * @return */ protected static List<Intervalable> findOverlappingRanges(IntervalNode node, Intervalable interval) { if (node != null) { return node.findOverlaps(interval); } return Collections.emptyList(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\interval\IntervalNode.java
1
请完成以下Java代码
public class GetIdentityLinksForTaskCmd implements Command<List<IdentityLink>>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; public GetIdentityLinksForTaskCmd(String taskId) { this.taskId = taskId; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public List<IdentityLink> execute(CommandContext commandContext) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); TaskEntity task = cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId); List<IdentityLink> identityLinks = (List) task.getIdentityLinks(); // assignee is not part of identity links in the db. // so if there is one, we add it here. // @Tom: we discussed this long on skype and you agreed ;-) // an assignee *is* an identityLink, and so must it be reflected in the API // // Note: we cant move this code to the TaskEntity (which would be cleaner), // since the task.delete cascaded to all associated identityLinks // and of course this leads to exception while trying to delete a non-existing identityLink
if (task.getAssignee() != null) { IdentityLinkEntity identityLink = cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService().createIdentityLink(); identityLink.setUserId(task.getAssignee()); identityLink.setType(IdentityLinkType.ASSIGNEE); identityLink.setTaskId(task.getId()); identityLinks.add(identityLink); } if (task.getOwner() != null) { IdentityLinkEntity identityLink = cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService().createIdentityLink(); identityLink.setUserId(task.getOwner()); identityLink.setTaskId(task.getId()); identityLink.setType(IdentityLinkType.OWNER); identityLinks.add(identityLink); } return identityLinks; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetIdentityLinksForTaskCmd.java
1
请完成以下Java代码
public Builder modifiers(KotlinModifier... modifiers) { this.modifiers = Arrays.asList(modifiers); return this; } /** * Sets the return type. * @param returnType the return type * @return this for method chaining */ public Builder returning(String returnType) { this.returnType = returnType; return this; } /** * Sets the parameters. * @param parameters the parameters * @return this for method chaining */ public Builder parameters(Parameter... parameters) { this.parameters = Arrays.asList(parameters);
return this; } /** * Sets the body. * @param code the code for the body * @return the function declaration containing the body */ public KotlinFunctionDeclaration body(CodeBlock code) { return new KotlinFunctionDeclaration(this, code); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinFunctionDeclaration.java
1
请完成以下Java代码
public void setCCM_Bundle_Result_ID (int CCM_Bundle_Result_ID) { if (CCM_Bundle_Result_ID < 1) set_ValueNoCheck (COLUMNNAME_CCM_Bundle_Result_ID, null); else set_ValueNoCheck (COLUMNNAME_CCM_Bundle_Result_ID, Integer.valueOf(CCM_Bundle_Result_ID)); } /** Get Bundle Result. @return Bundle Result */ public int getCCM_Bundle_Result_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CCM_Bundle_Result_ID); if (ii == null) return 0; return ii.intValue(); } /** CCM_Success AD_Reference_ID=319 */ public static final int CCM_SUCCESS_AD_Reference_ID=319; /** Yes = Y */ public static final String CCM_SUCCESS_Yes = "Y"; /** No = N */ public static final String CCM_SUCCESS_No = "N"; /** Set Is Success. @param CCM_Success Is Success */ public void setCCM_Success (String CCM_Success) { set_Value (COLUMNNAME_CCM_Success, CCM_Success); } /** Get Is Success. @return Is Success */ public String getCCM_Success () { return (String)get_Value(COLUMNNAME_CCM_Success); } /** 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 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()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_CCM_Bundle_Result.java
1
请在Spring Boot框架中完成以下Java代码
public static class EDIDesadvPackItem { @NonNull EDIDesadvPackItemId ediDesadvPackItemId; @NonNull EDIDesadvPackId ediDesadvPackId; @NonNull EDIDesadvLineId ediDesadvLineId; int line; @NonNull BigDecimal movementQty; @Nullable InOutId inOutId; @Nullable InOutLineId inOutLineId; @Nullable BigDecimal qtyItemCapacity; @Nullable Integer qtyTu;
@Nullable BigDecimal qtyCUsPerTU; @Nullable BigDecimal qtyCUPerTUinInvoiceUOM; @Nullable BigDecimal qtyCUsPerLU; @Nullable BigDecimal qtyCUsPerLUinInvoiceUOM; @Nullable Timestamp bestBeforeDate; @Nullable String lotNumber; @Nullable PackagingCodeId huPackagingCodeTuId; @Nullable String gtinTuPackingMaterial; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\pack\EDIDesadvPack.java
2
请在Spring Boot框架中完成以下Java代码
private void configurePlugins(Configuration config, RestExpress server) { configureMetrics(config, server); new SwaggerPlugin() .flag(Flags.Auth.PUBLIC_ROUTE) .register(server); new CacheControlPlugin() .register(server); new HyperExpressPlugin(Linkable.class) .register(server); new CorsHeaderPlugin("*") .flag(PUBLIC_ROUTE) .allowHeaders(CONTENT_TYPE, ACCEPT, AUTHORIZATION, REFERER, LOCATION) .exposeHeaders(LOCATION) .register(server); } private void configureMetrics(Configuration config, RestExpress server) { MetricsConfig mc = config.getMetricsConfig(); if (mc.isEnabled()) { MetricRegistry registry = new MetricRegistry(); new MetricsPlugin(registry) .register(server); if (mc.isGraphiteEnabled()) { final Graphite graphite = new Graphite(new InetSocketAddress(mc.getGraphiteHost(), mc.getGraphitePort())); final GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
.prefixedWith(mc.getPrefix()) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .build(graphite); reporter.start(mc.getPublishSeconds(), TimeUnit.SECONDS); } else { LOG.warn("*** Graphite Metrics Publishing is Disabled ***"); } } else { LOG.warn("*** Metrics Generation is Disabled ***"); } } private void mapExceptions(RestExpress server) { server .mapException(ItemNotFoundException.class, NotFoundException.class) .mapException(DuplicateItemException.class, ConflictException.class) .mapException(ValidationException.class, BadRequestException.class) .mapException(InvalidObjectIdException.class, BadRequestException.class); } }
repos\tutorials-master\microservices-modules\rest-express\src\main\java\com\baeldung\restexpress\Server.java
2
请完成以下Java代码
public final class LoginOrgConstraint extends Constraint { public static final LoginOrgConstraint of(final OrgId loginOrgId, final boolean orgLoginMandatory) { return new LoginOrgConstraint(loginOrgId, orgLoginMandatory); } public static final LoginOrgConstraint DEFAULT = new LoginOrgConstraint(); private static final transient Logger logger = LogManager.getLogger(LoginOrgConstraint.class); private final OrgId loginOrgId; private final boolean orgLoginMandatory; /** Defaults constructor */ private LoginOrgConstraint() { this.loginOrgId = null; this.orgLoginMandatory = false; } private LoginOrgConstraint(@Nullable final OrgId loginOrgId, boolean orgLoginMandatory) { this.loginOrgId = loginOrgId; this.orgLoginMandatory = orgLoginMandatory; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); if (loginOrgId != null) { sb.append("@Login_Org_ID@=" + loginOrgId.getRepoId()); } if (sb.length() > 0) { sb.append(", "); } sb.append("@IsOrgLoginMandatory@=@" + (orgLoginMandatory ? "Y" : "N") + "@"); return sb.insert(0, getClass().getSimpleName() + "[") .append("]") .toString(); } @Override public boolean isInheritable() { return false; } private OrgId getLoginOrgId() { return loginOrgId; }
private boolean isOrgLoginMandatory() { return orgLoginMandatory; } public boolean isValidOrg(final OrgResource org) { if (isOrgLoginMandatory() && !org.isRegularOrg()) { logger.debug("Not valid {} because is OrgLoginMandatory is set", org); return false; } // Enforce Login_Org_ID: final OrgId loginOrgId = getLoginOrgId(); if (loginOrgId != null && !OrgId.equals(loginOrgId, org.getOrgId())) { logger.debug("Not valid {} because is not Login_Org_ID", org); return false; } return true; } public Predicate<OrgResource> asOrgResourceMatcher() { return this::isValidOrg; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\LoginOrgConstraint.java
1
请在Spring Boot框架中完成以下Java代码
public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public OrderDeliveryAddress city(String city) { this.city = city; return this; } /** * Get city * @return city **/ @Schema(example = "Nürnberg", required = true, description = "") public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderDeliveryAddress orderDeliveryAddress = (OrderDeliveryAddress) o; return Objects.equals(this.gender, orderDeliveryAddress.gender) && Objects.equals(this.title, orderDeliveryAddress.title) && Objects.equals(this.name, orderDeliveryAddress.name) && Objects.equals(this.address, orderDeliveryAddress.address) && Objects.equals(this.additionalAddress, orderDeliveryAddress.additionalAddress) && Objects.equals(this.additionalAddress2, orderDeliveryAddress.additionalAddress2) && Objects.equals(this.postalCode, orderDeliveryAddress.postalCode) && Objects.equals(this.city, orderDeliveryAddress.city); }
@Override public int hashCode() { return Objects.hash(gender, title, name, address, additionalAddress, additionalAddress2, postalCode, city); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderDeliveryAddress {\n"); sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" additionalAddress: ").append(toIndentedString(additionalAddress)).append("\n"); sb.append(" additionalAddress2: ").append(toIndentedString(additionalAddress2)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderDeliveryAddress.java
2
请完成以下Java代码
private static JSONDocumentLayoutElementLine ofDocumentLayoutElementLineDescriptor( @NonNull final DocumentLayoutElementLineDescriptor elementLine, @NonNull final JSONDocumentLayoutOptions options) { return new JSONDocumentLayoutElementLine(elementLine, options); } @JsonProperty("elements") @JsonInclude(JsonInclude.Include.NON_EMPTY) @Getter private final List<JSONDocumentLayoutElement> elements; private JSONDocumentLayoutElementLine( @NonNull final DocumentLayoutElementLineDescriptor elementLine, @NonNull final JSONDocumentLayoutOptions options) { final List<JSONDocumentLayoutElement> elements = JSONDocumentLayoutElement.ofList(elementLine.getElements(), options); this.elements = ImmutableList.copyOf(elements); } @JsonCreator private JSONDocumentLayoutElementLine( @JsonProperty("elements") @Nullable final List<JSONDocumentLayoutElement> elements) {
this.elements = elements == null ? ImmutableList.of() : ImmutableList.copyOf(elements); } @JsonIgnore public boolean isEmpty() { return getElements().isEmpty(); } Stream<JSONDocumentLayoutElement> streamInlineTabElements() { return getElements() .stream() .filter(element -> element.getInlineTabId() != null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutElementLine.java
1
请在Spring Boot框架中完成以下Java代码
static class SimpleConnectionFactoryConfiguration { @Bean @ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", havingValue = false) ActiveMQConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { return createJmsConnectionFactory(properties, factoryCustomizers, connectionDetails); } private static ActiveMQConnectionFactory createJmsConnectionFactory(ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionDetails.getUser(), connectionDetails.getPassword(), connectionDetails.getBrokerUrl()); new ActiveMQConnectionFactoryConfigurer(properties, factoryCustomizers.orderedStream().toList()) .configure(connectionFactory); return connectionFactory; } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CachingConnectionFactory.class) @ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", matchIfMissing = true) static class CachingConnectionFactoryConfiguration { @Bean CachingConnectionFactory jmsConnectionFactory(JmsProperties jmsProperties, ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { JmsProperties.Cache cacheProperties = jmsProperties.getCache(); CachingConnectionFactory connectionFactory = new CachingConnectionFactory( createJmsConnectionFactory(properties, factoryCustomizers, connectionDetails)); connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheProducers(cacheProperties.isProducers()); connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize()); return connectionFactory; } } } @Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ JmsPoolConnectionFactory.class, PooledObject.class }) static class PooledConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") @ConditionalOnBooleanProperty("spring.activemq.pool.enabled") JmsPoolConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionDetails.getUser(), connectionDetails.getPassword(), connectionDetails.getBrokerUrl()); new ActiveMQConnectionFactoryConfigurer(properties, factoryCustomizers.orderedStream().toList()) .configure(connectionFactory); return new JmsPoolConnectionFactoryFactory(properties.getPool()) .createPooledConnectionFactory(connectionFactory); } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQConnectionFactoryConfiguration.java
2
请完成以下Java代码
public String retrieveVersion(DocumentEntityDescriptor entityDescriptor, int documentIdAsInt) { return VERSION_DEFAULT; } @Override public int retrieveLastLineNo(DocumentQuery query) { return 0; } private static final class DataEntryDocumentValuesSupplier implements DocumentValuesSupplier { private final DataEntryRecord dataEntryRecord; private final DataEntryWebuiTools dataEntryWebuiTools; private DataEntryDocumentValuesSupplier( @NonNull final DataEntryRecord dataEntryRecord, @NonNull DataEntryWebuiTools dataEntryWebuiTools) { this.dataEntryWebuiTools = dataEntryWebuiTools; this.dataEntryRecord = dataEntryRecord; }
@Override public DocumentId getDocumentId() { final DocumentId documentId = DataEntrySubTabBindingRepository.createDocumentId( dataEntryRecord.getDataEntrySubTabId(), dataEntryRecord.getMainRecord()); return documentId; } @Override public String getVersion() { return VERSION_DEFAULT; } @Override public Object getValue(@NonNull final DocumentFieldDescriptor fieldDescriptor) { return dataEntryWebuiTools.extractDataEntryValueForField(dataEntryRecord, fieldDescriptor); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntrySubTabBindingRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id private Long id; @Column(columnDefinition = "varchar(255) default 'John Snow'") private String name = "John Snow"; @Column(columnDefinition = "integer default 25") private Integer age = 25; @Column(columnDefinition = "boolean default false") private Boolean locked = false; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() {
return age; } public void setAge(Integer age) { this.age = age; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\defaultvalues\User.java
2
请完成以下Java代码
public Integer getMemberLevel() { return memberLevel; } public void setMemberLevel(Integer memberLevel) { this.memberLevel = memberLevel; } @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(", type=").append(type); sb.append(", name=").append(name); sb.append(", platform=").append(platform);
sb.append(", count=").append(count); sb.append(", amount=").append(amount); sb.append(", perLimit=").append(perLimit); sb.append(", minPoint=").append(minPoint); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", useType=").append(useType); sb.append(", note=").append(note); sb.append(", publishCount=").append(publishCount); sb.append(", useCount=").append(useCount); sb.append(", receiveCount=").append(receiveCount); sb.append(", enableTime=").append(enableTime); sb.append(", code=").append(code); sb.append(", memberLevel=").append(memberLevel); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCoupon.java
1
请完成以下Java代码
public SignalEventListenerInstanceQuery elementId(String elementId) { innerQuery.planItemInstanceElementId(elementId); return this; } @Override public SignalEventListenerInstanceQuery planItemDefinitionId(String planItemDefinitionId) { innerQuery.planItemDefinitionId(planItemDefinitionId); return this; } @Override public SignalEventListenerInstanceQuery name(String name) { innerQuery.planItemInstanceName(name); return this; } @Override public SignalEventListenerInstanceQuery stageInstanceId(String stageInstanceId) { innerQuery.stageInstanceId(stageInstanceId); return this; } @Override public SignalEventListenerInstanceQuery stateAvailable() { innerQuery.planItemInstanceStateAvailable(); return this; } @Override public SignalEventListenerInstanceQuery stateSuspended() { innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED); return this; } @Override public SignalEventListenerInstanceQuery orderByName() { innerQuery.orderByName(); return this; } @Override public SignalEventListenerInstanceQuery asc() { innerQuery.asc(); return this; }
@Override public SignalEventListenerInstanceQuery desc() { innerQuery.desc(); return this; } @Override public SignalEventListenerInstanceQuery orderBy(QueryProperty property) { innerQuery.orderBy(property); return this; } @Override public SignalEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { innerQuery.orderBy(property, nullHandlingOnOrder); return this; } @Override public long count() { return innerQuery.count(); } @Override public SignalEventListenerInstance singleResult() { PlanItemInstance instance = innerQuery.singleResult(); return SignalEventListenerInstanceImpl.fromPlanItemInstance(instance); } @Override public List<SignalEventListenerInstance> list() { return convertPlanItemInstances(innerQuery.list()); } @Override public List<SignalEventListenerInstance> listPage(int firstResult, int maxResults) { return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults)); } protected List<SignalEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) { if (instances == null) { return null; } return instances.stream().map(SignalEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\SignalEventListenerInstanceQueryImpl.java
1
请完成以下Java代码
public void setNode_ID (int Node_ID) { if (Node_ID < 0) set_ValueNoCheck (COLUMNNAME_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID)); } /** Get Node_ID. @return Node_ID */ public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Parent. @param Parent_ID Parent of Entity */ public void setParent_ID (int Parent_ID) { if (Parent_ID < 1) set_Value (COLUMNNAME_Parent_ID, null); else set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID)); } /** Get Parent. @return Parent of Entity */ public int getParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TreeNode.java
1
请在Spring Boot框架中完成以下Java代码
public class IncotermType { @XmlElement(name = "DeliveryOrTransportTermsCode") protected String deliveryOrTransportTermsCode; @XmlElement(name = "IncotermCode") protected String incotermCode; @XmlElement(name = "IncotermText") protected String incotermText; @XmlElement(name = "IncotermLocation") protected String incotermLocation; /** * Gets the value of the deliveryOrTransportTermsCode property. * * @return * possible object is * {@link String } * */ public String getDeliveryOrTransportTermsCode() { return deliveryOrTransportTermsCode; } /** * Sets the value of the deliveryOrTransportTermsCode property. * * @param value * allowed object is * {@link String } * */ public void setDeliveryOrTransportTermsCode(String value) { this.deliveryOrTransportTermsCode = value; } /** * Gets the value of the incotermCode property. * * @return * possible object is * {@link String } * */ public String getIncotermCode() { return incotermCode; } /** * Sets the value of the incotermCode property. * * @param value * allowed object is * {@link String } *
*/ public void setIncotermCode(String value) { this.incotermCode = value; } /** * Gets the value of the incotermText property. * * @return * possible object is * {@link String } * */ public String getIncotermText() { return incotermText; } /** * Sets the value of the incotermText property. * * @param value * allowed object is * {@link String } * */ public void setIncotermText(String value) { this.incotermText = value; } /** * Gets the value of the incotermLocation property. * * @return * possible object is * {@link String } * */ public String getIncotermLocation() { return incotermLocation; } /** * Sets the value of the incotermLocation property. * * @param value * allowed object is * {@link String } * */ public void setIncotermLocation(String value) { this.incotermLocation = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\IncotermType.java
2
请在Spring Boot框架中完成以下Java代码
public class PickingSlotQueueRepository { @NonNull private final IHUPickingSlotDAO dao = Services.get(IHUPickingSlotDAO.class); public PickingSlotQueuesSummary getNotEmptyQueuesSummary(@NonNull final PickingSlotQueueQuery query) { // TODO: improve performance by really running the aggregates in database // i.e. we need to implement something like org.adempiere.ad.dao.IQueryBuilder.aggregateOnColumn(java.lang.String, java.lang.Class<TargetModelType>) // but which is more low-level focuses, e.g. aggregate().groupBy(col1).groupBy(col2).countDistinct("colAlias", col3, col4).streamAsMaps()... final PickingSlotQueues queues = getNotEmptyQueues(query); return queues.getQueues() .stream() .map(queue -> PickingSlotQueueSummary.builder() .pickingSlotId(queue.getPickingSlotId()) .countHUs(queue.getCountHUs()) .build()) .collect(PickingSlotQueuesSummary.collect()); } public PickingSlotQueues getNotEmptyQueues(@NonNull final PickingSlotQueueQuery query) { final ImmutableListMultimap<PickingSlotId, PickingSlotQueueItem> items = dao.retrieveAllPickingSlotHUs(query) .stream() .collect(ImmutableListMultimap.toImmutableListMultimap( PickingSlotQueueRepository::extractPickingSlotId, PickingSlotQueueRepository::fromRecord )); return items.keySet() .stream() .map(pickingSlotId -> PickingSlotQueue.builder() .pickingSlotId(pickingSlotId) .items(items.get(pickingSlotId)) .build()) .collect(PickingSlotQueues.collect()); } public PickingSlotQueue getPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId) { final ImmutableList<PickingSlotQueueItem> items = dao.retrievePickingSlotHUs(ImmutableSet.of(pickingSlotId))
.stream() .map(PickingSlotQueueRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return PickingSlotQueue.builder() .pickingSlotId(pickingSlotId) .items(items) .build(); } private static @NonNull PickingSlotId extractPickingSlotId(final I_M_PickingSlot_HU queueItemRecord) { return PickingSlotId.ofRepoId(queueItemRecord.getM_PickingSlot_ID()); } private static PickingSlotQueueItem fromRecord(final I_M_PickingSlot_HU queueItemRecord) { return PickingSlotQueueItem.builder() .huId(HuId.ofRepoId(queueItemRecord.getM_HU_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotQueueRepository.java
2
请在Spring Boot框架中完成以下Java代码
public List<SmsHomeAdvertise> list(String name, Integer type, String endTime, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); SmsHomeAdvertiseExample example = new SmsHomeAdvertiseExample(); SmsHomeAdvertiseExample.Criteria criteria = example.createCriteria(); if (!StrUtil.isEmpty(name)) { criteria.andNameLike("%" + name + "%"); } if (type != null) { criteria.andTypeEqualTo(type); } if (!StrUtil.isEmpty(endTime)) { String startStr = endTime + " 00:00:00"; String endStr = endTime + " 23:59:59"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start = null; try { start = sdf.parse(startStr); } catch (ParseException e) {
e.printStackTrace(); } Date end = null; try { end = sdf.parse(endStr); } catch (ParseException e) { e.printStackTrace(); } if (start != null && end != null) { criteria.andEndTimeBetween(start, end); } } example.setOrderByClause("sort desc"); return advertiseMapper.selectByExample(example); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsHomeAdvertiseServiceImpl.java
2
请完成以下Java代码
void postConstruct() { final IProgramaticCalloutProvider programmaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class); programmaticCalloutProvider.registerAnnotatedCallout(this); } @CalloutMethod(columnNames = I_C_BPartner_Location_QuickInput.COLUMNNAME_C_Location_ID) public void onLocationChanged(@NonNull final I_C_BPartner_Location_QuickInput record) { final LocationId id = LocationId.ofRepoIdOrNull(record.getC_Location_ID()); if (id == null) { return; } final I_C_Location locationRecord = locationDAO.getById(id); if (locationRecord == null) { // location not yet created. Nothing to do yet return; } final POInfo poInfo = POInfo.getPOInfo(I_C_BPartner_Location_QuickInput.Table_Name); // gh12157: Please, keep in sync with org.compiere.model.MBPartnerLocation.beforeSave final String name = MakeUniqueLocationNameCommand.builder() .name(record.getName())
.address(locationRecord) .companyName(getCompanyNameOrNull(record)) .existingNames(repo.getOtherLocationNames(record.getC_BPartner_QuickInput_ID(), record.getC_BPartner_Location_QuickInput_ID())) .maxLength(poInfo.getFieldLength(I_C_BPartner_Location_QuickInput.COLUMNNAME_Name)) .build() .execute(); record.setName(name); } @Nullable private String getCompanyNameOrNull(@NonNull final I_C_BPartner_Location_QuickInput record) { final BPartnerQuickInputId bpartnerQuickInputId = BPartnerQuickInputId.ofRepoIdOrNull(record.getC_BPartner_QuickInput_ID()); if (bpartnerQuickInputId != null) { final I_C_BPartner_QuickInput bpartnerQuickInputRecord = repo.getById(bpartnerQuickInputId); return bpartnerQuickInputRecord.getCompanyname(); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\callout\C_BPartner_Location_QuickInput.java
1
请完成以下Java代码
public final I_C_UOM getC_UOM() { return orderBOMBL.getBOMLineUOM(ppOrderBOMLine); } @Override public ProductionMaterialType getType() { return type; } @Override public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw) { ppOrderBOMLine.setQM_QtyDeliveredPercOfRaw(qtyDeliveredPercOfRaw); } @Override public BigDecimal getQM_QtyDeliveredPercOfRaw() { return ppOrderBOMLine.getQM_QtyDeliveredPercOfRaw(); } @Override public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg) { ppOrderBOMLine.setQM_QtyDeliveredAvg(qtyDeliveredAvg); } @Override public BigDecimal getQM_QtyDeliveredAvg() { return ppOrderBOMLine.getQM_QtyDeliveredAvg(); } @Override public Object getModel() { return ppOrderBOMLine; }
@Override public String getVariantGroup() { return ppOrderBOMLine.getVariantGroup(); } @Override public BOMComponentType getComponentType() { return BOMComponentType.ofCode(ppOrderBOMLine.getComponentType()); } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { if (!_handlingUnitsInfoLoaded) { _handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrderBOMLine); _handlingUnitsInfoLoaded = true; } return _handlingUnitsInfo; } @Override public I_M_Product getMainComponentProduct() { return mainComponentProduct; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderBOMLineProductionMaterial.java
1
请完成以下Java代码
private void generateMissingInvoiceCandidatesForModel(@NonNull final List<TableRecordReference> modelReferences) { final List<Object> models = TableRecordReference.getModels(modelReferences, Object.class); final Multimap<AsyncBatchId, Object> batchIdWithUpdatedModel = asyncBatchBL.assignTempAsyncBatchToModelsIfMissing( models, Async_Constants.C_Async_Batch_InternalName_EnqueueInvoiceCandidateCreation); for (final AsyncBatchId asyncBatchId : batchIdWithUpdatedModel.keySet()) { final Collection<Object> modelsWithBatchId = batchIdWithUpdatedModel.get(asyncBatchId); final Supplier<IEnqueueResult> action = () -> { int counter = 0; for (final Object modelWithBatchId : modelsWithBatchId) { CreateMissingInvoiceCandidatesWorkpackageProcessor.schedule(modelWithBatchId); counter++; } final int finalCounter = counter; // a lambda's return value should be final return () -> finalCounter; // return the numer of workpackages that we enqeued
}; asyncBatchService.executeBatch(action, asyncBatchId); } } @NonNull private IInvoicingParams createDefaultIInvoicingParams() { final PlainInvoicingParams invoicingParams = new PlainInvoicingParams(); invoicingParams.setIgnoreInvoiceSchedule(false); invoicingParams.setDateInvoiced(LocalDate.now()); return invoicingParams; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\CreateInvoiceForModelService.java
1
请完成以下Java代码
class FindPanelContainer_Embedded extends FindPanelContainer { private PropertyChangeSupport _pcs; private static final String PROPERTY_Expanded = FindPanelContainer.class.getName() + ".Expanded"; private boolean expanded = false; public FindPanelContainer_Embedded(final FindPanelBuilder builder) { super(builder); } @Override protected void init(final FindPanelBuilder builder) { findPanel.setVisible(expanded); findPanel.setEnabled(expanded); } @Override public final JComponent getComponent() { return findPanel; } @Override public boolean isExpanded() { return expanded; } @Override public void setExpanded(final boolean expanded) { if (this.expanded == expanded) { return; } this.expanded = expanded; findPanel.setVisible(expanded); findPanel.setEnabled(expanded); _pcs.firePropertyChange(PROPERTY_Expanded, !expanded, expanded); } @Override public boolean isFocusable() { return findPanel.isFocusable(); } @Override public void requestFocus() { findPanel.requestFocus(); } @Override public boolean requestFocusInWindow() {
return findPanel.requestFocusInWindow(); } private final synchronized PropertyChangeSupport getPropertyChangeSupport() { if (_pcs == null) { _pcs = new PropertyChangeSupport(this); } return _pcs; } @Override public void runOnExpandedStateChange(final Runnable runnable) { Check.assumeNotNull(runnable, "runnable not null"); getPropertyChangeSupport().addPropertyChangeListener(PROPERTY_Expanded, new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { runnable.run(); } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_EmbeddedPanel.java
1
请完成以下Java代码
public I_K_Entry getK_Entry() throws RuntimeException { return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name) .getPO(getK_Entry_ID(), get_TrxName()); } /** Set Entry. @param K_Entry_ID Knowledge Entry */ public void setK_Entry_ID (int K_Entry_ID) { if (K_Entry_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID)); } /** Get Entry. @return Knowledge Entry */ public int getK_Entry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Related Entry. @param K_EntryRelated_ID Related Entry for this Enntry */ public void setK_EntryRelated_ID (int K_EntryRelated_ID) { if (K_EntryRelated_ID < 1) set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, null); else set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, Integer.valueOf(K_EntryRelated_ID)); } /** Get Related Entry. @return Related Entry for this Enntry */ public int getK_EntryRelated_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_EntryRelated_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair
*/ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getK_EntryRelated_ID())); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_EntryRelated.java
1
请在Spring Boot框架中完成以下Java代码
public class X_ExternalSystem_Config extends org.compiere.model.PO implements I_ExternalSystem_Config, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1603772571L; /** Standard Constructor */ public X_ExternalSystem_Config (final Properties ctx, final int ExternalSystem_Config_ID, @Nullable final String trxName) { super (ctx, ExternalSystem_Config_ID, trxName); } /** Load Constructor */ public X_ExternalSystem_Config (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAuditFileFolder (final java.lang.String AuditFileFolder) { set_Value (COLUMNNAME_AuditFileFolder, AuditFileFolder); } @Override public java.lang.String getAuditFileFolder() { return get_ValueAsString(COLUMNNAME_AuditFileFolder); } @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 setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); }
@Override public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class); } @Override public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_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); } @Override public void setWriteAudit (final boolean WriteAudit) { set_Value (COLUMNNAME_WriteAudit, WriteAudit); } @Override public boolean isWriteAudit() { return get_ValueAsBoolean(COLUMNNAME_WriteAudit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config.java
2
请完成以下Java代码
private static BPartnerQuery createBPartnerQuery( @NonNull final Collection<BPartnerCompositeLookupKey> bpartnerLookupKeys, @Nullable final OrgId onlyOrgId) { final BPartnerQueryBuilder query = BPartnerQuery.builder(); if (onlyOrgId != null) { query.onlyOrgId(onlyOrgId) .onlyOrgId(OrgId.ANY); } for (final BPartnerCompositeLookupKey bpartnerLookupKey : bpartnerLookupKeys) { addKeyToQueryBuilder(bpartnerLookupKey, query); } return query.build(); } private static void addKeyToQueryBuilder(final BPartnerCompositeLookupKey bpartnerLookupKey, final BPartnerQueryBuilder queryBuilder) { final JsonExternalId jsonExternalId = bpartnerLookupKey.getJsonExternalId(); if (jsonExternalId != null) { queryBuilder.externalId(JsonConverters.fromJsonOrNull(jsonExternalId)); } final String value = bpartnerLookupKey.getCode(); if (isNotBlank(value)) {
queryBuilder.bpartnerValue(value.trim()); } final GLN gln = bpartnerLookupKey.getGln(); if (gln != null) { queryBuilder.gln(gln); } final GlnWithLabel glnWithLabel = bpartnerLookupKey.getGlnWithLabel(); if (glnWithLabel != null) { queryBuilder.gln(glnWithLabel.getGln()); queryBuilder.glnLookupLabel(glnWithLabel.getLabel()); } final MetasfreshId metasfreshId = bpartnerLookupKey.getMetasfreshId(); if (metasfreshId != null) { queryBuilder.bPartnerId(BPartnerId.ofRepoId(metasfreshId.getValue())); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerQueryService.java
1
请在Spring Boot框架中完成以下Java代码
public class AgeAttributeStorageListener implements IAttributeStorageListener { private final transient AgeAttributesService ageAttributesService; public AgeAttributeStorageListener(final AgeAttributesService ageAttributesService) { this.ageAttributesService = ageAttributesService; Services.get(IAttributeStorageFactoryService.class).addAttributeStorageListener(this); } @Override public void onAttributeValueChanged( @NonNull final IAttributeValueContext attributeValueContext, @NonNull final IAttributeStorage storage, final IAttributeValue attributeValue, final Object valueOld) { // checks and so on final AbstractHUAttributeStorage huAttributeStorage = AbstractHUAttributeStorage.castOrNull(storage); final boolean storageIsAboutHUs = huAttributeStorage != null; if (!storageIsAboutHUs) { return; }
final boolean relevantAttributesArePresent = storage.hasAttribute(HUAttributeConstants.ATTR_Age) && storage.hasAttribute(HUAttributeConstants.ATTR_ProductionDate); if (!relevantAttributesArePresent) { return; } final AttributeCode attributeCode = attributeValue.getAttributeCode(); final boolean relevantAttributeHasChanged = HUAttributeConstants.ATTR_ProductionDate.equals(attributeCode); if (!relevantAttributeHasChanged) { return; } // actual logic starts here final LocalDateTime productionDate = storage.getValueAsLocalDateTime(HUAttributeConstants.ATTR_ProductionDate); if (productionDate != null) { final Age age = ageAttributesService.getAgeValues().computeAgeInMonths(productionDate); storage.setValue(HUAttributeConstants.ATTR_Age, age.toStringValue()); } else { storage.setValue(HUAttributeConstants.ATTR_Age, null); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\age\AgeAttributeStorageListener.java
2
请完成以下Java代码
public Optional<IssuingToleranceSpec> getIssuingToleranceSpec(@NonNull final ProductId productId) { final I_M_Product product = getById(productId); return extractIssuingToleranceSpec(product); } @Override public boolean isProductUsed(@NonNull final ProductId productId) { return queryBL .createQueryBuilder(I_C_OrderLine.class) .addEqualsFilter(I_C_OrderLine.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .anyMatch() || queryBL .createQueryBuilder(I_C_InvoiceLine.class) .addEqualsFilter(I_C_InvoiceLine.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .anyMatch() || queryBL .createQueryBuilder(I_M_InOutLine.class) .addEqualsFilter(I_M_InOutLine.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .anyMatch() || queryBL // Even if a product was not yet ordered/delivered/invoiced, it might be a component and thus end up in a cost-detail.. .createQueryBuilder(I_M_CostDetail.class) .addEqualsFilter(I_M_CostDetail.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .anyMatch(); } @Override
public Set<ProductId> getProductIdsMatchingQueryString( @NonNull final String queryString, @NonNull final ClientId clientId, @NonNull QueryLimit limit) { final IQueryBuilder<I_M_Product> queryBuilder = queryBL.createQueryBuilder(I_M_Product.class) .setLimit(limit) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Client_ID, clientId); queryBuilder.addCompositeQueryFilter() .setJoinOr() .addStringLikeFilter(I_M_Product.COLUMNNAME_Value, queryString, true) .addStringLikeFilter(I_M_Product.COLUMNNAME_Name, queryString, true); return queryBuilder.create().idsAsSet(ProductId::ofRepoIdOrNull); } @Override public void save(I_M_Product record) { InterfaceWrapperHelper.save(record); } @Override public boolean isExistingValue(@NonNull final String value, @NonNull final ClientId clientId) { return queryBL.createQueryBuilder(I_M_Product.class) //.addOnlyActiveRecordsFilter() // check inactive records too .addEqualsFilter(I_M_Product.COLUMNNAME_Value, value) .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Client_ID, clientId) .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impl\ProductDAO.java
1
请完成以下Java代码
public Image getCapture() { Mat mat = new Mat(); capture.read(mat); return mat2Img(mat); } public Image getCaptureWithFaceDetection() { Mat mat = new Mat(); capture.read(mat); Mat haarClassifiedImg = detectFace(mat); return mat2Img(haarClassifiedImg); } public Image mat2Img(Mat mat) { MatOfByte bytes = new MatOfByte(); Imgcodecs.imencode("img", mat, bytes); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray()); Image img = new Image(inputStream); return img; } public static void main(String[] args) {
Application.launch(args); } public static Mat detectFace(Mat inputImage) { MatOfRect facesDetected = new MatOfRect(); CascadeClassifier cascadeClassifier = new CascadeClassifier(); int minFaceSize = Math.round(inputImage.rows() * 0.1f); cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml"); cascadeClassifier.detectMultiScale(inputImage, facesDetected, 1.1, 3, Objdetect.CASCADE_SCALE_IMAGE, new Size(minFaceSize, minFaceSize), new Size()); Rect[] facesArray = facesDetected.toArray(); for (Rect face : facesArray) { Imgproc.rectangle(inputImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3); } return inputImage; } }
repos\tutorials-master\image-processing\src\main\java\com\baeldung\imageprocessing\opencv\CameraStream.java
1
请完成以下Java代码
public class IPOfflineUtil { private static final String UNKNOWN = "unknown"; protected IPOfflineUtil() { } public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_FORWARDED_FOR"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_FORWARDED"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_VIA"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("REMOTE_ADDR"); } if (!StringUtils.hasLength(ip) || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } int index = ip.indexOf(","); if (index != -1) { ip = ip.substring(0, index); }
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; } public static String getAddr(String ip) { String dbPath = "D:\\IdeaProjects\\ETFramework\\ipfilter\\src\\main\\resources\\ip2region\\ip2region.xdb"; // 1、from dbPath load all xdb to memory。 byte[] cBuff; try { cBuff = Searcher.loadContentFromFile(dbPath); } catch (Exception e) { log.info("failed to load content from `%s`: %s\n", dbPath, e); return null; } // 2、usr cBuff create a query object base on memory。 Searcher searcher; try { searcher = Searcher.newWithBuffer(cBuff); } catch (Exception e) { log.info("failed to create content cached searcher: %s\n", e); return null; } // 3、query try { String region = searcher.search(ip); return region; } catch (Exception e) { log.info("failed to search(%s): %s\n", ip, e); } return null; } }
repos\springboot-demo-master\ipfilter\src\main\java\com\et\ipfilter\util\IPOfflineUtil.java
1
请完成以下Java代码
public CustomerTradeMarginLineId getIdNotNull() { if (this.customerTradeMarginLineId == null) { throw new AdempiereException("getIdNotNull() should be called only for already persisted CustomerTradeMarginLine objects!") .appendParametersToMessage() .setParameter("CustomerTradeMarginLine", this); } return customerTradeMarginLineId; } public boolean appliesTo(@NonNull final MappingCriteria mappingCriteria) { return appliesToCustomer(mappingCriteria.getCustomerId()) && appliesToProduct(mappingCriteria.getProductId()) && appliesToProductCategory(mappingCriteria.getProductCategoryId()); } private boolean appliesToCustomer(@NonNull final BPartnerId customerCandidateId) { if (this.customerId == null) { return true; } return this.customerId.equals(customerCandidateId); } private boolean appliesToProduct(@NonNull final ProductId productId) { if (this.productId == null)
{ return true; } return this.productId.equals(productId); } private boolean appliesToProductCategory(@NonNull final ProductCategoryId productCategoryId) { if (this.productCategoryId == null) { return true; } return this.productCategoryId.equals(productCategoryId); } @NonNull public Percent getPercent() { return Percent.of(this.marginPercent); } @Value @Builder public static class MappingCriteria { @NonNull BPartnerId customerId; @NonNull ProductId productId; @NonNull ProductCategoryId productCategoryId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\CustomerTradeMarginLine.java
1
请完成以下Java代码
public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String[] getProcessDefinitionIdIn() { return processDefinitionIdIn; } public String[] getProcessDefinitionKeyIn() { return processDefinitionKeyIn; } public String[] getTenantIdIn() { return tenantIdIn; } public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } public boolean isTenantIdSet() { return isTenantIdSet; }
public boolean isCompact() { return isCompact; } protected void provideHistoryCleanupStrategy(CommandContext commandContext) { String historyCleanupStrategy = commandContext.getProcessEngineConfiguration() .getHistoryCleanupStrategy(); isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy); } public boolean isHistoryCleanupStrategyRemovalTimeBased() { return isHistoryCleanupStrategyRemovalTimeBased; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricProcessInstanceReportImpl.java
1
请完成以下Java代码
public static Optional<PaymentId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final PaymentId id) { return id != null ? id.getRepoId() : -1; } public static ImmutableSet<PaymentId> fromIntSet(@NonNull final Collection<Integer> repoIds) { if (repoIds.isEmpty()) { return ImmutableSet.of(); } return repoIds.stream().map(PaymentId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()); } public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<PaymentId> ids) { if (ids.isEmpty()) { return ImmutableSet.of(); } return ids.stream().map(PaymentId::getRepoId).collect(ImmutableSet.toImmutableSet());
} int repoId; private PaymentId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Payment_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable PaymentId id1, @Nullable PaymentId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\PaymentId.java
1
请完成以下Java代码
public class M_ShipmentSchedule { public static M_ShipmentSchedule INSTANCE = new M_ShipmentSchedule(); private M_ShipmentSchedule() { } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_M_ShipmentSchedule.COLUMNNAME_QtyDelivered, I_M_ShipmentSchedule.COLUMNNAME_QtyPickList }) public void updateSubScriptionProgress(final I_M_ShipmentSchedule shipmentSchedule) { final I_C_SubscriptionProgress subscriptionProgress = getSubscriptionRecordOrNull(shipmentSchedule); if (subscriptionProgress == null) { return; } final BigDecimal qtyDelivered = shipmentSchedule.getQtyDelivered(); if (qtyDelivered.compareTo(subscriptionProgress.getQty()) >= 0) { subscriptionProgress.setStatus(X_C_SubscriptionProgress.STATUS_Done); InterfaceWrapperHelper.save(subscriptionProgress); return; } final BigDecimal qtyPickList = shipmentSchedule.getQtyPickList(); if (qtyPickList.signum() > 0) { subscriptionProgress.setStatus(X_C_SubscriptionProgress.STATUS_InPicking); InterfaceWrapperHelper.save(subscriptionProgress); return; }
subscriptionProgress.setStatus(X_C_SubscriptionProgress.STATUS_Open); InterfaceWrapperHelper.save(subscriptionProgress); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE }) public void updateSubScriptionProgressAfterDelete(final I_M_ShipmentSchedule shipmentSchedule) { final I_C_SubscriptionProgress subscriptionProgress = getSubscriptionRecordOrNull(shipmentSchedule); if (subscriptionProgress == null) { return; } subscriptionProgress.setProcessed(false); subscriptionProgress.setM_ShipmentSchedule_ID(0); subscriptionProgress.setStatus(X_C_SubscriptionProgress.STATUS_Planned); InterfaceWrapperHelper.save(subscriptionProgress); } private I_C_SubscriptionProgress getSubscriptionRecordOrNull(final I_M_ShipmentSchedule shipmentSchedule) { final TableRecordReference ref = TableRecordReference.of(shipmentSchedule.getAD_Table_ID(), shipmentSchedule.getRecord_ID()); if (!I_C_SubscriptionProgress.Table_Name.equals(ref.getTableName())) { return null; } final I_C_SubscriptionProgress subscriptionProgress = ref.getModel( InterfaceWrapperHelper.getContextAware(shipmentSchedule), I_C_SubscriptionProgress.class); return subscriptionProgress; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\M_ShipmentSchedule.java
1
请在Spring Boot框架中完成以下Java代码
static class SimpleAsyncTaskSchedulerBuilderConfiguration { private final TaskSchedulingProperties properties; private final ObjectProvider<TaskDecorator> taskDecorator; private final ObjectProvider<SimpleAsyncTaskSchedulerCustomizer> taskSchedulerCustomizers; SimpleAsyncTaskSchedulerBuilderConfiguration(TaskSchedulingProperties properties, ObjectProvider<TaskDecorator> taskDecorator, ObjectProvider<SimpleAsyncTaskSchedulerCustomizer> taskSchedulerCustomizers) { this.properties = properties; this.taskDecorator = taskDecorator; this.taskSchedulerCustomizers = taskSchedulerCustomizers; } @Bean @ConditionalOnMissingBean @ConditionalOnThreading(Threading.PLATFORM) SimpleAsyncTaskSchedulerBuilder simpleAsyncTaskSchedulerBuilder() { return builder(); } @Bean(name = "simpleAsyncTaskSchedulerBuilder") @ConditionalOnMissingBean @ConditionalOnThreading(Threading.VIRTUAL) SimpleAsyncTaskSchedulerBuilder simpleAsyncTaskSchedulerBuilderVirtualThreads() { return builder().virtualThreads(true); }
private SimpleAsyncTaskSchedulerBuilder builder() { SimpleAsyncTaskSchedulerBuilder builder = new SimpleAsyncTaskSchedulerBuilder(); builder = builder.threadNamePrefix(this.properties.getThreadNamePrefix()); builder = builder.taskDecorator(getTaskDecorator(this.taskDecorator)); builder = builder.customizers(this.taskSchedulerCustomizers.orderedStream()::iterator); TaskSchedulingProperties.Simple simple = this.properties.getSimple(); builder = builder.concurrencyLimit(simple.getConcurrencyLimit()); TaskSchedulingProperties.Shutdown shutdown = this.properties.getShutdown(); if (shutdown.isAwaitTermination()) { builder = builder.taskTerminationTimeout(shutdown.getAwaitTerminationPeriod()); } return builder; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskSchedulingConfigurations.java
2
请完成以下Java代码
private static void startAddOns() { final IAddonStarter addonStarter = new AddonStarter(); addonStarter.startAddons(); } /** * If enabled, everything will run database decoupled. Supposed to be called before an interface like org.compiere.model.I_C_Order is to be used in a unit test. */ public static void enableUnitTestMode() { unitTestMode = true; } public static boolean isUnitTestMode() { return unitTestMode; } public static void assertUnitTestMode() { if (!isUnitTestMode()) { throw new IllegalStateException("JUnit test mode shall be enabled");
} } private static boolean unitTestMode = false; public static boolean isJVMDebugMode() { Boolean jvmDebugMode = Adempiere._jvmDebugMode; if (jvmDebugMode == null) { jvmDebugMode = Adempiere._jvmDebugMode = computeJVMDebugMode(); } return jvmDebugMode; } private static boolean computeJVMDebugMode() { return java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("-agentlib:jdwp"); } } // Adempiere
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\Adempiere.java
1
请完成以下Java代码
public void setRuecknahmeangebotVereinbart(boolean value) { this.ruecknahmeangebotVereinbart = value; } /** * Gets the value of the sondertag property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the sondertag property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSondertag().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TypSondertag } * * */ public List<TypSondertag> getSondertag() { if (sondertag == null) { sondertag = new ArrayList<TypSondertag>(); } return this.sondertag; } /** * Gets the value of the automatischerAbruf property. * */ public boolean isAutomatischerAbruf() { return automatischerAbruf; } /** * Sets the value of the automatischerAbruf property. * */ public void setAutomatischerAbruf(boolean value) { this.automatischerAbruf = value; } /** * Gets the value of the kundenKennung property.
* * @return * possible object is * {@link String } * */ public String getKundenKennung() { return kundenKennung; } /** * Sets the value of the kundenKennung property. * * @param value * allowed object is * {@link String } * */ public void setKundenKennung(String value) { this.kundenKennung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VertragsdatenAntwort.java
1
请完成以下Java代码
public void setOldValue (java.lang.String OldValue) { set_ValueNoCheck (COLUMNNAME_OldValue, OldValue); } /** Get Alter Wert. @return The old file data */ @Override public java.lang.String getOldValue () { return (java.lang.String)get_Value(COLUMNNAME_OldValue); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Redo. @param Redo Redo */ @Override public void setRedo (java.lang.String Redo) { set_Value (COLUMNNAME_Redo, Redo); } /** Get Redo.
@return Redo */ @Override public java.lang.String getRedo () { return (java.lang.String)get_Value(COLUMNNAME_Redo); } /** Set Transaktion. @param TrxName Name of the transaction */ @Override public void setTrxName (java.lang.String TrxName) { set_ValueNoCheck (COLUMNNAME_TrxName, TrxName); } /** Get Transaktion. @return Name of the transaction */ @Override public java.lang.String getTrxName () { return (java.lang.String)get_Value(COLUMNNAME_TrxName); } /** Set Undo. @param Undo Undo */ @Override public void setUndo (java.lang.String Undo) { set_Value (COLUMNNAME_Undo, Undo); } /** Get Undo. @return Undo */ @Override public java.lang.String getUndo () { return (java.lang.String)get_Value(COLUMNNAME_Undo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog.java
1
请完成以下Java代码
/* package */ void validateBbanEntryCharacterType(final BBANStructureEntry entry, final String entryValue) { switch (entry.getCharacterType()) { case a: for (char ch : entryValue.toCharArray()) { Check.assume(Character.isUpperCase(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Upper_Letters", new Object[] { entryValue })); } break; case c: for (char ch : entryValue.toCharArray()) { Check.assume(Character.isLetterOrDigit(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Letters_Digits", new Object[] { entryValue })); } break; case n: for (char ch : entryValue.toCharArray()) { Check.assume(Character.isDigit(ch), msgBL.getMsg(Env.getCtx(), "BBAN_Digits", new Object[] { entryValue }));
} break; } } /* package */ BBANStructure getBBANCode(final String iban) { final String countryCode = getCountryCode(iban); return Services.get(IBBANStructureBL.class).getBBANStructureForCountry(countryCode); } private String fromCharCode(int... codePoints) { return new String(codePoints, 0, codePoints.length); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\IBANValidationBL.java
1
请完成以下Java代码
public ProcessInstanceMigrationValidationResult validateMigration(String processInstanceId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); return getProcessMigrationService().validateMigrationForProcessInstance(processInstanceId, document); } @Override public void migrateProcessInstances(String processDefinitionId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); getProcessMigrationService().migrateProcessInstancesOfProcessDefinition(processDefinitionId, document); } @Override public ProcessInstanceMigrationValidationResult validateMigrationOfProcessInstances(String processDefinitionId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); return getProcessMigrationService().validateMigrationForProcessInstancesOfProcessDefinition(processDefinitionId, document); } @Override public void migrateProcessInstances(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); getProcessMigrationService().migrateProcessInstancesOfProcessDefinition(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, document); } @Override public Batch batchMigrateProcessInstances(String processDefinitionId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); return getProcessMigrationService().batchMigrateProcessInstancesOfProcessDefinition(processDefinitionId, document); } @Override public Batch batchMigrateProcessInstances(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build();
return getProcessMigrationService().batchMigrateProcessInstancesOfProcessDefinition(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, document); } @Override public ProcessInstanceMigrationValidationResult validateMigrationOfProcessInstances(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId) { ProcessInstanceMigrationDocument document = migrationDocumentBuilder.build(); return getProcessMigrationService().validateMigrationForProcessInstancesOfProcessDefinition(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, document); } protected ProcessMigrationService getProcessMigrationService() { if (processInstanceMigrationService == null) { throw new FlowableException("ProcessInstanceMigrationService cannot be null, Obtain your builder instance from the ProcessInstanceMigrationService to access this feature"); } return processInstanceMigrationService; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\migration\ProcessInstanceMigrationBuilderImpl.java
1
请完成以下Java代码
public void setAttribute(String attributeName, Object attributeValue) { this.cached.setAttribute(attributeName, attributeValue); this.delta.put(getAttributeKey(attributeName), attributeValue); flushIfRequired(); } @Override public void removeAttribute(String attributeName) { setAttribute(attributeName, null); } @Override public Instant getCreationTime() { return this.cached.getCreationTime(); } @Override public void setLastAccessedTime(Instant lastAccessedTime) { this.cached.setLastAccessedTime(lastAccessedTime); this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, getLastAccessedTime().toEpochMilli()); flushIfRequired(); } @Override public Instant getLastAccessedTime() { return this.cached.getLastAccessedTime(); } @Override public void setMaxInactiveInterval(Duration interval) { this.cached.setMaxInactiveInterval(interval); this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); flushIfRequired(); } @Override public Duration getMaxInactiveInterval() { return this.cached.getMaxInactiveInterval(); } @Override public boolean isExpired() { return this.cached.isExpired(); } private void flushIfRequired() { if (RedisSessionRepository.this.flushMode == FlushMode.IMMEDIATE) { save(); } } private boolean hasChangedSessionId() { return !getId().equals(this.originalSessionId); } private void save() { saveChangeSessionId(); saveDelta(); if (this.isNew) {
this.isNew = false; } } private void saveChangeSessionId() { if (hasChangedSessionId()) { if (!this.isNew) { String originalSessionIdKey = getSessionKey(this.originalSessionId); String sessionIdKey = getSessionKey(getId()); RedisSessionRepository.this.sessionRedisOperations.rename(originalSessionIdKey, sessionIdKey); } this.originalSessionId = getId(); } } private void saveDelta() { if (this.delta.isEmpty()) { return; } String key = getSessionKey(getId()); RedisSessionRepository.this.sessionRedisOperations.opsForHash().putAll(key, new HashMap<>(this.delta)); RedisSessionRepository.this.sessionRedisOperations.expireAt(key, Instant.ofEpochMilli(getLastAccessedTime().toEpochMilli()) .plusSeconds(getMaxInactiveInterval().getSeconds())); this.delta.clear(); } } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\RedisSessionRepository.java
1
请完成以下Java代码
public void authorizePayPalOrder(final PaymentReservation reservation) { reservation.getStatus().assertApprovedByPayer(); PayPalOrder paypalOrder = paypalOrderService.getByReservationId(reservation.getId()); final Order apiOrder = paypalClient.authorizeOrder( paypalOrder.getExternalId(), createPayPalClientExecutionContext(reservation, paypalOrder)); paypalOrder = paypalOrderService.save(paypalOrder.getId(), apiOrder); if (!paypalOrder.isAuthorized()) { throw new AdempiereException("Not authorized: " + paypalOrder); } reservation.changeStatusTo(paypalOrder.getStatus().toPaymentReservationStatus()); paymentReservationRepo.save(reservation); completeSalesOrder(reservation.getSalesOrderId()); } private void completeSalesOrder(@NonNull final OrderId salesOrderId) { final IOrderDAO ordersRepo = Services.get(IOrderDAO.class); final I_C_Order order = ordersRepo.getById(salesOrderId); final DocStatus orderDocStatus = DocStatus.ofCode(order.getDocStatus()); if (orderDocStatus.isWaitingForPayment()) { Services.get(IDocumentBL.class).processEx(order, IDocument.ACTION_WaitComplete); ordersRepo.save(order);
} } public void processCapture( @NonNull final PaymentReservation reservation, @NonNull final PaymentReservationCapture capture) { reservation.getStatus().assertCompleted(); PayPalOrder paypalOrder = paypalOrderService.getByReservationId(capture.getReservationId()); final Boolean finalCapture = null; final Capture apiCapture = paypalClient.captureOrder( paypalOrder.getAuthorizationId(), moneyService.toAmount(capture.getAmount()), finalCapture, createPayPalClientExecutionContext(capture, paypalOrder)); paypalOrder = updatePayPalOrderFromAPI(paypalOrder.getExternalId()); updateReservationFromPayPalOrderNoSave(reservation, paypalOrder); } private static void updateReservationFromPayPalOrderNoSave( @NonNull final PaymentReservation reservation, @NonNull final PayPalOrder payPalOrder) { reservation.changeStatusTo(payPalOrder.getStatus().toPaymentReservationStatus()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\PayPal.java
1
请完成以下Java代码
public void setLocation (int x, int y) { super.setLocation (x, y); m_node.setXPosition(x); m_node.setYPosition(y); } /** * String Representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer("WFNode["); sb.append(getNodeId().getRepoId()).append("-").append(m_name) .append(",").append(getBounds()) .append("]"); return sb.toString(); } // toString /** * Get Font. * Italics if not editable * @return font */ public Font getFont () { Font base = new Font(null); if (!isEditable()) return base; // Return Bold Italic Font return new Font(base.getName(), Font.ITALIC | Font.BOLD, base.getSize()); } // getFont /************************************************************************** * Get Preferred Size * @return size */ public Dimension getPreferredSize () { return s_size; } // getPreferredSize /** * Paint Component * @param g Graphics */ protected void paintComponent (Graphics g) {
Graphics2D g2D = (Graphics2D)g; // center icon m_icon.paintIcon(this, g2D, s_size.width/2 - m_icon.getIconWidth()/2, 5); // Paint Text Color color = getForeground(); g2D.setPaint(color); Font font = getFont(); // AttributedString aString = new AttributedString(m_name); aString.addAttribute(TextAttribute.FONT, font); aString.addAttribute(TextAttribute.FOREGROUND, color); AttributedCharacterIterator iter = aString.getIterator(); // LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext()); float width = s_size.width - m_icon.getIconWidth() - 2; TextLayout layout = measurer.nextLayout(width); // center text float xPos = (float)(s_size.width/2 - layout.getBounds().getWidth()/2); float yPos = m_icon.getIconHeight() + 20; // layout.draw(g2D, xPos, yPos); width = s_size.width - 4; // 2 pt while (measurer.getPosition() < iter.getEndIndex()) { layout = measurer.nextLayout(width); yPos += layout.getAscent() + layout.getDescent() + layout.getLeading(); layout.draw(g2D, xPos, yPos); } } // paintComponent } // WFNode
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFNodeComponent.java
1
请完成以下Java代码
public void addTransactionListener( final TransactionState transactionState, final TransactionListener transactionListener ) { if (transactionState.equals(TransactionState.COMMITTING)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void beforeCommit(boolean readOnly) { transactionListener.execute(commandContext); } } ); } else if (transactionState.equals(TransactionState.COMMITTED)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void afterCommit() { transactionListener.execute(commandContext); } } ); } else if (transactionState.equals(TransactionState.ROLLINGBACK)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void beforeCompletion() { transactionListener.execute(commandContext); } } ); } else if (transactionState.equals(TransactionState.ROLLED_BACK)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { if (TransactionSynchronization.STATUS_ROLLED_BACK == status) { transactionListener.execute(commandContext); } } }
); } } protected abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered { public void suspend() {} public void resume() {} public void flush() {} public void beforeCommit(boolean readOnly) {} public void beforeCompletion() {} public void afterCommit() {} public void afterCompletion(int status) {} @Override public int getOrder() { return transactionSynchronizationAdapterOrder; } } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringTransactionContext.java
1
请完成以下Java代码
public class CandidateGroupsPayload implements Payload { private String id; private String taskId; private List<String> candidateGroups; public CandidateGroupsPayload() { this.id = UUID.randomUUID().toString(); } public CandidateGroupsPayload(String taskId, List<String> candidateGroups) { this(); this.taskId = taskId; this.candidateGroups = candidateGroups; } @Override public String getId() { return id; } public List<String> getCandidateGroups() {
return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } }
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\CandidateGroupsPayload.java
1
请完成以下Java代码
public class NoPropagationHUAttributePropagator extends AbstractHUAttributePropagator { /** * @return {@link X_M_HU_PI_Attribute#PROPAGATIONTYPE_NoPropagation}. */ @Override public String getPropagationType() { return X_M_HU_PI_Attribute.PROPAGATIONTYPE_NoPropagation; } /** * @return {@link X_M_HU_PI_Attribute#PROPAGATIONTYPE_NoPropagation}. */ @Override public String getReversalPropagationType() { return getPropagationType(); // same } /** * Gets the the attribute specified within the given <code>propagationContext</code> and calls {@link #setStorageValue(IAttributeStorage, I_M_Attribute, Object)} with that attribute, the given * <code>attributeSet</code> and the given <code>value</code>. Does no propagation (neither up nor down). * */ @Override public void propagateValue(final IHUAttributePropagationContext propagationContext, final IAttributeStorage attributeSet, final Object value) { // // Just set the value and nothing more
final I_M_Attribute attribute = propagationContext.getAttribute(); if (propagationContext.isUpdateStorageValue() && attributeSet.hasAttribute(attribute)) { setStorageValue(propagationContext, attributeSet, attribute, value); } } @Override public String toString() { return "NoPropagationHUAttributePropagator []"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\impl\NoPropagationHUAttributePropagator.java
1
请完成以下Java代码
public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; } public String getContentId() { return contentId; } public void setContentId(String contentId) { this.contentId = contentId; } public ByteArrayEntity getContent() { return content; } public void setContent(ByteArrayEntity content) { this.content = content; } public void setUserId(String userId) { this.userId = userId; } @Override public String getUserId() { return userId; } @Override public Date getTime() { return time; } @Override public void setTime(Date time) { this.time = time; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntity.java
1
请完成以下Java代码
private static String normalizeCode(@Nullable final Object obj) { return obj != null ? StringUtils.trimBlankToNull(obj.toString()) : null; } public static ScannedCode ofString(@NonNull final String code) {return new ScannedCode(code);} @Nullable public static ScannedCode ofNullableString(@Nullable final String code) { final String codeNorm = StringUtils.trimBlankToNull(code); return codeNorm != null ? new ScannedCode(codeNorm) : null; } @Nullable @JsonCreator(mode = JsonCreator.Mode.DELEGATING) // IMPORTANT: keep it here because we want to handle the case when the JSON value is empty string, number etc. public static ScannedCode ofNullableObject(@Nullable final Object obj) { final String code = normalizeCode(obj); return code != null ? new ScannedCode(code) : null;
} @Override @Deprecated public String toString() {return getAsString();} @JsonValue public String getAsString() {return code;} public GlobalQRCode toGlobalQRCode() {return toGlobalQRCodeIfMatching().orThrow();} public GlobalQRCodeParseResult toGlobalQRCodeIfMatching() {return GlobalQRCode.parse(code);} public PrintableScannedCode toPrintableScannedCode() {return PrintableScannedCode.of(this);} public String substring(final int beginIndex, final int endIndex) {return code.substring(beginIndex, endIndex);} public int length() {return code.length();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\ScannedCode.java
1
请完成以下Spring Boot application配置
# 开发环境配置 # 数据源配置,请修改为你项目的实际配置 spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=1
23456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
repos\spring-boot-api-project-seed-master\src\main\resources\application-dev.properties
2
请完成以下Java代码
public List<HistoricProcessInstance> findHistoricProcessInstancesByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) { return dataManager.findHistoricProcessInstancesByQueryCriteria(historicProcessInstanceQuery); } @Override public List<HistoricProcessInstance> findHistoricProcessInstancesAndVariablesByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) { return dataManager.findHistoricProcessInstancesAndVariablesByQueryCriteria(historicProcessInstanceQuery); } @Override public List<HistoricProcessInstance> findHistoricProcessInstanceIdsByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) { return dataManager.findHistoricProcessInstanceIdsByQueryCriteria(historicProcessInstanceQuery); } @Override public List<HistoricProcessInstance> findHistoricProcessInstancesByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findHistoricProcessInstancesByNativeQuery(parameterMap); } @Override public List<HistoricProcessInstance> findHistoricProcessInstancesBySuperProcessInstanceId(String historicProcessInstanceId) { return dataManager.findHistoricProcessInstancesBySuperProcessInstanceId(historicProcessInstanceId); } @Override public List<String> findHistoricProcessInstanceIdsBySuperProcessInstanceIds(Collection<String> superProcessInstanceIds) { return dataManager.findHistoricProcessInstanceIdsBySuperProcessInstanceIds(superProcessInstanceIds); }
@Override public List<String> findHistoricProcessInstanceIdsByProcessDefinitionId(String processDefinitionId) { return dataManager.findHistoricProcessInstanceIdsByProcessDefinitionId(processDefinitionId); } @Override public long findHistoricProcessInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findHistoricProcessInstanceCountByNativeQuery(parameterMap); } @Override public void deleteHistoricProcessInstances(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) { dataManager.deleteHistoricProcessInstances(historicProcessInstanceQuery); } @Override public void bulkDeleteHistoricProcessInstances(Collection<String> processInstanceIds) { dataManager.bulkDeleteHistoricProcessInstances(processInstanceIds); } protected HistoryManager getHistoryManager() { return engineConfiguration.getHistoryManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricProcessInstanceEntityManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void handleEvent(@NonNull final ShipmentScheduleUpdatedEvent event) { final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery.ofShipmentScheduleId(event.getShipmentScheduleId()); final CandidatesQuery candidatesQuery = CandidatesQuery .builder() .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .demandDetailsQuery(demandDetailsQuery) .build(); final Candidate candidate = candidateRepository.retrieveLatestMatchOrNull(candidatesQuery); final Candidate updatedCandidate; final DemandDetail demandDetail = DemandDetail.forDocumentLine( event.getShipmentScheduleId(), event.getDocumentLineDescriptor(), event.getMaterialDescriptor().getQuantity()); if (candidate == null) { updatedCandidate = Candidate .builderForEventDescriptor(event.getEventDescriptor()) .materialDescriptor(event.getMaterialDescriptor()) .minMaxDescriptor(event.getMinMaxDescriptor()) .type(CandidateType.DEMAND)
.businessCase(CandidateBusinessCase.SHIPMENT) .businessCaseDetail(demandDetail) .build(); } else { updatedCandidate = candidate.toBuilder() .materialDescriptor(event.getMaterialDescriptor()) .minMaxDescriptor(event.getMinMaxDescriptor()) .businessCaseDetail(demandDetail) .build(); } candidateChangeHandler.onCandidateNewOrChange(updatedCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\shipmentschedule\ShipmentScheduleUpdatedHandler.java
2
请在Spring Boot框架中完成以下Java代码
public boolean mv(String sourceFile, String targetFile) { return false; } @Override public File putFile(String dir) { return null; } @Override public List<File> mputFile(String dir) { return null; } @Override public String nlstFile(String dir) { return gateway.nlstFile(dir); } private static File convertInputStreamToFile(InputStream inputStream, String savePath) { OutputStream outputStream = null; File file = new File(savePath); try { outputStream = new FileOutputStream(file); int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } log.info("convert InputStream to file done, savePath is : {}", savePath); } catch (IOException e) {
log.error("error:", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { log.error("error:", e); } } } return file; } private static File convert(MultipartFile file) throws IOException { File convertFile = new File(file.getOriginalFilename()); convertFile.createNewFile(); FileOutputStream fos = new FileOutputStream(convertFile); fos.write(file.getBytes()); fos.close(); return convertFile; } }
repos\springboot-demo-master\sftp\src\main\java\com\et\sftp\service\impl\SftpServiceImpl.java
2
请完成以下Java代码
protected boolean isLeafActivity(ScopeImpl scope) { return scope.getActivities().isEmpty(); } @Override public ExecutionEntity resolveRepresentativeExecution() { return representativeExecution; } @Override public void remove(boolean skipCustomListeners, boolean skipIoMappings) { ExecutionEntity currentExecution = resolveRepresentativeExecution(); ExecutionEntity parentExecution = currentExecution.getParent(); currentExecution.setActivity((PvmActivity) sourceScope); currentExecution.setActivityInstanceId(activityInstance.getId()); currentExecution.deleteCascade("migration", skipCustomListeners, skipIoMappings); getParent().destroyAttachableExecution(parentExecution); setParent(null); for (MigratingTransitionInstance child : childTransitionInstances) { child.setParent(null); } for (MigratingActivityInstance child : childActivityInstances) { child.setParent(null); } for (MigratingEventScopeInstance child : childCompensationInstances) { child.setParent(null); } } @Override public ExecutionEntity createAttachableExecution() { ExecutionEntity scopeExecution = resolveRepresentativeExecution(); ExecutionEntity attachableExecution = scopeExecution;
if (currentScope.getActivityBehavior() instanceof ModificationObserverBehavior) { ModificationObserverBehavior behavior = (ModificationObserverBehavior) currentScope.getActivityBehavior(); attachableExecution = (ExecutionEntity) behavior.createInnerInstance(scopeExecution); } else { if (!scopeExecution.getNonEventScopeExecutions().isEmpty() || scopeExecution.getActivity() != null) { attachableExecution = (ExecutionEntity) scopeExecution.createConcurrentExecution(); attachableExecution.setActive(false); scopeExecution.forceUpdate(); } } return attachableExecution; } @Override public void destroyAttachableExecution(ExecutionEntity execution) { if (currentScope.getActivityBehavior() instanceof ModificationObserverBehavior) { ModificationObserverBehavior behavior = (ModificationObserverBehavior) currentScope.getActivityBehavior(); behavior.destroyInnerInstance(execution); } else { if (execution.isConcurrent()) { execution.remove(); execution.getParent().tryPruneLastConcurrentChild(); execution.getParent().forceUpdate(); } } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingActivityInstance.java
1
请在Spring Boot框架中完成以下Java代码
public class HelloWorldController { @RequestMapping("/hello") public Map<String, Object> showHelloWorld() { Map<String, Object> map = new HashMap<>(); map.put("msg", "HelloWorld"); return map; } @RequestMapping("/calByVistor") public Integer calByVistor(@RequestParam String expr) { try { // Debug log for incoming expression System.out.println("Received expression: " + expr); // Handle URL encoded newline characters expr = expr.replace("%20", " ").replace("%5Cn", "\n"); System.out.println("Processed expression: " + expr); // Initialize ANTLR components ANTLRInputStream input = new ANTLRInputStream(expr); LabeledExprLexer lexer = new LabeledExprLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); LabeledExprParser parser = new LabeledExprParser(tokens); ParseTree tree = parser.prog(); // parse // Debug log for parse tree System.out.println("Parse tree: " + tree.toStringTree(parser)); // Initialize EvalVisitor EvalVisitor eval = new EvalVisitor(); int outcome = eval.visit(tree); return outcome; } catch (Exception e) { e.printStackTrace(); return null; // Or handle the error in a more appropriate way } } @GetMapping("/calBylistener") public String calBylistener(@RequestParam String expr) {
try { // Handle URL encoded newline characters expr = expr.replace("%20", " ").replace("%5Cn", "\n"); InputStream is = new ByteArrayInputStream(expr.getBytes()); ANTLRInputStream input = new ANTLRInputStream(is); LabeledExprLexer lexer = new LabeledExprLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); LabeledExprParser parser = new LabeledExprParser(tokens); ParseTree tree = parser.prog(); // parse ParseTreeWalker walker = new ParseTreeWalker(); EvalListener listener = new EvalListener(); walker.walk(listener, tree); // Assuming the listener has a method to get the result of the last expression int result = listener.getResult(); return String.valueOf(result); } catch (Exception e) { e.printStackTrace(); return "Error: " + e.getMessage(); } } }
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\controller\HelloWorldController.java
2
请完成以下Java代码
public void setProducts(Set<Product> products) { this.products = products; } @OneToMany(mappedBy = "customerOrder" , cascade = CascadeType.ALL) private Set<Product> products; @Column private LocalDate orderDate; public CustomerOrder(Long id, Set<Product> products, LocalDate orderDate, Customer customer) { this.id = id; this.products = products; this.orderDate = orderDate; this.customer = customer; } @Override public String toString() { return "Consult{" + "id=" + id + ", products=" + products + ", orderDate=" + orderDate + ", customer=" + customer + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomerOrder co = (CustomerOrder) o; return Objects.equals(id, co.id);
} @Override public int hashCode() { return Objects.hash(id); } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="customer_id", nullable = false) private Customer customer; public Long getId() { return id; } public LocalDate getOrderDate() { return orderDate; } public void setOrderDate(LocalDate orderDate) { this.orderDate = orderDate; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\CustomerOrder.java
1
请完成以下Java代码
protected boolean isValidValueForResumePreviousBy(String resumePreviousBy) { return resumePreviousBy.equals(ResumePreviousBy.RESUME_BY_DEPLOYMENT_NAME) || resumePreviousBy.equals(ResumePreviousBy.RESUME_BY_PROCESS_DEFINITION_KEY); } protected Map<String, byte[]> findResources(final ClassLoader processApplicationClassloader, String paResourceRoot, String[] additionalResourceSuffixes) { return ProcessApplicationScanningUtil.findResources(processApplicationClassloader, paResourceRoot, metaFileUrl, additionalResourceSuffixes); } @Override public void cancelOperationStep(DeploymentOperation operationContext) { final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); final AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION); ProcessEngine processEngine = getProcessEngine(serviceContainer, processApplication.getDefaultDeployToEngineName()); // if a registration was performed, remove it. if (deployment != null && deployment.getProcessApplicationRegistration() != null) { processEngine.getManagementService().unregisterProcessApplication(deployment.getProcessApplicationRegistration().getDeploymentIds(), true); } // delete deployment if we were able to create one AND if // isDeleteUponUndeploy is set. if (deployment != null && PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_DELETE_UPON_UNDEPLOY, false)) { if (processEngine != null) { processEngine.getRepositoryService().deleteDeployment(deployment.getId(), true); } } }
protected ProcessEngine getProcessEngine(final PlatformServiceContainer serviceContainer) { return getProcessEngine(serviceContainer, ProcessEngines.NAME_DEFAULT); } protected ProcessEngine getProcessEngine(final PlatformServiceContainer serviceContainer, String defaultDeployToProcessEngineName) { String processEngineName = processArchive.getProcessEngineName(); if (processEngineName != null) { ProcessEngine processEngine = serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, processEngineName); ensureNotNull("Cannot deploy process archive '" + processArchive.getName() + "' to process engine '" + processEngineName + "' no such process engine exists", "processEngine", processEngine); return processEngine; } else { ProcessEngine processEngine = serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, defaultDeployToProcessEngineName); ensureNotNull("Cannot deploy process archive '" + processArchive.getName() + "' to default process: no such process engine exists", "processEngine", processEngine); return processEngine; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\DeployProcessArchiveStep.java
1
请完成以下Java代码
public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; }
public Integer getDisabled() { return disabled; } public void setDisabled(Integer disabled) { this.disabled = disabled; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
repos\springBoot-master\springboot-swagger-ui\src\main\java\com\abel\example\bean\User.java
1
请完成以下Java代码
private void purgeLinesOK(final Properties ctx, final IShipmentSchedulesDuringUpdate candidates) { for (final DeliveryGroupCandidate groupCandidate : candidates.getCandidates()) { for (final DeliveryLineCandidate lineCandidate : groupCandidate.getLines()) { try (final MDCCloseable mdcClosable = ShipmentSchedulesMDC.putShipmentScheduleId(lineCandidate.getShipmentScheduleId())) { // check the complete and postage free status final CompleteStatus completeStatus = lineCandidate.getCompleteStatus(); if (!CompleteStatus.OK.equals(completeStatus)) { logger.debug("Discard lineCandidate because completeStatus={}", completeStatus); lineCandidate.setDiscarded(); } // // final IProductBL productBL = Services.get(IProductBL.class); final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); // task 08745: by default we don't allow this, to stay backwards compatible final boolean allowShipSingleNonItems = sysConfigBL.getBooleanValue(AD_SYSCONFIG_DE_METAS_INOUTCANDIDATE_ALLOW_SHIP_SINGLE_NON_ITEMS, false); final boolean isItemProduct = productBL.getProductType(ProductId.ofRepoId(lineCandidate.getProductId())).isItem(); if (!allowShipSingleNonItems && !isItemProduct) { // allowShipSingleNonItems was true, we wouldn't have to care. // product is not an item -> check if there if there would // also be an item on the same inOut boolean inOutContainsItem = false; for (final DeliveryLineCandidate searchIol : groupCandidate.getLines()) {
if (productBL.getProductType(ProductId.ofRepoId(searchIol.getProductId())).isItem()) { inOutContainsItem = true; break; } } if (!inOutContainsItem) { // check if the delivery of this non-item has been // enforced using QtyToDeliver_Override>0 final BigDecimal qtyToDeliverOverride = lineCandidate.getQtyToDeliverOverride(); if (qtyToDeliverOverride == null || qtyToDeliverOverride.signum() <= 0) { logger.debug("Discard lineCandidate because its groupCandidate contains no 'item' products and qtyToDeliverOverride is not set"); lineCandidate.setDiscarded(); candidates.addStatusInfo(lineCandidate, Services.get(IMsgBL.class).getMsg(ctx, MSG_NO_ITEM_TO_SHIP)); } } } } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\DefaultCandidateProcessor.java
1
请完成以下Java代码
public Date getExitBefore() { return exitBefore; } public Date getExitAfter() { return exitAfter; } public Date getEndedBefore() { return endedBefore; } public Date getEndedAfter() { return endedAfter; } public String getStartUserId() { return startUserId; } public String getAssignee() { return assignee; } public String getCompletedBy() { return completedBy; } public String getReferenceId() { return referenceId; } public String getReferenceType() { return referenceType; } public boolean isEnded() { return ended; } public boolean isNotEnded() { return notEnded; } public String getEntryCriterionId() { return entryCriterionId; } public String getExitCriterionId() { return exitCriterionId; } public String getFormKey() { return formKey; } public String getExtraValue() { return extraValue; } public String getInvolvedUser() { return involvedUser; } public Collection<String> getInvolvedGroups() { return involvedGroups; } public boolean isOnlyStages() {
return onlyStages; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isIncludeLocalVariables() { return includeLocalVariables; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeCaseInstanceIds = safeProcessInstanceIds; } public Collection<String> getCaseInstanceIds() { return caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricPlanItemInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void onSuccess(@Nullable List<Void> result) { futureToSet.set(null); } @Override public void onFailure(Throwable t) { log.error("[{}] Exception during loading relation to edge on sync!", tenantId, t); futureToSet.setException(t); } }, dbCallbackExecutorService); } @Override public void onFailure(Throwable t) { log.error("[{}] Can't find entity views by entity id [{}]", tenantId, entityId, t); futureToSet.setException(t); }
}, dbCallbackExecutorService); return futureToSet; } private ListenableFuture<Void> saveEdgeEvent(TenantId tenantId, EdgeId edgeId, EdgeEventType type, EdgeEventActionType action, EntityId entityId, JsonNode body) { log.trace("Pushing edge event to edge queue. tenantId [{}], edgeId [{}], type [{}], action[{}], entityId [{}], body [{}]", tenantId, edgeId, type, action, entityId, body); EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(tenantId, edgeId, type, action, entityId, body); return edgeEventService.saveAsync(edgeEvent); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\sync\DefaultEdgeRequestsService.java
2
请在Spring Boot框架中完成以下Java代码
public CommentResponse getComment(@ApiParam(name = "processInstanceId") @PathVariable("processInstanceId") String processInstanceId, @ApiParam(name = "commentId") @PathVariable("commentId") String commentId) { HistoricProcessInstance instance = getHistoricProcessInstanceFromRequest(processInstanceId); Comment comment = taskService.getComment(commentId); if (comment == null || comment.getProcessInstanceId() == null || !comment.getProcessInstanceId().equals(instance.getId())) { throw new FlowableObjectNotFoundException("Process instance '" + instance.getId() + "' does not have a comment with id '" + commentId + "'.", Comment.class); } return restResponseFactory.createRestComment(comment); } @ApiOperation(value = "Delete a comment on a historic process instance", tags = { "History Process" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the historic process instance and comment were found and the comment is deleted. Response body is left empty intentionally."),
@ApiResponse(code = 404, message = "Indicates the requested historic process instance was not found or the historic process instance does not have a comment with the given ID.") }) @DeleteMapping(value = "/history/historic-process-instances/{processInstanceId}/comments/{commentId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteComment(@ApiParam(name = "processInstanceId") @PathVariable("processInstanceId") String processInstanceId, @ApiParam(name = "commentId") @PathVariable("commentId") String commentId) { HistoricProcessInstance instance = getHistoricProcessInstanceFromRequest(processInstanceId); Comment comment = taskService.getComment(commentId); if (comment == null || comment.getProcessInstanceId() == null || !comment.getProcessInstanceId().equals(instance.getId())) { throw new FlowableObjectNotFoundException("Process instance '" + instance.getId() + "' does not have a comment with id '" + commentId + "'.", Comment.class); } taskService.deleteComment(commentId); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceCommentResource.java
2
请完成以下Java代码
public NewRecordDescriptor getNewRecordDescriptorOrNull(@NonNull final String tableName) { return newRecordDescriptorsByTableName.get(tableName); } /** * @param entityDescriptor the entity descriptor of the quick input window (e.g. for BPartner that is C_BPartner_QuickInput) * @return new record descriptor */ public NewRecordDescriptor getNewRecordDescriptor(final DocumentEntityDescriptor entityDescriptor) { final WindowId newRecordWindowId = entityDescriptor.getWindowId(); return newRecordDescriptorsByTableName.values() .stream() .filter(descriptor -> WindowId.equals(newRecordWindowId, descriptor.getNewRecordWindowId())) .findFirst() .orElseThrow(() -> new AdempiereException("No new record quick input defined windowId=" + newRecordWindowId)); } @Nullable
public DocumentEntityDescriptor getNewRecordEntityDescriptorIfAvailable(@NonNull final String tableName) { final NewRecordDescriptor newRecordDescriptor = getNewRecordDescriptorOrNull(tableName); if (newRecordDescriptor == null) { return null; } try { return documentDescriptors.getDocumentEntityDescriptor(newRecordDescriptor.getNewRecordWindowId()); } catch (final Exception ex) { logger.warn("Failed fetching document entity descriptor for {}. Ignored", newRecordDescriptor, ex); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\NewRecordDescriptorsProvider.java
1
请完成以下Java代码
public XMLGregorianCalendar getEndDt() { return endDt; } /** * Sets the value of the endDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setEndDt(XMLGregorianCalendar value) { this.endDt = value; } /** * Gets the value of the txDtTm property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getTxDtTm() { return txDtTm; } /** * Sets the value of the txDtTm property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setTxDtTm(XMLGregorianCalendar value) { this.txDtTm = value; } /** * Gets the value of the prtry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prtry property. *
* <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryDate2 } * * */ public List<ProprietaryDate2> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryDate2>(); } return this.prtry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionDates2.java
1
请完成以下Java代码
private static int computeChecksum(final String barcodeWithoutChecksum) { int oddSum = 0; int evenSum = 0; // Loop through barcode without the checksum for (int i = 0; i < barcodeWithoutChecksum.length(); i++) { final int digit = Character.getNumericValue(barcodeWithoutChecksum.charAt(i)); if (i % 2 == 0) { // Odd positions (1st, 3rd, 5th, etc.) oddSum += digit; } else { // Even positions (2nd, 4th, 6th, etc.) evenSum += digit; } } // Multiply the even positions' sum by 3 evenSum *= 3; // Total sum final int totalSum = oddSum + evenSum; // Calculate check digit (nearest multiple of 10 - total sum % 10) final int nearestTen = (int)Math.ceil(totalSum / 10.0) * 10; return nearestTen - totalSum; } private static EAN13 parseVariableWeight(@NonNull final String barcode, @NonNull final EAN13Prefix prefix, final int checksum) { final EAN13ProductCode productNo = EAN13ProductCode.ofString(barcode.substring(2, 7)); // 5 digits for article code (AAAAA) final String weightStr = barcode.substring(7, 12); // 5 digits for weight (GGGGG) // Interpret the weight/measure (assume it's in grams or kilograms) final BigDecimal weightInKg = new BigDecimal(weightStr).divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP); return EAN13.builder() .barcode(barcode) .prefix(prefix) .productNo(productNo) .weightInKg(weightInKg) .checksum(checksum)
.build(); } private static EAN13 parseInternalUseOrVariableMeasure(@NonNull final String barcode, @NonNull final EAN13Prefix prefix, final int checksum) { // 4 digits for article code (IIII), // The digit at index 6 does not belong to the product code. It can be used for other purposes. For the time being it's ignored. // see https://www.gs1.org/docs/barcodes/SummaryOfGS1MOPrefixes20-29.pdf, page 81 (2.71 GS1 Switzerland) final EAN13ProductCode productNo = EAN13ProductCode.ofString(barcode.substring(2, 6)); final String weightStr = barcode.substring(7, 12); // 5 digits for weight (GGGGG) // Interpret the weight/measure (assume it's in grams or kilograms) final BigDecimal weightInKg = new BigDecimal(weightStr).divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP); return EAN13.builder() .barcode(barcode) .prefix(prefix) .productNo(productNo) .weightInKg(weightInKg) .checksum(checksum) .build(); } private static EAN13 parseStandardProduct(@NonNull final String barcode, @NonNull final EAN13Prefix prefix, final int checksum) { final String manufacturerAndProductCode = barcode.substring(3, 12); final EAN13ProductCode productNo = EAN13ProductCode.ofString(manufacturerAndProductCode); return EAN13.builder() .barcode(barcode) .prefix(prefix) .productNo(productNo) .checksum(checksum) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\ean13\EAN13Parser.java
1
请在Spring Boot框架中完成以下Java代码
protected Class<?> getConfiguration() { return EnableJpaRepositoriesConfiguration.class; } @Override protected RepositoryConfigurationExtension getRepositoryConfigurationExtension() { return new JpaRepositoryConfigExtension(); } @Override protected BootstrapMode getBootstrapMode() { return (this.bootstrapMode == null) ? BootstrapMode.DEFAULT : this.bootstrapMode; } @Override public void setEnvironment(Environment environment) { super.setEnvironment(environment); configureBootstrapMode(environment);
} private void configureBootstrapMode(Environment environment) { String property = environment.getProperty("spring.data.jpa.repositories.bootstrap-mode"); if (StringUtils.hasText(property)) { this.bootstrapMode = BootstrapMode.valueOf(property.toUpperCase(Locale.ENGLISH)); } } @EnableJpaRepositories private static final class EnableJpaRepositoriesConfiguration { } }
repos\spring-boot-4.0.1\module\spring-boot-data-jpa\src\main\java\org\springframework\boot\data\jpa\autoconfigure\DataJpaRepositoriesRegistrar.java
2
请完成以下Java代码
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception { FlowableHttpResponseHandler responseHandler = new FlowableHttpResponseHandler(); BpmnXMLUtil.addXMLLocation(responseHandler, xtr); if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_CLASS))) { responseHandler.setImplementation(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_CLASS)); responseHandler.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_CLASS); } else if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_DELEGATEEXPRESSION))) { responseHandler.setImplementation(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_DELEGATEEXPRESSION)); responseHandler.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION); } else if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_TYPE))) { responseHandler.setImplementationType(xtr.getAttributeValue(null, ATTRIBUTE_LISTENER_TYPE)); }
if (parentElement instanceof HttpServiceTask) { ((HttpServiceTask) parentElement).setHttpResponseHandler(responseHandler); if (ImplementationType.IMPLEMENTATION_TYPE_SCRIPT.equals(responseHandler.getImplementationType())) { parseChildElements(xtr, responseHandler, model, new ScriptInfoParser()); } else { parseChildElements(xtr, responseHandler, model, new FieldExtensionParser()); } } } @Override public String getElementName() { return ELEMENT_HTTP_RESPONSE_HANDLER; } }
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\child\FlowableHttpResponseHandlerParser.java
1
请完成以下Java代码
public List<TbResourceInfo> findSystemOrTenantResourcesByIds(TenantId tenantId, List<TbResourceId> resourceIds) { log.trace("Executing findSystemOrTenantResourcesByIds, tenantId [{}], resourceIds [{}]", tenantId, resourceIds); return resourceInfoDao.findSystemOrTenantResourcesByIds(tenantId, resourceIds); } @Override public String calculateEtag(byte[] data) { return Hashing.sha256().hashBytes(data).toString(); } @Override public TbResourceInfo findSystemOrTenantResourceByEtag(TenantId tenantId, ResourceType resourceType, String etag) { if (StringUtils.isEmpty(etag)) { return null; } log.trace("Executing findSystemOrTenantResourceByEtag [{}] [{}] [{}]", tenantId, resourceType, etag); return resourceInfoDao.findSystemOrTenantResourceByEtag(tenantId, resourceType, etag); } protected String encode(String data) { return encode(data.getBytes(StandardCharsets.UTF_8)); } protected String encode(byte[] data) { if (data == null || data.length == 0) { return ""; } return Base64.getEncoder().encodeToString(data); } protected String decode(String value) { if (value == null) { return null; } return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8); }
private final PaginatedRemover<TenantId, TbResourceId> tenantResourcesRemover = new PaginatedRemover<>() { @Override protected PageData<TbResourceId> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return resourceDao.findIdsByTenantId(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, TbResourceId resourceId) { deleteResource(tenantId, resourceId, true); } }; @TransactionalEventListener(classes = ResourceInfoEvictEvent.class) @Override public void handleEvictEvent(ResourceInfoEvictEvent event) { if (event.getResourceId() != null) { cache.evict(new ResourceInfoCacheKey(event.getResourceId())); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\resource\BaseResourceService.java
1
请完成以下Java代码
public I_C_ValidCombination getE_Expense_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getE_Expense_Acct(), get_TrxName()); } /** Set Employee Expense. @param E_Expense_Acct Account for Employee Expenses */ public void setE_Expense_Acct (int E_Expense_Acct) { set_Value (COLUMNNAME_E_Expense_Acct, Integer.valueOf(E_Expense_Acct)); } /** Get Employee Expense. @return Account for Employee Expenses */ public int getE_Expense_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_E_Expense_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getE_Prepayment_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getE_Prepayment_Acct(), get_TrxName()); } /** Set Employee Prepayment. @param E_Prepayment_Acct Account for Employee Expense Prepayments
*/ public void setE_Prepayment_Acct (int E_Prepayment_Acct) { set_Value (COLUMNNAME_E_Prepayment_Acct, Integer.valueOf(E_Prepayment_Acct)); } /** Get Employee Prepayment. @return Account for Employee Expense Prepayments */ public int getE_Prepayment_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_E_Prepayment_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Employee_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public void setTypeName(String typeName) { // Not relevant } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getExecutionId() { return executionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public String getMetaInfo() { return metaInfo; } @Override public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } // The methods below are not relevant, as getValue() is used directly to return the value set during the transaction @Override public String getTextValue() { return null;
} @Override public void setTextValue(String textValue) { } @Override public String getTextValue2() { return null; } @Override public void setTextValue2(String textValue2) { } @Override public Long getLongValue() { return null; } @Override public void setLongValue(Long longValue) { } @Override public Double getDoubleValue() { return null; } @Override public void setDoubleValue(Double doubleValue) { } @Override public byte[] getBytes() { return null; } @Override public void setBytes(byte[] bytes) { } @Override public Object getCachedValue() { return null; } @Override public void setCachedValue(Object cachedValue) { } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java
2
请完成以下Java代码
public final void onEvent(ActivitiEvent event) { if (isValidEvent(event)) { // Check if this event if (event.getType() == ActivitiEventType.ENTITY_CREATED) { onCreate(event); } else if (event.getType() == ActivitiEventType.ENTITY_INITIALIZED) { onInitialized(event); } else if (event.getType() == ActivitiEventType.ENTITY_DELETED) { onDelete(event); } else if (event.getType() == ActivitiEventType.ENTITY_UPDATED) { onUpdate(event); } else { // Entity-specific event onEntityEvent(event); } } } @Override public boolean isFailOnException() { return failOnException; } /** * @return true, if the event is an {@link ActivitiEntityEvent} and (if needed) the entityClass set in this instance, is assignable from the entity class in the event. */ protected boolean isValidEvent(ActivitiEvent event) { boolean valid = false; if (event instanceof ActivitiEntityEvent) { if (entityClass == null) { valid = true; } else { valid = entityClass.isAssignableFrom(((ActivitiEntityEvent) event).getEntity().getClass()); } } return valid; } /** * Called when an entity create event is received.
*/ protected void onCreate(ActivitiEvent event) { // Default implementation is a NO-OP } /** * Called when an entity initialized event is received. */ protected void onInitialized(ActivitiEvent event) { // Default implementation is a NO-OP } /** * Called when an entity delete event is received. */ protected void onDelete(ActivitiEvent event) { // Default implementation is a NO-OP } /** * Called when an entity update event is received. */ protected void onUpdate(ActivitiEvent event) { // Default implementation is a NO-OP } /** * Called when an event is received, which is not a create, an update or delete. */ protected void onEntityEvent(ActivitiEvent event) { // Default implementation is a NO-OP } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\BaseEntityEventListener.java
1
请在Spring Boot框架中完成以下Java代码
public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; parentTaskIdSet = true; } public void setCategory(String category) { this.category = category; categorySet = true; } public String getCategory() { return category; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; tenantIdSet = true; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; formKeySet = true; } public boolean isOwnerSet() { return ownerSet; } public boolean isAssigneeSet() { return assigneeSet; } public boolean isDelegationStateSet() {
return delegationStateSet; } public boolean isNameSet() { return nameSet; } public boolean isDescriptionSet() { return descriptionSet; } public boolean isDuedateSet() { return duedateSet; } public boolean isPrioritySet() { return prioritySet; } public boolean isParentTaskIdSet() { return parentTaskIdSet; } public boolean isCategorySet() { return categorySet; } public boolean isTenantIdSet() { return tenantIdSet; } public boolean isFormKeySet() { return formKeySet; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskRequest.java
2
请完成以下Java代码
public org.eevolution.model.I_PP_Order_Node getPP_Order_Node() throws RuntimeException { return (org.eevolution.model.I_PP_Order_Node)MTable.get(getCtx(), org.eevolution.model.I_PP_Order_Node.Table_Name) .getPO(getPP_Order_Node_ID(), get_TrxName()); } /** Set Manufacturing Order Activity. @param PP_Order_Node_ID Manufacturing Order Activity */ public void setPP_Order_Node_ID (int PP_Order_Node_ID) { if (PP_Order_Node_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Node_ID, Integer.valueOf(PP_Order_Node_ID)); } /** Get Manufacturing Order Activity. @return Manufacturing Order Activity */ public int getPP_Order_Node_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Node_ID); if (ii == null) return 0; return ii.intValue(); } public org.eevolution.model.I_PP_Order_Workflow getPP_Order_Workflow() throws RuntimeException
{ return (org.eevolution.model.I_PP_Order_Workflow)MTable.get(getCtx(), org.eevolution.model.I_PP_Order_Workflow.Table_Name) .getPO(getPP_Order_Workflow_ID(), get_TrxName()); } /** Set Manufacturing Order Workflow. @param PP_Order_Workflow_ID Manufacturing Order Workflow */ public void setPP_Order_Workflow_ID (int PP_Order_Workflow_ID) { if (PP_Order_Workflow_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Workflow_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Workflow_ID, Integer.valueOf(PP_Order_Workflow_ID)); } /** Get Manufacturing Order Workflow. @return Manufacturing Order Workflow */ public int getPP_Order_Workflow_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Workflow_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node_Asset.java
1
请完成以下Java代码
public class C_Print_Job_TestPrintQueueItem extends AbstractPrintJobCreate { private int p_C_Printing_Queue_ID = -1; @Override protected void prepare() { if (I_C_Printing_Queue.Table_Name.equals(getTableName())) { p_C_Printing_Queue_ID = getRecord_ID(); } else { throw new AdempiereException("@NotSupported@ @TableName@: " + getTableName()); } Check.assume(p_C_Printing_Queue_ID > 0, "C_Printing_Queue_ID specified"); } @Override protected List<IPrintingQueueSource> createPrintingQueueSources(final Properties ctxToUse) { // out of transaction because methods which are polling the printing queue are working out of transaction final String trxName = ITrx.TRXNAME_None; final I_C_Printing_Queue item = InterfaceWrapperHelper.create(ctxToUse, p_C_Printing_Queue_ID, I_C_Printing_Queue.class, trxName);
Check.assumeNotNull(item, "C_Printing_Queue for {} exists", p_C_Printing_Queue_ID); final UserId adUserToPrintId = Env.getLoggedUserId(ctxToUse); // logged in user final SingletonPrintingQueueSource queue = new SingletonPrintingQueueSource(item, adUserToPrintId); // 04015 : This is a test process. We shall not mark the item as printed queue.setPersistPrintedFlag(false); return ImmutableList.<IPrintingQueueSource> of(queue); } @Override protected int createSelection() { throw new IllegalStateException("Method createSelection() shall never been called because we provided an IPrintingQueueSource"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Print_Job_TestPrintQueueItem.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_PrintFont[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Print Font. @param AD_PrintFont_ID Maintain Print Font */ public void setAD_PrintFont_ID (int AD_PrintFont_ID) { if (AD_PrintFont_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PrintFont_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PrintFont_ID, Integer.valueOf(AD_PrintFont_ID)); } /** Get Print Font. @return Maintain Print Font */ public int getAD_PrintFont_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintFont_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation code. @param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); } /** Set Default.
@param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set 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_AD_PrintFont.java
1
请完成以下Java代码
public void setEndToEndId(String value) { this.endToEndId = value; } /** * Gets the value of the txId property. * * @return * possible object is * {@link String } * */ public String getTxId() { return txId; } /** * Sets the value of the txId property. * * @param value * allowed object is * {@link String } * */ public void setTxId(String value) { this.txId = value; } /** * Gets the value of the mndtId property. * * @return * possible object is * {@link String } * */ public String getMndtId() { return mndtId; } /** * Sets the value of the mndtId property. * * @param value * allowed object is * {@link String } * */ public void setMndtId(String value) { this.mndtId = value; } /** * Gets the value of the chqNb property. * * @return * possible object is * {@link String } * */ public String getChqNb() { return chqNb; } /** * Sets the value of the chqNb property. * * @param value * allowed object is * {@link String } * */ public void setChqNb(String value) { this.chqNb = value; } /**
* Gets the value of the clrSysRef property. * * @return * possible object is * {@link String } * */ public String getClrSysRef() { return clrSysRef; } /** * Sets the value of the clrSysRef property. * * @param value * allowed object is * {@link String } * */ public void setClrSysRef(String value) { this.clrSysRef = value; } /** * Gets the value of the prtry property. * * @return * possible object is * {@link ProprietaryReference1 } * */ public ProprietaryReference1 getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link ProprietaryReference1 } * */ public void setPrtry(ProprietaryReference1 value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionReferences2.java
1
请完成以下Java代码
public ModelQuery modelTenantIdLike(String tenantIdLike) { if (tenantIdLike == null) { throw new ActivitiIllegalArgumentException("Model tenant id is null"); } this.tenantIdLike = tenantIdLike; return this; } public ModelQuery modelWithoutTenantId() { this.withoutTenantId = true; return this; } // sorting //////////////////////////////////////////// public ModelQuery orderByModelCategory() { return orderBy(ModelQueryProperty.MODEL_CATEGORY); } public ModelQuery orderByModelId() { return orderBy(ModelQueryProperty.MODEL_ID); } public ModelQuery orderByModelKey() { return orderBy(ModelQueryProperty.MODEL_KEY); } public ModelQuery orderByModelVersion() { return orderBy(ModelQueryProperty.MODEL_VERSION); } public ModelQuery orderByModelName() { return orderBy(ModelQueryProperty.MODEL_NAME); } public ModelQuery orderByCreateTime() { return orderBy(ModelQueryProperty.MODEL_CREATE_TIME); } public ModelQuery orderByLastUpdateTime() { return orderBy(ModelQueryProperty.MODEL_LAST_UPDATE_TIME); } public ModelQuery orderByTenantId() { return orderBy(ModelQueryProperty.MODEL_TENANT_ID); } // results //////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getModelEntityManager().findModelCountByQueryCriteria(this); } public List<Model> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getModelEntityManager().findModelsByQueryCriteria(this, page); } // getters //////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public Integer getVersion() { return version; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; }
public String getCategoryNotEquals() { return categoryNotEquals; } public static long getSerialversionuid() { return serialVersionUID; } public String getKey() { return key; } public boolean isLatest() { return latest; } public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed; } public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ModelQueryImpl.java
1
请完成以下Java代码
public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID) { if (M_HU_PackingMaterial_ID < 1) set_Value (COLUMNNAME_M_HU_PackingMaterial_ID, null); else set_Value (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID); } @Override public int getM_HU_PackingMaterial_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID); } @Override public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID) { if (M_HU_PI_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID); } @Override public int getM_HU_PI_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI_Version getM_HU_PI_Version() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class); } @Override public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version); }
@Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Item.java
1
请完成以下Java代码
protected List<String[]> convertToSequence(Sentence sentence) { List<Word> wordList = sentence.toSimpleWordList(); List<String[]> xyList = new ArrayList<String[]>(wordList.size()); for (Word word : wordList) { xyList.add(new String[]{word.getValue(), word.getLabel()}); } return xyList; } @Override protected TagSet getTagSet() { return tagSet; } @Override public String[] tag(String... words) { int[] obsArray = new int[words.length]; for (int i = 0; i < obsArray.length; i++) { obsArray[i] = vocabulary.idOf(words[i]); } int[] tagArray = new int[obsArray.length];
model.predict(obsArray, tagArray); String[] tags = new String[obsArray.length]; for (int i = 0; i < tagArray.length; i++) { tags[i] = tagSet.stringOf(tagArray[i]); } return tags; } @Override public String[] tag(List<String> wordList) { return tag(wordList.toArray(new String[0])); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMPOSTagger.java
1
请完成以下Java代码
public int getImpex_ConnectorParam_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Impex_ConnectorParam_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()); } /** Set Parameter-Name. @param ParamName Parameter-Name */ public void setParamName (String ParamName) { set_Value (COLUMNNAME_ParamName, ParamName); } /** Get Parameter-Name. @return Parameter-Name */ public String getParamName () { return (String)get_Value(COLUMNNAME_ParamName); } /** Set Parameterwert. @param ParamValue Parameterwert */ public void setParamValue (String ParamValue)
{ set_Value (COLUMNNAME_ParamValue, ParamValue); } /** Get Parameterwert. @return Parameterwert */ public String getParamValue () { return (String)get_Value(COLUMNNAME_ParamValue); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_Impex_ConnectorParam.java
1
请在Spring Boot框架中完成以下Java代码
public static Map<String, Map<String, Object>> toMap() { BusCategoryEnum[] ary = BusCategoryEnum.values(); Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>(); for (int num = 0; num < ary.length; num++) { Map<String, Object> map = new HashMap<String, Object>(); String key = ary[num].name(); map.put("desc", ary[num].getDesc()); enumMap.put(key, map); } return enumMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList() { BusCategoryEnum[] ary = BusCategoryEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("name", ary[i].name()); map.put("desc", ary[i].getDesc()); map.put("minAmount", ary[i].getMinAmount()); map.put("maxAmount", ary[i].getMaxAmount()); map.put("beginTime", ary[i].getBeginTime()); map.put("endTime", ary[i].getEndTime()); list.add(map); } return list; }
/** * 取枚举的json字符串 * * @return */ public static String getJsonStr() { BusCategoryEnum[] enums = BusCategoryEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (BusCategoryEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\BusCategoryEnum.java
2
请完成以下Java代码
public class EntityFieldsData { private static final ObjectMapper mapper = new ObjectMapper(); static { SimpleModule entityFieldsModule = new SimpleModule("EntityFieldsModule", new Version(1, 0, 0, null, null, null)); entityFieldsModule.addSerializer(EntityId.class, new EntityIdFieldSerializer()); mapper.disable(MapperFeature.USE_ANNOTATIONS); mapper.registerModule(entityFieldsModule); } private ObjectNode fieldsData; public EntityFieldsData(BaseData data) { fieldsData = mapper.valueToTree(data); } public String getFieldValue(String field) { return getFieldValue(field, false); } public String getFieldValue(String field, boolean ignoreNullStrings) { String[] fieldsTree = field.split("\\."); JsonNode current = fieldsData; for (String key : fieldsTree) { if (current.has(key)) { current = current.get(key); } else { current = null; break; }
} if (current == null) { return null; } if (current.isNull() && ignoreNullStrings) { return null; } if (current.isValueNode()) { String textValue = current.asText(); if (StringUtils.isEmpty(textValue) && ignoreNullStrings) { return null; } return textValue; } try { return mapper.writeValueAsString(current); } catch (JsonProcessingException e) { return null; } } private static class EntityIdFieldSerializer extends JsonSerializer<EntityId> { @Override public void serialize(EntityId value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeObject(value.getId()); } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\EntityFieldsData.java
1
请完成以下Java代码
public void refresh() { final int M_Product_ID = getM_Product_ID(); final int M_Warehouse_ID = getM_Warehouse_ID(); final int M_PriceList_Version_ID = getM_PriceList_Version_ID(); final int M_AttributeSetInstance_ID = getM_AttributeSetInstance_ID(); final boolean onlyIfStale = false; refresh(onlyIfStale, M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID); } /** * Refresh only if stale */ private void refreshIfStale() { final int M_Product_ID = getM_Product_ID(); final int M_Warehouse_ID = getM_Warehouse_ID(); final int M_PriceList_Version_ID = getM_PriceList_Version_ID(); final int M_AttributeSetInstance_ID = getM_AttributeSetInstance_ID(); final boolean onlyIfStale = true; refresh(onlyIfStale, M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID); }
private void refresh(boolean onlyIfStale, int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID) { final ArrayKey refreshKey = Util.mkKey(M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID); if (!onlyIfStale || !isStale(refreshKey)) { detail.refresh(M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID); } this.refreshKeyLast = refreshKey; } private boolean isStale(final ArrayKey refreshKey) { return !Check.equals(refreshKey, refreshKeyLast); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductDetails.java
1
请完成以下Java代码
public static String convertByteArrayToString(byte[] a) { StringBuilder out = new StringBuilder(); for (byte b : a) { out.append(String.format("%02X", b)); } return out.toString(); } public static String convertTimestampToUtcString(long timestampInMillis) { String dateFormat = "yyyy-MM-dd HH:mm:ss"; String utcZone = "UTC"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); simpleDateFormat.setTimeZone(TimeZone.getTimeZone(utcZone)); return String.format("%s UTC", simpleDateFormat.format(new Date(timestampInMillis))); } public static JsonObject setDefaultMeasurements(String serialNumber, boolean batteryStatus, long measurementPeriod, long nextTransmissionAtMillis, long signal, long startTimestampMillis) { JsonObject values = new JsonObject(); values.addProperty("serial", serialNumber);
values.addProperty("battery", batteryStatus ? "ok" : "low"); values.addProperty("measured_at", convertTimestampToUtcString(startTimestampMillis)); values.addProperty("next_transmission_at", convertTimestampToUtcString(nextTransmissionAtMillis)); values.addProperty("signal", signal); values.addProperty("measurement_interval", measurementPeriod); return values; } public static boolean isBinarySensor(MeasurementType type) { return type == MEASUREMENT_TYPE_OK_ALARM || type == MEASUREMENT_TYPE_FLOODING || type == MEASUREMENT_TYPE_OUTPUT_CONTROL; } public static boolean isSensorError(int sampleOffset) { return sampleOffset >= 8355840 && sampleOffset <= 8388607; } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\efento\utils\CoapEfentoUtils.java
1
请完成以下Java代码
public Set<Class<?>> getJDKFunctinalInterfaces() { Reflections reflections = new Reflections("java.util.function"); Set<Class<?>> typesSet = reflections.getTypesAnnotatedWith(FunctionalInterface.class); return typesSet; } public Set<Method> getDateDeprecatedMethods() { Reflections reflections = new Reflections(Date.class, new MethodAnnotationsScanner()); Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class); return deprecatedMethodsSet; } @SuppressWarnings("rawtypes") public Set<Constructor> getDateDeprecatedConstructors() { Reflections reflections = new Reflections(Date.class, new MethodAnnotationsScanner()); Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class); return constructorsSet; } public Set<Method> getMethodsWithDateParam() { Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner()); Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class); return methodsSet; }
public Set<Method> getMethodsWithVoidReturn() { Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner()); Set<Method> methodsSet = reflections.getMethodsReturn(void.class); return methodsSet; } public Set<String> getPomXmlPaths() { Reflections reflections = new Reflections(new ResourcesScanner()); Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml")); return resourcesSet; } public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() { Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections")) .setScanners(new SubTypesScanner())); Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class); return scannersSet; } }
repos\tutorials-master\libraries-jdk8\src\main\java\reflections\ReflectionsApp.java
1
请完成以下Java代码
public TbQueueConsumer<TbProtoQueueMsg<ToVersionControlServiceMsg>> createToVersionControlMsgConsumer() { TbKafkaConsumerTemplate.TbKafkaConsumerTemplateBuilder<TbProtoQueueMsg<ToVersionControlServiceMsg>> consumerBuilder = TbKafkaConsumerTemplate.builder(); consumerBuilder.settings(kafkaSettings); consumerBuilder.topic(topicService.buildTopicName(vcSettings.getTopic())); consumerBuilder.clientId("tb-vc-consumer-" + serviceInfoProvider.getServiceId()); consumerBuilder.groupId(topicService.buildTopicName("tb-vc-node")); consumerBuilder.decoder(msg -> new TbProtoQueueMsg<>(msg.getKey(), ToVersionControlServiceMsg.parseFrom(msg.getData()), msg.getHeaders())); consumerBuilder.admin(vcAdmin); consumerBuilder.statsService(consumerStatsService); return consumerBuilder.build(); } @Override public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> createToUsageStatsServiceMsgProducer() { TbKafkaProducerTemplate.TbKafkaProducerTemplateBuilder<TbProtoQueueMsg<ToUsageStatsServiceMsg>> requestBuilder = TbKafkaProducerTemplate.builder(); requestBuilder.settings(kafkaSettings); requestBuilder.clientId("tb-vc-us-producer-" + serviceInfoProvider.getServiceId()); requestBuilder.defaultTopic(topicService.buildTopicName(coreSettings.getUsageStatsTopic())); requestBuilder.admin(coreAdmin); return requestBuilder.build(); } @Override public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> createHousekeeperMsgProducer() { return TbKafkaProducerTemplate.<TbProtoQueueMsg<ToHousekeeperServiceMsg>>builder() .settings(kafkaSettings) .clientId("tb-vc-housekeeper-producer-" + serviceInfoProvider.getServiceId())
.defaultTopic(topicService.buildTopicName(coreSettings.getHousekeeperTopic())) .admin(housekeeperAdmin) .build(); } @PreDestroy private void destroy() { if (coreAdmin != null) { coreAdmin.destroy(); } if (vcAdmin != null) { vcAdmin.destroy(); } if (notificationAdmin != null) { notificationAdmin.destroy(); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\KafkaTbVersionControlQueueFactory.java
1