instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected void onCurrentItemChanged(MTreeNode node) { // nothing at this level. To be overridden by extending class. } /** * Menu tree node as {@link ResultItem}. */ private static final class MenuResultItem extends ResultItemWrapper<MTreeNode> { public MenuResultItem(final MTreeNode node) { super(node); } @Override public String getText() { return getValue().getName(); } public Icon getIcon() { final String iconName = getValue().getIconName(); return Images.getImageIcon2(iconName); } } /** * Source of {@link MenuResultItem}s. */ private static final class MenuResultItemSource implements org.compiere.swing.autocomplete.ResultItemSource { public static MenuResultItemSource forRootNode(final MTreeNode root) { final Enumeration<?> nodesEnum = root.preorderEnumeration(); final List<MenuResultItem> items = new ArrayList<>(); while (nodesEnum.hasMoreElements()) { final MTreeNode node = (MTreeNode)nodesEnum.nextElement(); if (node == root) { continue; } if (node.isSummary()) { continue; } final MenuResultItem item = new MenuResultItem(node); items.add(item); } return new MenuResultItemSource(items); } private final ImmutableList<MenuResultItem> items; private MenuResultItemSource(final List<MenuResultItem> items) { super(); this.items = ImmutableList.copyOf(items); } @Override
public List<MenuResultItem> query(final String searchText, final int limit) { return items; } } /** * {@link MenuResultItem} renderer. */ private static final class ResultItemRenderer implements ListCellRenderer<ResultItem> { private final DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer(); @Override public Component getListCellRendererComponent(final JList<? extends ResultItem> list, final ResultItem value, final int index, final boolean isSelected, final boolean cellHasFocus) { final String valueAsText; final Icon icon; boolean enabled = true; if (value == null) { // shall not happen valueAsText = ""; icon = null; } else if (value == MORE_Marker) { valueAsText = "..."; icon = null; enabled = false; } else if (value instanceof MenuResultItem) { final MenuResultItem menuItem = (MenuResultItem)value; valueAsText = menuItem.getText(); icon = menuItem.getIcon(); } else { valueAsText = value.toString(); icon = null; } defaultRenderer.getListCellRendererComponent(list, valueAsText, index, isSelected, cellHasFocus); defaultRenderer.setIcon(icon); defaultRenderer.setEnabled(enabled); return defaultRenderer; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\TreeSearchAutoCompleter.java
1
请完成以下Java代码
public class SpringExpressionManager extends JuelExpressionManager { protected ApplicationContext applicationContext; /** * @param applicationContext * the applicationContext to use. Ignored when 'beans' parameter is * not null. * @param beans * a map of custom beans to expose. If null, all beans in the * application-context will be exposed. */ public SpringExpressionManager(ApplicationContext applicationContext, Map<Object, Object> beans) { super(beans); this.applicationContext = applicationContext; } /** * @param applicationContext * the applicationContext to use. * @see #SpringExpressionManager(ApplicationContext, Map) */ public SpringExpressionManager(ApplicationContext applicationContext) { this(applicationContext, null); } @Override protected ELResolver createElResolver() { CompositeELResolver compositeElResolver = new CompositeELResolver(); compositeElResolver.add(new VariableScopeElResolver()); compositeElResolver.add(new VariableContextElResolver()); compositeElResolver.add(new MockElResolver()); if(beans != null) {
// Only expose limited set of beans in expressions compositeElResolver.add(new ReadOnlyMapELResolver(beans)); } else { // Expose full application-context in expressions compositeElResolver.add(new ApplicationContextElResolver(applicationContext)); } compositeElResolver.add(new ArrayELResolver()); compositeElResolver.add(new ListELResolver()); compositeElResolver.add(new MapELResolver()); compositeElResolver.add(new BeanELResolver()); return compositeElResolver; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringExpressionManager.java
1
请完成以下Java代码
public double getWidth (boolean orientationCorrected) { if (orientationCorrected && m_landscape) return super.getHeight(); return super.getWidth(); } /** * Get Height in 1/72 inch * @param orientationCorrected correct for orientation * @return height */ public double getHeight (boolean orientationCorrected) { if (orientationCorrected && m_landscape) return super.getWidth(); return super.getHeight(); } /** * Get Image Y in 1/72 inch * @param orientationCorrected correct for orientation * @return imagable Y */ public double getImageableY (boolean orientationCorrected) { if (orientationCorrected && m_landscape) return super.getImageableX(); return super.getImageableY(); } /** * Get Image X in 1/72 inch * @param orientationCorrected correct for orientation * @return imagable X */ public double getImageableX (boolean orientationCorrected) { if (orientationCorrected && m_landscape) return super.getImageableY(); return super.getImageableX(); } /** * Get Image Height in 1/72 inch * @param orientationCorrected correct for orientation * @return imagable height
*/ public double getImageableHeight (boolean orientationCorrected) { if (orientationCorrected && m_landscape) return super.getImageableWidth(); return super.getImageableHeight(); } /** * Get Image Width in 1/72 inch * @param orientationCorrected correct for orientation * @return imagable width */ public double getImageableWidth (boolean orientationCorrected) { if (orientationCorrected && m_landscape) return super.getImageableHeight(); return super.getImageableWidth(); } /** * Get Margin * @param orientationCorrected correct for orientation * @return margin */ public Insets getMargin (boolean orientationCorrected) { return new Insets ((int)getImageableY(orientationCorrected), // top (int)getImageableX(orientationCorrected), // left (int)(getHeight(orientationCorrected)-getImageableY(orientationCorrected)-getImageableHeight(orientationCorrected)), // bottom (int)(getWidth(orientationCorrected)-getImageableX(orientationCorrected)-getImageableWidth(orientationCorrected))); // right } // getMargin } // CPapaer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\CPaper.java
1
请完成以下Java代码
public class LockFailedException extends LockException { private static final long serialVersionUID = -343950791566871398L; public static LockFailedException wrapIfNeeded(final Exception e) { if (e instanceof LockFailedException) { return (LockFailedException)e; } else { return new LockFailedException("Lock failed: " + e.getLocalizedMessage(), e); } } public LockFailedException(final String message) { super(message); } public LockFailedException(final String message, final Throwable cause) { super(message, cause); } public LockFailedException setLockCommand(final ILockCommand lockCommand) { setParameter("Lock command", lockCommand); return this; } @Override public LockFailedException setSql(final String sql, final Object[] sqlParams) {
super.setSql(sql, sqlParams); return this; } public LockFailedException setRecordToLock(final TableRecordReference recordToLock) { super.setRecord(recordToLock); return this; } public LockFailedException setExistingLocks(@NonNull final ImmutableList<ExistingLockInfo> existingLocks) { super.setExistingLocks(existingLocks); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\exceptions\LockFailedException.java
1
请完成以下Java代码
public Collection<Integer> getC_InvoiceCandidate_InOutLine_IDs() { return iciolIds; } @Override public void negateAmounts() { setQtysToInvoice(getQtysToInvoice().negate()); setNetLineAmt(getNetLineAmt().negate()); } @Override public int getC_Activity_ID() { return activityID; } @Override public void setC_Activity_ID(final int activityID) { this.activityID = activityID; } @Override public Tax getC_Tax() { return tax; } @Override public void setC_Tax(final Tax tax) { this.tax = tax; } @Override public boolean isPrinted() { return printed; } @Override public void setPrinted(final boolean printed) { this.printed = printed; } @Override public int getLineNo() { return lineNo; }
@Override public void setLineNo(final int lineNo) { this.lineNo = lineNo; } @Override public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes) { this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes); } @Override public List<IInvoiceLineAttribute> getInvoiceLineAttributes() { return invoiceLineAttributes; } @Override public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate() { return iciolsToUpdate; } @Override public int getC_PaymentTerm_ID() { return C_PaymentTerm_ID; } @Override public void setC_PaymentTerm_ID(final int paymentTermId) { C_PaymentTerm_ID = paymentTermId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java
1
请完成以下Java代码
public void setSAP_GLJournal_ID (final int SAP_GLJournal_ID) { if (SAP_GLJournal_ID < 1) set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, null); else set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, SAP_GLJournal_ID); } @Override public int getSAP_GLJournal_ID() { return get_ValueAsInt(COLUMNNAME_SAP_GLJournal_ID); } @Override public void setSAP_GLJournalLine_ID (final int SAP_GLJournalLine_ID) { if (SAP_GLJournalLine_ID < 1) set_ValueNoCheck (COLUMNNAME_SAP_GLJournalLine_ID, null); else set_ValueNoCheck (COLUMNNAME_SAP_GLJournalLine_ID, SAP_GLJournalLine_ID); } @Override public int getSAP_GLJournalLine_ID() { return get_ValueAsInt(COLUMNNAME_SAP_GLJournalLine_ID); } @Override public void setUserElementString1 (final @Nullable java.lang.String UserElementString1) { set_Value (COLUMNNAME_UserElementString1, UserElementString1); } @Override public java.lang.String getUserElementString1() { return get_ValueAsString(COLUMNNAME_UserElementString1); } @Override public void setUserElementString2 (final @Nullable java.lang.String UserElementString2) { set_Value (COLUMNNAME_UserElementString2, UserElementString2); } @Override public java.lang.String getUserElementString2() { return get_ValueAsString(COLUMNNAME_UserElementString2); } @Override public void setUserElementString3 (final @Nullable java.lang.String UserElementString3) { set_Value (COLUMNNAME_UserElementString3, UserElementString3); } @Override public java.lang.String getUserElementString3() { return get_ValueAsString(COLUMNNAME_UserElementString3); } @Override public void setUserElementString4 (final @Nullable java.lang.String UserElementString4) { set_Value (COLUMNNAME_UserElementString4, UserElementString4); } @Override
public java.lang.String getUserElementString4() { return get_ValueAsString(COLUMNNAME_UserElementString4); } @Override public void setUserElementString5 (final @Nullable java.lang.String UserElementString5) { set_Value (COLUMNNAME_UserElementString5, UserElementString5); } @Override public java.lang.String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5); } @Override public void setUserElementString6 (final @Nullable java.lang.String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public java.lang.String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable java.lang.String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public java.lang.String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournalLine.java
1
请完成以下Java代码
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception { //1. code is required String code = params.getFirst("code"); if (code == null || "".equals(code)) { throw new WebApplicationException("invalid_grant"); } AuthorizationCode authorizationCode = entityManager.find(AuthorizationCode.class, code); if (!authorizationCode.getExpirationDate().isAfter(LocalDateTime.now())) { throw new WebApplicationException("code Expired !"); } String redirectUri = params.getFirst("redirect_uri"); //redirecturi match if (authorizationCode.getRedirectUri() != null && !authorizationCode.getRedirectUri().equals(redirectUri)) { //redirectUri params should be the same as the requested redirectUri. throw new WebApplicationException("invalid_grant"); } //client match
if (!clientId.equals(authorizationCode.getClientId())) { throw new WebApplicationException("invalid_grant"); } //3. JWT Payload or claims String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes()); String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes()); return Json.createObjectBuilder() .add("token_type", "Bearer") .add("access_token", accessToken) .add("expires_in", expiresInMin * 60) .add("scope", authorizationCode.getApprovedScopes()) .add("refresh_token", refreshToken) .build(); } }
repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-authorization-server\src\main\java\com\baeldung\oauth2\authorization\server\handler\AuthorizationCodeGrantTypeHandler.java
1
请在Spring Boot框架中完成以下Java代码
class WebMvcConfig implements WebMvcConfigurer { private final WebProperties webProperties; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("favicon.ico") .addResourceLocations(this.webProperties.getResources().getStaticLocations()); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeInterceptor()); } public HandlerInterceptor localeInterceptor() { LocaleChangeInterceptor localeInt = new LocaleChangeInterceptor(); localeInt.setParamName("lang"); return localeInt; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.US); return slr; }
@Bean public PageableHandlerMethodArgumentResolverCustomizer paginationCustomizer() { return new PaginationCustomizer(); } @Bean public FilterRegistrationBean<ReqLogFilter> loggingFilter() { var registrationBean = new FilterRegistrationBean<ReqLogFilter>(); registrationBean.setFilter(new ReqLogFilter()); registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE); return registrationBean; } }
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\config\WebMvcConfig.java
2
请完成以下Java代码
private List<Object> retrieveIds(final ResultSet rs) throws SQLException { final Array sqlArray = rs.getArray(sqlValuesColumn); if (sqlArray != null) { return Stream.of((Object[])sqlArray.getArray()) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } else { return ImmutableList.of(); } } } @Builder @Value private static class ColorDocumentFieldValueLoader implements DocumentFieldValueLoader { @NonNull String sqlColumnName; @Override @Nullable public Object retrieveFieldValue( @NonNull final ResultSet rs, final boolean isDisplayColumnAvailable_NOTUSED, final String adLanguage_NOTUSED, final LookupDescriptor lookupDescriptor_NOTUSED) throws SQLException { final ColorId adColorId = ColorId.ofRepoIdOrNull(rs.getInt(sqlColumnName)); if (adColorId == null) {
return null; } final IColorRepository colorRepository = Services.get(IColorRepository.class); final MFColor color = colorRepository.getColorById(adColorId); if (color == null) { return null; } final Color awtColor = color.toFlatColor().getFlatColor(); return ColorValue.ofRGB(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\DocumentFieldValueLoaders.java
1
请完成以下Java代码
public <T extends OAuth2Token> T getAccessToken() { return (T) this.accessToken; } /** * Returns a new {@link Builder}, initialized with the DPoP Proof {@link Jwt}. * @param dPoPProof the DPoP Proof {@link Jwt} * @return the {@link Builder} */ public static Builder withDPoPProof(String dPoPProof) { return new Builder(dPoPProof); } /** * A builder for {@link DPoPProofContext}. */ public static final class Builder { private String dPoPProof; private String method; private String targetUri; private OAuth2Token accessToken; private Builder(String dPoPProof) { Assert.hasText(dPoPProof, "dPoPProof cannot be empty"); this.dPoPProof = dPoPProof; } /** * Sets the value of the HTTP method of the request to which the DPoP Proof * {@link Jwt} is attached. * @param method the value of the HTTP method of the request to which the DPoP * Proof {@link Jwt} is attached * @return the {@link Builder} */ public Builder method(String method) { this.method = method; return this; } /** * Sets the value of the HTTP target URI of the request to which the DPoP Proof * {@link Jwt} is attached, without query and fragment parts. * @param targetUri the value of the HTTP target URI of the request to which the * DPoP Proof {@link Jwt} is attached * @return the {@link Builder}
*/ public Builder targetUri(String targetUri) { this.targetUri = targetUri; return this; } /** * Sets the access token if the request is a Protected Resource request. * @param accessToken the access token if the request is a Protected Resource * request * @return the {@link Builder} */ public Builder accessToken(OAuth2Token accessToken) { this.accessToken = accessToken; return this; } /** * Builds a new {@link DPoPProofContext}. * @return a {@link DPoPProofContext} */ public DPoPProofContext build() { validate(); return new DPoPProofContext(this.dPoPProof, this.method, this.targetUri, this.accessToken); } private void validate() { Assert.hasText(this.method, "method cannot be empty"); Assert.hasText(this.targetUri, "targetUri cannot be empty"); if (!"GET".equals(this.method) && !"HEAD".equals(this.method) && !"POST".equals(this.method) && !"PUT".equals(this.method) && !"PATCH".equals(this.method) && !"DELETE".equals(this.method) && !"OPTIONS".equals(this.method) && !"TRACE".equals(this.method)) { throw new IllegalArgumentException("method is invalid"); } URI uri; try { uri = new URI(this.targetUri); uri.toURL(); } catch (Exception ex) { throw new IllegalArgumentException("targetUri must be a valid URL", ex); } if (uri.getQuery() != null || uri.getFragment() != null) { throw new IllegalArgumentException("targetUri cannot contain query or fragment parts"); } } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\DPoPProofContext.java
1
请完成以下Java代码
public Integer getPopulation() { return population; } public void setPopulation(Integer population) { this.population = population; } public Float getLifeexpectancy() { return lifeexpectancy; } public void setLifeexpectancy(Float lifeexpectancy) { this.lifeexpectancy = lifeexpectancy; } public Float getGnp() { return gnp; } public void setGnp(Float gnp) { this.gnp = gnp; } public Float getGnpold() { return gnpold; } public void setGnpold(Float gnpold) { this.gnpold = gnpold; } public String getLocalname() { return localname; } public void setLocalname(String localname) { this.localname = localname == null ? null : localname.trim(); } public String getGovernmentform() { return governmentform; } public void setGovernmentform(String governmentform) { this.governmentform = governmentform == null ? null : governmentform.trim(); } public String getHeadofstate() {
return headofstate; } public void setHeadofstate(String headofstate) { this.headofstate = headofstate == null ? null : headofstate.trim(); } public Integer getCapital() { return capital; } public void setCapital(Integer capital) { this.capital = capital; } public String getCode2() { return code2; } public void setCode2(String code2) { this.code2 = code2 == null ? null : code2.trim(); } }
repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\Country.java
1
请完成以下Java代码
public class UserDto { private String firstName; private String lastName; private String age; private AddressDto address; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAge() { return age; }
public void setAge(String age) { this.age = age; } public AddressDto getAddress() { return address; } public void setAddress(AddressDto address) { this.address = address; } @Override public String toString() { return "User{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age='" + age + '\'' + ", address=" + address + '}'; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-5\src\main\java\com\baeldung\jsonargs\UserDto.java
1
请完成以下Java代码
public V remove(Object key) { V removedValue = super.remove(key); if (removedValue != null) { removeFromTrackingMaps(key); } return removedValue; } @Override public boolean remove(Object key, Object value) { boolean removed = super.remove(key, value); if (removed) { removeFromTrackingMaps(key); } return removed; } @Override public void clear() { super.clear(); numberToKey.clear(); keyToNumber.clear(); } public V getRandomValue() { if (this.isEmpty()) { return null; } int randomNumber = ThreadLocalRandom.current().nextInt(this.size()); K randomKey = numberToKey.get(randomNumber); return this.get(randomKey); } private void removeFromTrackingMaps(Object key) { @SuppressWarnings("unchecked") K keyToRemove = (K) key;
Integer numberToRemove = keyToNumber.get(keyToRemove); if (numberToRemove == null) { return; } int mapSize = this.size(); int lastIndex = mapSize; if (numberToRemove == lastIndex) { numberToKey.remove(numberToRemove); keyToNumber.remove(keyToRemove); } else { K lastKey = numberToKey.get(lastIndex); if (lastKey == null) { numberToKey.remove(numberToRemove); keyToNumber.remove(keyToRemove); return; } numberToKey.put(numberToRemove, lastKey); keyToNumber.put(lastKey, numberToRemove); numberToKey.remove(lastIndex); keyToNumber.remove(keyToRemove); } } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\randommapkey\RandomizedMap.java
1
请完成以下Java代码
public String circuitBreakerApi() { return externalAPICaller.callApi(); } @GetMapping("/retry") @Retry(name = "retryApi", fallbackMethod = "fallbackAfterRetry") public String retryApi() { return externalAPICaller.callApi(); } @GetMapping("/time-limiter") @TimeLimiter(name = "timeLimiterApi") public CompletableFuture<String> timeLimiterApi() { return CompletableFuture.supplyAsync(externalAPICaller::callApiWithDelay); } @GetMapping("/bulkhead") @Bulkhead(name = "bulkheadApi")
public String bulkheadApi() { return externalAPICaller.callApi(); } @GetMapping("/rate-limiter") @RateLimiter(name = "rateLimiterApi") public String rateLimitApi() { return externalAPICaller.callApi(); } public String fallbackAfterRetry(Exception ex) { return "all retries have exhausted"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\resilientapp\ResilientAppController.java
1
请在Spring Boot框架中完成以下Java代码
public class OpenRepository { public static void main(String[] args) throws IOException, GitAPIException { // first create a test-repository, the return is including the .get directory here! File repoDir = createSampleGitRepo(); // now open the resulting repository with a FileRepositoryBuilder FileRepositoryBuilder builder = new FileRepositoryBuilder(); try (Repository repository = builder.setGitDir(repoDir) .readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build()) { System.out.println("Having repository: " + repository.getDirectory()); // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) Ref head = repository.exactRef("refs/heads/master"); System.out.println("Ref of refs/heads/master: " + head); } } private static File createSampleGitRepo() throws IOException, GitAPIException { try (Repository repository = Helper.createNewRepository()) { System.out.println("Temporary repository at " + repository.getDirectory()); // create the file File myfile = new File(repository.getDirectory().getParent(), "testfile"); if(!myfile.createNewFile()) { throw new IOException("Could not create file " + myfile); } // run the add-call try (Git git = new Git(repository)) { git.add() .addFilepattern("testfile")
.call(); // and then commit the changes git.commit() .setMessage("Added testfile") .call(); } System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); return repository.getDirectory(); } } }
repos\tutorials-master\jgit\src\main\java\com\baeldung\jgit\OpenRepository.java
2
请完成以下Java代码
public void setProductGroup (final @Nullable java.lang.String ProductGroup) { throw new IllegalArgumentException ("ProductGroup is virtual column"); } @Override public java.lang.String getProductGroup() { return get_ValueAsString(COLUMNNAME_ProductGroup); } @Override public void setProductName (final @Nullable java.lang.String ProductName) { throw new IllegalArgumentException ("ProductName is virtual column"); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQtyCount (final BigDecimal QtyCount)
{ set_Value (COLUMNNAME_QtyCount, QtyCount); } @Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java
1
请在Spring Boot框架中完成以下Java代码
class ArticleCommentController implements AuthenticationAwareMixin { private final UserService userService; private final UserRelationshipService userRelationshipService; private final ArticleService articleService; private final ArticleCommentService articleCommentService; @PostMapping("/api/articles/{slug}/comments") SingleCommentResponse postComment( AuthToken commenterToken, @PathVariable String slug, @RequestBody WriteCommentRequest request) { var article = articleService.getArticle(slug); var commenter = userService.getUser(commenterToken.userId()); var comment = articleCommentService.write( new ArticleComment(article, commenter, request.comment().body())); return new SingleCommentResponse(comment); } @GetMapping("/api/articles/{slug}/comments") MultipleCommentsResponse getComment(AuthToken readersToken, @PathVariable String slug) { var article = articleService.getArticle(slug); var comments = articleCommentService.getComments(article); if (this.isAnonymousUser(readersToken)) { return new MultipleCommentsResponse( comments.stream().map(ArticleCommentResponse::new).toList()); }
var reader = userService.getUser(readersToken.userId()); return new MultipleCommentsResponse(comments.stream() .map(comment -> new ArticleCommentResponse( comment, userRelationshipService.isFollowing(reader, comment.getAuthor()))) .toList()); } @SuppressWarnings("MVCPathVariableInspection") @DeleteMapping("/api/articles/{slug}/comments/{id}") void deleteComment(AuthToken commenterToken, @PathVariable("id") int commentId) { var commenter = userService.getUser(commenterToken.userId()); var comment = articleCommentService.getComment(commentId); articleCommentService.delete(commenter, comment); } }
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\api\ArticleCommentController.java
2
请在Spring Boot框架中完成以下Java代码
public DataSize getMaxInMemorySize() { return this.maxInMemorySize; } public void setMaxInMemorySize(DataSize maxInMemorySize) { this.maxInMemorySize = maxInMemorySize; } public DataSize getMaxHeadersSize() { return this.maxHeadersSize; } public void setMaxHeadersSize(DataSize maxHeadersSize) { this.maxHeadersSize = maxHeadersSize; } public DataSize getMaxDiskUsagePerPart() { return this.maxDiskUsagePerPart; } public void setMaxDiskUsagePerPart(DataSize maxDiskUsagePerPart) { this.maxDiskUsagePerPart = maxDiskUsagePerPart; } public Integer getMaxParts() { return this.maxParts; } public void setMaxParts(Integer maxParts) { this.maxParts = maxParts; } public @Nullable String getFileStorageDirectory() {
return this.fileStorageDirectory; } public void setFileStorageDirectory(@Nullable String fileStorageDirectory) { this.fileStorageDirectory = fileStorageDirectory; } public Charset getHeadersCharset() { return this.headersCharset; } public void setHeadersCharset(Charset headersCharset) { this.headersCharset = headersCharset; } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\ReactiveMultipartProperties.java
2
请完成以下Java代码
public class ToArrayBenchmark { @Param({ "10", "10000", "10000000" }) private int size; @Param({ "array-list", "tree-set" }) private String type; private Collection<String> collection; @Setup public void setup() { switch (type) { case "array-list": collection = new ArrayList<String>(); break; case "tree-set": collection = new TreeSet<String>(); break; default: throw new UnsupportedOperationException(); } for (int i = 0; i < size; i++) { collection.add(String.valueOf(i));
} } @Benchmark public String[] zero_sized() { return collection.toArray(new String[0]); } @Benchmark public String[] pre_sized() { return collection.toArray(new String[collection.size()]); } public static void main(String[] args) { try { org.openjdk.jmh.Main.main(args); } catch (IOException e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\toarraycomparison\ToArrayBenchmark.java
1
请完成以下Java代码
public List<ActivityImpl> getInitialActivityStack() { return getInitialActivityStack(initial); } public synchronized List<ActivityImpl> getInitialActivityStack(ActivityImpl startActivity) { List<ActivityImpl> initialActivityStack = initialActivityStacks.get(startActivity); if (initialActivityStack == null) { initialActivityStack = new ArrayList<>(); ActivityImpl activity = startActivity; while (activity != null) { initialActivityStack.add(0, activity); activity = activity.getParentActivity(); } initialActivityStacks.put(startActivity, initialActivityStack); } return initialActivityStack; } protected InterpretableExecution newProcessInstance(ActivityImpl startActivity) { return new ExecutionImpl(startActivity); } @Override public String getDiagramResourceName() { return null; } @Override public String getDeploymentId() { return null; } public void addLaneSet(LaneSet newLaneSet) { getLaneSets().add(newLaneSet); } public Lane getLaneForId(String id) { if (laneSets != null && !laneSets.isEmpty()) { Lane lane; for (LaneSet set : laneSets) { lane = set.getLaneForId(id); if (lane != null) { return lane; } } } return null; } // getters and setters ////////////////////////////////////////////////////// @Override public ActivityImpl getInitial() { return initial; } public void setInitial(ActivityImpl initial) { this.initial = initial; } @Override public String toString() { return "ProcessDefinition(" + id + ")";
} @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Override public String getDescription() { return (String) getProperty("documentation"); } /** * @return all lane-sets defined on this process-instance. Returns an empty list if none are defined. */ public List<LaneSet> getLaneSets() { if (laneSets == null) { laneSets = new ArrayList<>(); } return laneSets; } public void setParticipantProcess(ParticipantProcess participantProcess) { this.participantProcess = participantProcess; } public ParticipantProcess getParticipantProcess() { return participantProcess; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ProcessDefinitionImpl.java
1
请完成以下Java代码
public class ResultExporter { public static void exportResult(String titleStr, Collection<RunResult> results, String paramKey, String xunit) throws Exception { // 几个测试对象 List<String> objects = new ArrayList<>(); // 测试维度,输入值n List<String> dimensions = new ArrayList<>(); // 有几个测试对象,就有几组测试数据,每组测试数据中对应几个维度的结果 List<List<Double>> allData = new ArrayList<>(); List<Double> temp = new ArrayList<>(); for (RunResult runResult : results) { BenchmarkResult benchmarkResult = runResult.getAggregatedResult(); Result r = benchmarkResult.getPrimaryResult(); BenchmarkParams params = runResult.getParams(); if (!objects.contains(r.getLabel())) { objects.add(r.getLabel()); if (!temp.isEmpty()) { allData.add(temp); temp = new ArrayList<>(); }
} temp.add(Double.parseDouble(String.format("%.2f", r.getScore()))); // 测试维度 if (!dimensions.contains("n=" + params.getParam(paramKey))) { dimensions.add("n=" + params.getParam(paramKey)); } } // 最后一组测试数据别忘记加进去了 allData.add(temp); String optionStr = generateOption(titleStr, objects, dimensions, allData, xunit); // POST到接口上 postOption(optionStr, "http://localhost:9075/api/v1/data"); } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\common\ResultExporter.java
1
请完成以下Java代码
public class DBRes_hu extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][]{ { "CConnectionDialog", "Szerver kapcsolat" }, { "Name", "Név" }, { "AppsHost", "Alkalmazás szerver" }, { "AppsPort", "Alkalmazás port" }, { "TestApps", "Teszt alkalmazás szerver" }, { "DBHost", "Adatbázis szerver" }, { "DBPort", "Adatbázis port" }, { "DBName", "Adatbázis név" }, { "DBUidPwd", "Felhasználó / Jelszó" }, { "ViaFirewall", "Firewallon keresztül" }, { "FWHost", "Firewall cím" }, { "FWPort", "Firewall port" }, { "TestConnection", "Test Adatbázis" }, { "Type", "Adatbázis típus" }, { "BequeathConnection", "Kapcsolat hagyományozása" }, { "Overwrite", "Felülír" }, { "ConnectionProfile", "Kapcsolat profil" }, { "LAN", "LAN" },
{ "TerminalServer", "Terminál szerver" }, { "VPN", "VPN" }, { "WAN", "WAN" }, { "ConnectionError", "Kapcsolat hiba" }, { "ServerNotActive", "Szerver nem aktív" } }; /** * Get Contsnts * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_hu.java
1
请完成以下Java代码
public void setQtyInvoicedInPriceUOM_AndLineNetAMT(final I_C_InvoiceLine invoiceLine) { if (invoiceLine == null) { // nothing to do return; } final IInvoiceLineBL invoiceLineBL = Services.get(IInvoiceLineBL.class); final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); invoiceLineBL.setQtyInvoicedInPriceUOM(invoiceLine); invoiceBL.setLineNetAmt(invoiceLine); } /** * update prices on ASI change */ @CalloutMethod(columnNames = { I_C_InvoiceLine.COLUMNNAME_M_AttributeSetInstance_ID }) public void onASIorDiscountChange(final I_C_InvoiceLine invoiceLine, final ICalloutField field) { Services.get(IInvoiceLineBL.class).updatePrices(invoiceLine); } /** * Recalculate priceActual on discount or priceEntered change. * Don't invoice the pricing engine. */ @CalloutMethod(columnNames = { I_C_InvoiceLine.COLUMNNAME_PriceEntered, I_C_InvoiceLine.COLUMNNAME_Discount }) public void recomputePriceActual(final I_C_InvoiceLine invoiceLine, final ICalloutField field) { final CurrencyPrecision pricePrecision = extractPrecision(invoiceLine); if (pricePrecision == null) { return; } InvoiceLinePriceAndDiscount.of(invoiceLine, pricePrecision) .withUpdatedPriceActual() .applyTo(invoiceLine); } @Nullable private CurrencyPrecision extractPrecision(@NonNull final I_C_InvoiceLine invoiceLine) { final IPriceListBL priceListBL = Services.get(IPriceListBL.class); if (invoiceLine.getC_Invoice_ID() <= 0) { return null; } final I_C_Invoice invoice = invoiceLine.getC_Invoice(); return priceListBL.getPricePrecision(PriceListId.ofRepoId(invoice.getM_PriceList_ID())); }
/** * Set the product as soon as the order line is set */ @CalloutMethod(columnNames = { I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID }) public void setProduct(final I_C_InvoiceLine invoiceLine, final ICalloutField field) { if (InterfaceWrapperHelper.isNull(invoiceLine, I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID)) { // set the product to null if the orderline was set to null invoiceLine.setM_Product_ID(-1); return; } final I_C_OrderLine ol = invoiceLine.getC_OrderLine(); invoiceLine.setM_Product_ID(ol.getM_Product_ID()); } @CalloutMethod(columnNames = { I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID }) public void setIsPackagingMaterial(final I_C_InvoiceLine invoiceLine, final ICalloutField field) { if (InterfaceWrapperHelper.isNull(invoiceLine, I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID)) { // in case the c_orderline_id is removed, make sure the flag is on false. The user can set it on true, manually invoiceLine.setIsPackagingMaterial(false); return; } final de.metas.interfaces.I_C_OrderLine ol = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), de.metas.interfaces.I_C_OrderLine.class); invoiceLine.setIsPackagingMaterial(ol.isPackagingMaterial()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\callout\C_InvoiceLine.java
1
请完成以下Java代码
public void manuallyStartCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).manualStart(); } public void manuallyStartCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).manualStart(); } public void disableCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).disable(); } public void disableCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).disable(); } public void reenableCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).reenable(); } public void reenableCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).reenable(); } public void completeCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).complete();
} public void completeCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).complete(); } public void closeCaseInstance(String caseInstanceId) { withCaseExecution(caseInstanceId).close(); } public void terminateCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).terminate(); } public void terminateCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).terminate(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class EntityMetaData { private boolean isJPAEntity; private Class<?> entityClass; private Method idMethod; private Field idField; public boolean isJPAEntity() { return isJPAEntity; } public void setJPAEntity(boolean isJPAEntity) { this.isJPAEntity = isJPAEntity; } public Class<?> getEntityClass() { return entityClass; } public void setEntityClass(Class<?> entityClass) { this.entityClass = entityClass; } public Method getIdMethod() { return idMethod; } public void setIdMethod(Method idMethod) { this.idMethod = idMethod; idMethod.setAccessible(true); }
public Field getIdField() { return idField; } public void setIdField(Field idField) { this.idField = idField; idField.setAccessible(true); } public Class<?> getIdType() { Class<?> idType = null; if (idField != null) { idType = idField.getType(); } else if (idMethod != null) { idType = idMethod.getReturnType(); } return idType; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\EntityMetaData.java
2
请完成以下Java代码
public static CostingDocumentRef ofCostCollectorId(final int ppCostCollectorId) { return ofCostCollectorId(PPCostCollectorId.ofRepoId(ppCostCollectorId)); } public static CostingDocumentRef ofCostCollectorId(final PPCostCollectorId ppCostCollectorId) { return new CostingDocumentRef(TABLE_NAME_PP_Cost_Collector, ppCostCollectorId, I_M_CostDetail.COLUMNNAME_PP_Cost_Collector_ID, null); } public static CostingDocumentRef ofCostRevaluationLineId(@NonNull final CostRevaluationLineId costRevaluationLineId) { return new CostingDocumentRef(TABLE_NAME_M_CostRevaluationLine, costRevaluationLineId, I_M_CostDetail.COLUMNNAME_M_CostRevaluationLine_ID, null); } String tableName; RepoIdAware id; String costDetailColumnName; Boolean outboundTrx; private CostingDocumentRef( @NonNull final String tableName, @NonNull final RepoIdAware id, @NonNull final String costDetailColumnName, @Nullable final Boolean outboundTrx) { this.tableName = tableName; this.id = id; this.costDetailColumnName = costDetailColumnName; this.outboundTrx = outboundTrx; } public boolean isTableName(final String expectedTableName) {return Objects.equals(tableName, expectedTableName);} public boolean isInventoryLine() {return isTableName(TABLE_NAME_M_InventoryLine);} public boolean isCostRevaluationLine() {return isTableName(TABLE_NAME_M_CostRevaluationLine);} public boolean isMatchInv() { return isTableName(TABLE_NAME_M_MatchInv); }
public PPCostCollectorId getCostCollectorId() { return getId(PPCostCollectorId.class); } public <T extends RepoIdAware> T getId(final Class<T> idClass) { if (idClass.isInstance(id)) { return idClass.cast(id); } else { throw new AdempiereException("Expected id to be of type " + idClass + " but it was " + id); } } public static boolean equals(CostingDocumentRef ref1, CostingDocumentRef ref2) {return Objects.equals(ref1, ref2);} public TableRecordReference toTableRecordReference() {return TableRecordReference.of(tableName, id);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostingDocumentRef.java
1
请完成以下Java代码
public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException { getDelegate().storeToXML(os, comment, encoding); } @Override public String getProperty(String key) { return getDelegate().getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames()
{ return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请完成以下Java代码
class SelectionColumnCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; public SelectionColumnCellRenderer() { super(); checkbox = new JCheckBox(); checkbox.setMargin(new Insets(0, 0, 0, 0)); checkbox.setHorizontalAlignment(SwingConstants.CENTER); } private final JCheckBox checkbox; /** * Set Value (for multi-selection) * * @param value */
@Override protected void setValue(final Object value) { final boolean selected = DisplayType.toBooleanNonNull(value, false); checkbox.setSelected(selected); } // setValue @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { setValue(value); return checkbox; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\SelectionColumnCellRenderer.java
1
请完成以下Java代码
public Set<ProductId> getProductIds() {return products.getProductIds();} public OptionalBoolean hasQtyAvailableToPick() { return products.hasQtyAvailableToPick(); } @Nullable public ProductId getProductId() { return products.getSingleProductIdOrNull(); } public ITranslatableString getProductName() {
return products.getSingleProductNameOrNull(); } @Nullable public Quantity getQtyToDeliver() { return products.getSingleQtyToDeliverOrNull(); } @Nullable public Quantity getQtyAvailableToPick() { return products.getSingleQtyAvailableToPickOrNull(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobCandidate.java
1
请完成以下Java代码
public Object[] toArray() { Collection<T> modelElementCollection = ModelUtil.getModelElementCollection(getView(modelElement), modelElement.getModelInstance()); return modelElementCollection.toArray(); } public <U> U[] toArray(U[] a) { Collection<T> modelElementCollection = ModelUtil.getModelElementCollection(getView(modelElement), modelElement.getModelInstance()); return modelElementCollection.toArray(a); } public int size() { return getView(modelElement).size(); } public boolean add(T e) { if(!isMutable) { throw new UnsupportedModelOperationException("add()", "collection is immutable"); } performAddOperation(modelElement, e); return true; } public boolean addAll(Collection<? extends T> c) { if(!isMutable) { throw new UnsupportedModelOperationException("addAll()", "collection is immutable"); } boolean result = false; for (T t : c) { result |= add(t); } return result; } public void clear() { if(!isMutable) { throw new UnsupportedModelOperationException("clear()", "collection is immutable"); } Collection<DomElement> view = getView(modelElement); performClearOperation(modelElement, view); } public boolean remove(Object e) { if(!isMutable) { throw new UnsupportedModelOperationException("remove()", "collection is immutable"); }
ModelUtil.ensureInstanceOf(e, ModelElementInstanceImpl.class); return performRemoveOperation(modelElement, e); } public boolean removeAll(Collection<?> c) { if(!isMutable) { throw new UnsupportedModelOperationException("removeAll()", "collection is immutable"); } boolean result = false; for (Object t : c) { result |= remove(t); } return result; } public boolean retainAll(Collection<?> c) { throw new UnsupportedModelOperationException("retainAll()", "not implemented"); } }; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\child\ChildElementCollectionImpl.java
1
请完成以下Java代码
public void parseSequenceFlow(Element sequenceFlowElement, ScopeImpl scopeElement, TransitionImpl transition) { addExecutionListener(transition); } @Override public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) { addExecutionListener(activity); } @Override public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl activity) { addExecutionListener(activity); } @Override public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) { addExecutionListener(activity); } @Override public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) { addExecutionListener(activity); } @Override public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) { addExecutionListener(activity); } private void addExecutionListener(final ActivityImpl activity) { if (executionListener != null) { for (String event : EXECUTION_EVENTS) { addListenerOnCoreModelElement(activity, executionListener, event); } } }
private void addExecutionListener(final TransitionImpl transition) { if (executionListener != null) { addListenerOnCoreModelElement(transition, executionListener, EVENTNAME_TAKE); } } private void addListenerOnCoreModelElement(CoreModelElement element, DelegateListener<?> listener, String event) { if (skippable) { element.addListener(event, listener); } else { element.addBuiltInListener(event, listener); } } private void addTaskListener(TaskDefinition taskDefinition) { if (taskListener != null) { for (String event : TASK_EVENTS) { if (skippable) { taskDefinition.addTaskListener(event, taskListener); } else { taskDefinition.addBuiltInTaskListener(event, taskListener); } } } } /** * Retrieves task definition. * * @param activity the taskActivity * @return taskDefinition for activity */ private TaskDefinition taskDefinition(final ActivityImpl activity) { final UserTaskActivityBehavior activityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior(); return activityBehavior.getTaskDefinition(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\PublishDelegateParseListener.java
1
请完成以下Java代码
private Map<String, Object> resolveExpressions( MappingExecutionContext mappingExecutionContext, Map<String, Object> availableVariables, Map<String, Object> outboundVariables ) { if (mappingExecutionContext.hasExecution()) { return resolveExecutionExpressions(mappingExecutionContext, availableVariables, outboundVariables); } else { return expressionResolver.resolveExpressionsMap( new SimpleMapExpressionEvaluator(availableVariables), outboundVariables ); } } private Map<String, Object> resolveExecutionExpressions( MappingExecutionContext mappingExecutionContext, Map<String, Object> availableVariables, Map<String, Object> outboundVariables ) { if (availableVariables != null && !availableVariables.isEmpty()) { return expressionResolver.resolveExpressionsMap( new CompositeVariableExpressionEvaluator( new SimpleMapExpressionEvaluator(availableVariables),
new VariableScopeExpressionEvaluator(mappingExecutionContext.getExecution()) ), outboundVariables ); } return expressionResolver.resolveExpressionsMap( new VariableScopeExpressionEvaluator(mappingExecutionContext.getExecution()), outboundVariables ); } private boolean isTargetProcessVariableDefined( Extension extensions, DelegateExecution execution, String variableName ) { return ( extensions.getPropertyByName(variableName) != null || (execution != null && execution.getVariable(variableName) != null) ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\ExtensionsVariablesMappingProvider.java
1
请完成以下Java代码
public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config, Object returnedObject) throws AccessDeniedException { if (returnedObject == null) { // AclManager interface contract prohibits nulls // As they have permission to null/nothing, grant access logger.debug("Return object is null, skipping"); return null; } if (!getProcessDomainObjectClass().isAssignableFrom(returnedObject.getClass())) { logger.debug("Return object is not applicable for this provider, skipping"); return returnedObject; } for (ConfigAttribute attr : config) { if (!this.supports(attr)) { continue; } // Need to make an access decision on this invocation if (hasPermission(authentication, returnedObject)) { return returnedObject; }
logger.debug("Denying access"); throw new AccessDeniedException(this.messages.getMessage("AclEntryAfterInvocationProvider.noPermission", new Object[] { authentication.getName(), returnedObject }, "Authentication {0} has NO permissions to the domain object {1}")); } return returnedObject; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\acls\afterinvocation\AclEntryAfterInvocationProvider.java
1
请完成以下Java代码
public class PropertyEntity implements DbEntity, HasDbRevision, Serializable { protected static final EnginePersistenceLogger LOG = ProcessEngineLogger.PERSISTENCE_LOGGER; private static final long serialVersionUID = 1L; String name; int revision; String value; public PropertyEntity() { } public PropertyEntity(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } // persistent object methods //////////////////////////////////////////////// public String getId() {
return name; } public Object getPersistentState() { return value; } public void setId(String id) { throw LOG.notAllowedIdException(id); } public int getRevisionNext() { return revision+1; } @Override public String toString() { return this.getClass().getSimpleName() + "[name=" + name + ", revision=" + revision + ", value=" + value + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\PropertyEntity.java
1
请完成以下Java代码
private final void markStorageStaled() { if (productStorage == null) { return; } productStorage.markStaled(); } @Override public final void removeAssignedHUs(final Collection<I_M_HU> husToUnassign) { final Object documentLineModel = getDocumentLineModel(); final String trxName = getTrxName(); final Set<HuId> huIdsToUnassign = husToUnassign.stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(Collectors.toSet()); huAssignmentBL.unassignHUs(documentLineModel, huIdsToUnassign, trxName); deleteAllocations(husToUnassign); // // Reset cached values assignedHUs = null; markStorageStaled(); } @Override public final void destroyAssignedHU(final I_M_HU huToDestroy) { Check.assumeNotNull(huToDestroy, "huToDestroy not null"); InterfaceWrapperHelper.setThreadInheritedTrxName(huToDestroy);
removeAssignedHUs(Collections.singleton(huToDestroy)); final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(huToDestroy); final IHUContext huContext = Services.get(IHandlingUnitsBL.class).createMutableHUContext(contextProvider); handlingUnitsBL.markDestroyed(huContext, huToDestroy); } @Override public String toString() { return "AbstractHUAllocations [contextProvider=" + contextProvider + ", documentLineModel=" + documentLineModel + ", productStorage=" + productStorage + ", assignedHUs=" + assignedHUs + ", assignedHUsTrxName=" + assignedHUsTrxName + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUAllocations.java
1
请完成以下Java代码
public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() {
return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请完成以下Java代码
public TopicSubscriptionBuilder withoutTenantId() { withoutTenantId = true; return this; } public TopicSubscriptionBuilder tenantIdIn(String... tenantIds) { ensureNotNull(tenantIds, "tenantIds"); this.tenantIds = Arrays.asList(tenantIds); return this; } public TopicSubscriptionBuilder includeExtensionProperties(boolean includeExtensionProperties) { this.includeExtensionProperties = includeExtensionProperties; return this; } public TopicSubscription open() { if (topicName == null) { throw LOG.topicNameNullException(); } if (lockDuration != null && lockDuration <= 0L) { throw LOG.lockDurationIsNotGreaterThanZeroException(lockDuration); } if (externalTaskHandler == null) { throw LOG.externalTaskHandlerNullException(); } TopicSubscriptionImpl subscription = new TopicSubscriptionImpl(topicName, lockDuration, externalTaskHandler, topicSubscriptionManager, variableNames, businessKey); if (processDefinitionId != null) { subscription.setProcessDefinitionId(processDefinitionId); } if (processDefinitionIds != null) { subscription.setProcessDefinitionIdIn(processDefinitionIds); } if (processDefinitionKey != null) {
subscription.setProcessDefinitionKey(processDefinitionKey); } if (processDefinitionKeys != null) { subscription.setProcessDefinitionKeyIn(processDefinitionKeys); } if (withoutTenantId) { subscription.setWithoutTenantId(withoutTenantId); } if (tenantIds != null) { subscription.setTenantIdIn(tenantIds); } if(processDefinitionVersionTag != null) { subscription.setProcessDefinitionVersionTag(processDefinitionVersionTag); } if (processVariables != null) { subscription.setProcessVariables(processVariables); } if (localVariables) { subscription.setLocalVariables(localVariables); } if(includeExtensionProperties) { subscription.setIncludeExtensionProperties(includeExtensionProperties); } topicSubscriptionManager.subscribe(subscription); return subscription; } protected void ensureNotNull(Object tenantIds, String parameterName) { if (tenantIds == null) { throw LOG.passNullValueParameter(parameterName); } } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionBuilderImpl.java
1
请完成以下Java代码
public static boolean isDecisionRequirementsDefinitionPersistable(DecisionRequirementsDefinitionEntity definition) { // persist no decision requirements definition for a single decision return definition.getDecisions().size() > 1; } @Override protected void updateDefinitionByPersistedDefinition(DeploymentEntity deployment, DecisionRequirementsDefinitionEntity definition, DecisionRequirementsDefinitionEntity persistedDefinition) { // cannot update the definition if it is not persistent if (persistedDefinition != null) { super.updateDefinitionByPersistedDefinition(deployment, definition, persistedDefinition); } } //context ///////////////////////////////////////////////////////////////////////////////////////////
protected DecisionRequirementsDefinitionManager getDecisionRequirementsDefinitionManager() { return getCommandContext().getDecisionRequirementsDefinitionManager(); } // getters/setters /////////////////////////////////////////////////////////////////////////////////// public DmnTransformer getTransformer() { return transformer; } public void setTransformer(DmnTransformer transformer) { this.transformer = transformer; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\deployer\DecisionRequirementsDefinitionDeployer.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<User> getUsers() { return users; } public void setUsers(Collection<User> users) { this.users = users; } public Collection<Privilege> getPrivileges() { return privileges; } public void setPrivileges(Collection<Privilege> privileges) { this.privileges = privileges; } @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Role role = (Role) obj; if (!role.equals(role.name)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\model\Role.java
1
请在Spring Boot框架中完成以下Java代码
public class LookupCacheInvalidationDispatcher implements ICacheResetListener { private static final String TRXPROP_TableNamesToInvalidate = LookupCacheInvalidationDispatcher.class + ".TableNamesToInvalidate"; private final LookupDataSourceFactory lookupDataSourceFactory; private final Executor async; public LookupCacheInvalidationDispatcher( @NonNull final LookupDataSourceFactory lookupDataSourceFactory) { this.lookupDataSourceFactory = lookupDataSourceFactory; async = createAsyncExecutor(); } @NonNull private static Executor createAsyncExecutor() { final CustomizableThreadFactory asyncThreadFactory = new CustomizableThreadFactory(LookupCacheInvalidationDispatcher.class.getSimpleName()); asyncThreadFactory.setDaemon(true); return Executors.newSingleThreadExecutor(asyncThreadFactory); } @PostConstruct private void postConstruct() { CacheMgt.get().addCacheResetListener(this); } @Override public long reset(final CacheInvalidateMultiRequest multiRequest) { final ITrxManager trxManager = Services.get(ITrxManager.class); final ITrx currentTrx = trxManager.getThreadInheritedTrx(OnTrxMissingPolicy.ReturnTrxNone); if (trxManager.isNull(currentTrx)) { async.execute(() -> resetNow(extractTableNames(multiRequest))); } else { final TableNamesToResetCollector collector = currentTrx.getProperty(TRXPROP_TableNamesToInvalidate, trx -> { final TableNamesToResetCollector c = new TableNamesToResetCollector(); trx.getTrxListenerManager() .newEventListener(TrxEventTiming.AFTER_COMMIT) .registerHandlingMethod(innerTrx -> { final Set<String> tableNames = c.toSet(); if (tableNames.isEmpty()) { return; } async.execute(() -> resetNow(tableNames)); }); return c; }); collector.addTableNames(extractTableNames(multiRequest)); } return 1; // not relevant
} private Set<String> extractTableNames(final CacheInvalidateMultiRequest multiRequest) { if (multiRequest.isResetAll()) { // not relevant for our lookups return ImmutableSet.of(); } return multiRequest.getRequests() .stream() .filter(request -> !request.isAll()) // not relevant for our lookups .map(CacheInvalidateRequest::getTableNameEffective) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } private void resetNow(final Set<String> tableNames) { if (tableNames.isEmpty()) { return; } lookupDataSourceFactory.cacheInvalidateOnRecordsChanged(tableNames); } private static final class TableNamesToResetCollector { private final Set<String> tableNames = new HashSet<>(); public Set<String> toSet() { return ImmutableSet.copyOf(tableNames); } public void addTableNames(final Collection<String> tableNamesToAdd) { tableNames.addAll(tableNamesToAdd); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupCacheInvalidationDispatcher.java
2
请在Spring Boot框架中完成以下Java代码
public Map<String, MonitorConfig> getMonitors() { return monitors; } public void setMonitors(Map<String, MonitorConfig> monitors) { this.monitors = monitors; } public Map<String, ProviderConfig> getProviders() { return providers; } public void setProviders(Map<String, ProviderConfig> providers) { this.providers = providers; } public Map<String, ConsumerConfig> getConsumers() { return consumers; } public void setConsumers(Map<String, ConsumerConfig> consumers) { this.consumers = consumers; } public Map<String, ConfigCenterBean> getConfigCenters() { return configCenters; } public void setConfigCenters(Map<String, ConfigCenterBean> configCenters) { this.configCenters = configCenters; } public Map<String, MetadataReportConfig> getMetadataReports() { return metadataReports; } public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) { this.metadataReports = metadataReports; } static class Config { /**
* Indicates multiple properties binding from externalized configuration or not. */ private boolean multiple = DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE; /** * The property name of override Dubbo config */ private boolean override = DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE; public boolean isOverride() { return override; } public void setOverride(boolean override) { this.override = override; } public boolean isMultiple() { return multiple; } public void setMultiple(boolean multiple) { this.multiple = multiple; } } static class Scan { /** * The basePackages to scan , the multiple-value is delimited by comma * * @see EnableDubbo#scanBasePackages() */ private Set<String> basePackages = new LinkedHashSet<>(); public Set<String> getBasePackages() { return basePackages; } public void setBasePackages(Set<String> basePackages) { this.basePackages = basePackages; } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboConfigurationProperties.java
2
请完成以下Java代码
CurrencyConversionContext getCurrencyConversionCtxForBankInTransit() { CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankInTransit; if (currencyConversionContext == null) { currencyConversionContext = this._currencyConversionContextForBankInTransit = createCurrencyConversionCtxForBankInTransit(); } return currencyConversionContext; } private CurrencyConversionContext createCurrencyConversionCtxForBankInTransit() { final I_C_Payment payment = getC_Payment(); if (payment != null) { return paymentBL.extractCurrencyConversionContext(payment); } else { final I_C_BankStatementLine line = getC_BankStatementLine(); final PaymentCurrencyContext paymentCurrencyContext = bankStatementBL.getPaymentCurrencyContext(line);
final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID()); CurrencyConversionContext conversionCtx = services.createCurrencyConversionContext( LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone), paymentCurrencyContext.getCurrencyConversionTypeId(), ClientId.ofRepoId(line.getAD_Client_ID())); final FixedConversionRate fixedCurrencyRate = paymentCurrencyContext.toFixedConversionRateOrNull(); if (fixedCurrencyRate != null) { conversionCtx = conversionCtx.withFixedConversionRate(fixedCurrencyRate); } return conversionCtx; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\DocLine_BankStatement.java
1
请完成以下Java代码
private DhlCustomsDocument getCustomsDocument(@NonNull final I_DHL_ShipmentOrder firstOrder, @NonNull final I_DHL_ShipmentOrder po, @Nullable final String orgBpEORI) { final I_C_BPartner consigneeBpartner = bpartnerDAO.getById(firstOrder.getC_BPartner_ID()); final Package mPackage = purchaseOrderToShipperTransportationRepository.getPackageById(PackageId.ofRepoId(po.getM_Package_ID())); final ImmutableList<DhlCustomsItem> dhlCustomsItems = mPackage.getPackageContents() .stream() .map(this::toDhlCustomsItem) .collect(ImmutableList.toImmutableList()); return DhlCustomsDocument.builder() .consigneeEORI(consigneeBpartner.getEORI()) .shipperEORI(orgBpEORI) .items(dhlCustomsItems) .build(); } private DhlCustomsItem toDhlCustomsItem(@NonNull final PackageItem packageItem) { final ProductId productId = packageItem.getProductId(); final I_M_Product product = productDAO.getById(productId); final BigDecimal weightInKg = computeNominalGrossWeightInKg(packageItem).orElse(BigDecimal.ZERO); Quantity packagedQuantity; try { packagedQuantity = uomConversionBL.convertQuantityTo(packageItem.getQuantity(), productId, UomId.EACH); }
catch (final NoUOMConversionException exception) { //can't convert to EACH, so we don't have an exact number. Just put 1 packagedQuantity = Quantitys.of(1, UomId.EACH); } final I_C_OrderLine orderLine = orderDAO.getOrderLineById(packageItem.getOrderLineId()); final CurrencyCode currencyCode = currencyRepository.getCurrencyCodeById(CurrencyId.ofRepoId(orderLine.getC_Currency_ID())); return DhlCustomsItem.builder() .itemDescription(product.getName()) .weightInKg(weightInKg) .packagedQuantity(packagedQuantity.intValueExact()) .itemValue(Amount.of(orderLine.getPriceEntered(), currencyCode)) .build(); } private Optional<BigDecimal> computeNominalGrossWeightInKg(final PackageItem packageItem) { final ProductId productId = packageItem.getProductId(); final Quantity quantity = packageItem.getQuantity(); return productBL.computeGrossWeight(productId, quantity) .map(weight -> uomConversionBL.convertToKilogram(weight, productId)) .map(Quantity::getAsBigDecimal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\DhlDeliveryOrderService.java
1
请完成以下Java代码
public void operation1() { lock1.lock(); print("lock1 acquired, waiting to acquire lock2."); sleep(50); lock2.lock(); print("lock2 acquired"); print("executing first operation."); lock2.unlock(); lock1.unlock(); } public void operation2() { lock2.lock(); print("lock2 acquired, waiting to acquire lock1."); sleep(50); lock1.lock(); print("lock1 acquired"); print("executing second operation."); lock1.unlock();
lock2.unlock(); } public void print(String message) { System.out.println("Thread " + Thread.currentThread() .getName() + ": " + message); } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\deadlockAndLivelock\DeadlockExample.java
1
请完成以下Java代码
public int serializedKeySize() { return this.delegate.serializedKeySize(); } public int serializedValueSize() { return this.delegate.serializedValueSize(); } public String topic() { return this.delegate.topic(); } public int partition() { return this.delegate.partition(); } public TimestampType timestampType() { return this.timestampType; } @Override public int hashCode() { return this.delegate.hashCode() + this.timestampType.name().hashCode(); } @Override
public boolean equals(Object obj) { if (!(obj instanceof ConsumerRecordMetadata)) { return false; } ConsumerRecordMetadata crm = (ConsumerRecordMetadata) obj; return this.delegate.equals(crm.delegate) && this.timestampType.equals(crm.timestampType()); } @Override public String toString() { return this.delegate.toString(); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\ConsumerRecordMetadata.java
1
请完成以下Java代码
public int getC_Queue_WorkPackage_ID() { return get_ValueAsInt(COLUMNNAME_C_Queue_WorkPackage_ID); } @Override public I_C_Queue_WorkPackage getC_Queue_Workpackage_Preceeding() { return get_ValueAsPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class); } @Override public void setC_Queue_Workpackage_Preceeding(final I_C_Queue_WorkPackage C_Queue_Workpackage_Preceeding) { set_ValueFromPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class, C_Queue_Workpackage_Preceeding); } @Override public void setC_Queue_Workpackage_Preceeding_ID (final int C_Queue_Workpackage_Preceeding_ID) { throw new IllegalArgumentException ("C_Queue_Workpackage_Preceeding_ID is virtual column"); } @Override public int getC_Queue_Workpackage_Preceeding_ID()
{ return get_ValueAsInt(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Element.java
1
请完成以下Java代码
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { // @formatter:off return this.matcher.matches(exchange) .filter(ServerWebExchangeMatcher.MatchResult::isMatch) .flatMap((result) -> this.generateRequestResolver.resolve(exchange)) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())) .flatMap(this.oneTimeTokenService::generate) .flatMap((token) -> this.oneTimeTokenGenerationSuccessHandler.handle(exchange, token)); // @formatter:on } /** * Use the given {@link ServerWebExchangeMatcher} to match the request. * @param matcher */ public void setRequestMatcher(ServerWebExchangeMatcher matcher) {
Assert.notNull(matcher, "matcher cannot be null"); this.matcher = matcher; } /** * Use the given {@link ServerGenerateOneTimeTokenRequestResolver} to resolve the * request, defaults to {@link DefaultServerGenerateOneTimeTokenRequestResolver} * @param requestResolver {@link ServerGenerateOneTimeTokenRequestResolver} * @since 6.5 */ public void setGenerateRequestResolver(ServerGenerateOneTimeTokenRequestResolver requestResolver) { Assert.notNull(requestResolver, "requestResolver cannot be null"); this.generateRequestResolver = requestResolver; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\ott\GenerateOneTimeTokenWebFilter.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isNf() { return state.notifications; } public boolean isEmpty() { return subs.isEmpty(); } public TbSubscription<?> registerPendingSubscription(TbSubscription<?> subscription, TbEntitySubEvent event) { if (TbSubscriptionType.ATTRIBUTES.equals(subscription.getType())) { if (event != null) { log.trace("[{}][{}] Registering new pending attributes subscription event: {} for subscription: {}", tenantId, entityId, event.getSeqNumber(), subscription.getSubscriptionId()); pendingAttributesEvent = event.getSeqNumber(); pendingAttributesEventTs = System.currentTimeMillis(); pendingSubs.computeIfAbsent(pendingAttributesEvent, e -> new HashSet<>()).add(subscription); } else if (pendingAttributesEvent > 0) { log.trace("[{}][{}] Registering pending attributes subscription {} for event: {} ", tenantId, entityId, subscription.getSubscriptionId(), pendingAttributesEvent); pendingSubs.computeIfAbsent(pendingAttributesEvent, e -> new HashSet<>()).add(subscription); } else { return subscription; } } else if (subscription instanceof TbTimeSeriesSubscription) { if (event != null) { log.trace("[{}][{}] Registering new pending time-series subscription event: {} for subscription: {}", tenantId, entityId, event.getSeqNumber(), subscription.getSubscriptionId()); pendingTimeSeriesEvent = event.getSeqNumber(); pendingTimeSeriesEventTs = System.currentTimeMillis(); pendingSubs.computeIfAbsent(pendingTimeSeriesEvent, e -> new HashSet<>()).add(subscription); } else if (pendingTimeSeriesEvent > 0) { log.trace("[{}][{}] Registering pending time-series subscription {} for event: {} ", tenantId, entityId, subscription.getSubscriptionId(), pendingTimeSeriesEvent); pendingSubs.computeIfAbsent(pendingTimeSeriesEvent, e -> new HashSet<>()).add(subscription); } else {
return subscription; } } return null; } public Set<TbSubscription<?>> clearPendingSubscriptions(int seqNumber) { if (pendingTimeSeriesEvent == seqNumber) { pendingTimeSeriesEvent = 0; pendingTimeSeriesEventTs = 0L; } else if (pendingAttributesEvent == seqNumber) { pendingAttributesEvent = 0; pendingAttributesEventTs = 0L; } return pendingSubs.remove(seqNumber); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbEntityLocalSubsInfo.java
2
请在Spring Boot框架中完成以下Java代码
private void validateMBeans() { HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(this.dataSource, HikariConfigMXBean.class, HikariDataSource.class); if (hikariDataSource != null && hikariDataSource.isRegisterMbeans()) { this.mBeanExporter.ifUnique((exporter) -> exporter.addExcludedBean("dataSource")); } } } @Configuration(proxyBeanMethods = false) @ConditionalOnBooleanProperty("spring.datasource.tomcat.jmx-enabled") @ConditionalOnClass(DataSourceProxy.class) @ConditionalOnSingleCandidate(DataSource.class) static class TomcatDataSourceJmxConfiguration { @Bean @ConditionalOnMissingBean(name = "dataSourceMBean") @Nullable Object dataSourceMBean(DataSource dataSource) {
DataSourceProxy dataSourceProxy = DataSourceUnwrapper.unwrap(dataSource, PoolConfiguration.class, DataSourceProxy.class); if (dataSourceProxy != null) { try { return dataSourceProxy.createPool().getJmxPool(); } catch (SQLException ex) { logger.warn("Cannot expose DataSource to JMX (could not connect)"); } } return null; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceJmxConfiguration.java
2
请完成以下Java代码
public double getCount() { return rule.getCount(); } @JsonIgnore @JSONField(serialize = false) public List<ParamFlowItem> getParamFlowItemList() { return rule.getParamFlowItemList(); } @JsonIgnore @JSONField(serialize = false) public int getControlBehavior() { return rule.getControlBehavior(); } @JsonIgnore @JSONField(serialize = false) public int getMaxQueueingTimeMs() { return rule.getMaxQueueingTimeMs(); } @JsonIgnore @JSONField(serialize = false) public int getBurstCount() { return rule.getBurstCount();
} @JsonIgnore @JSONField(serialize = false) public long getDurationInSec() { return rule.getDurationInSec(); } @JsonIgnore @JSONField(serialize = false) public boolean isClusterMode() { return rule.isClusterMode(); } @JsonIgnore @JSONField(serialize = false) public ParamFlowClusterConfig getClusterConfig() { return rule.getClusterConfig(); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\ParamFlowRuleEntity.java
1
请完成以下Java代码
public class MigratorTool { public static void main(String[] args) { CommandLine cmd = parseArgs(args); try { boolean castEnable = Boolean.parseBoolean(cmd.getOptionValue("castEnable")); File allTelemetrySource = new File(cmd.getOptionValue("telemetryFrom")); File tsSaveDir = null; File partitionsSaveDir = null; File latestSaveDir = null; RelatedEntitiesParser allEntityIdsAndTypes = new RelatedEntitiesParser(new File(cmd.getOptionValue("relatedEntities"))); DictionaryParser dictionaryParser = new DictionaryParser(allTelemetrySource); if(cmd.getOptionValue("latestTelemetryOut") != null) { latestSaveDir = new File(cmd.getOptionValue("latestTelemetryOut")); } if(cmd.getOptionValue("telemetryOut") != null) { tsSaveDir = new File(cmd.getOptionValue("telemetryOut")); partitionsSaveDir = new File(cmd.getOptionValue("partitionsOut")); } new PgCaMigrator(allTelemetrySource, tsSaveDir, partitionsSaveDir, latestSaveDir, allEntityIdsAndTypes, dictionaryParser, castEnable).migrate(); } catch (Throwable th) { th.printStackTrace(); throw new IllegalStateException("failed", th); } } private static CommandLine parseArgs(String[] args) { Options options = new Options(); Option telemetryAllFrom = new Option("telemetryFrom", "telemetryFrom", true, "telemetry source file"); telemetryAllFrom.setRequired(true); options.addOption(telemetryAllFrom); Option latestTsOutOpt = new Option("latestOut", "latestTelemetryOut", true, "latest telemetry save dir"); latestTsOutOpt.setRequired(false); options.addOption(latestTsOutOpt); Option tsOutOpt = new Option("tsOut", "telemetryOut", true, "sstable save dir"); tsOutOpt.setRequired(false); options.addOption(tsOutOpt); Option partitionOutOpt = new Option("partitionsOut", "partitionsOut", true, "partitions save dir"); partitionOutOpt.setRequired(false); options.addOption(partitionOutOpt);
Option castOpt = new Option("castEnable", "castEnable", true, "cast String to Double if possible"); castOpt.setRequired(true); options.addOption(castOpt); Option relatedOpt = new Option("relatedEntities", "relatedEntities", true, "related entities source file path"); relatedOpt.setRequired(true); options.addOption(relatedOpt); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); try { return parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); System.exit(1); } return null; } }
repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\MigratorTool.java
1
请完成以下Java代码
public void setSidIdentityQuery(String sidIdentityQuery) { Assert.hasText(sidIdentityQuery, "New sidIdentityQuery query is required"); this.sidIdentityQuery = sidIdentityQuery; } public void setDeleteEntryByObjectIdentityForeignKeySql(String deleteEntryByObjectIdentityForeignKey) { this.deleteEntryByObjectIdentityForeignKey = deleteEntryByObjectIdentityForeignKey; } public void setDeleteObjectIdentityByPrimaryKeySql(String deleteObjectIdentityByPrimaryKey) { this.deleteObjectIdentityByPrimaryKey = deleteObjectIdentityByPrimaryKey; } public void setInsertClassSql(String insertClass) { this.insertClass = insertClass; } public void setInsertEntrySql(String insertEntry) { this.insertEntry = insertEntry; } public void setInsertObjectIdentitySql(String insertObjectIdentity) { this.insertObjectIdentity = insertObjectIdentity; } public void setInsertSidSql(String insertSid) { this.insertSid = insertSid; } public void setClassPrimaryKeyQuery(String selectClassPrimaryKey) { this.selectClassPrimaryKey = selectClassPrimaryKey; } public void setObjectIdentityPrimaryKeyQuery(String selectObjectIdentityPrimaryKey) { this.selectObjectIdentityPrimaryKey = selectObjectIdentityPrimaryKey; } public void setSidPrimaryKeyQuery(String selectSidPrimaryKey) { this.selectSidPrimaryKey = selectSidPrimaryKey; }
public void setUpdateObjectIdentity(String updateObjectIdentity) { this.updateObjectIdentity = updateObjectIdentity; } /** * @param foreignKeysInDatabase if false this class will perform additional FK * constrain checking, which may cause deadlocks (the default is true, so deadlocks * are avoided but the database is expected to enforce FKs) */ public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) { this.foreignKeysInDatabase = foreignKeysInDatabase; } @Override public void setAclClassIdSupported(boolean aclClassIdSupported) { super.setAclClassIdSupported(aclClassIdSupported); if (aclClassIdSupported) { // Change the default insert if it hasn't been overridden if (this.insertClass.equals(DEFAULT_INSERT_INTO_ACL_CLASS)) { this.insertClass = DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID; } else { log.debug("Insert class statement has already been overridden, so not overridding the default"); } } } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\JdbcMutableAclService.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonHUAttribute { @NonNull String code; @NonNull String caption; @Nullable Object value; @Nullable Object valueDisplay; @Builder @Jacksonized private JsonHUAttribute( @NonNull final String code, @NonNull final String caption, @Nullable final Object value, @Nullable final Object valueDisplay) { this.code = code; this.caption = caption; this.value = convertValueToJson(value); this.valueDisplay = valueDisplay != null ? valueDisplay : CoalesceUtil.coalesceNotNull(this.value, ""); } @Nullable public static Object convertValueToJson(final Object value) { if (value == null) { return null; } else if (value instanceof String) { return value; } else if (value instanceof Integer) { return value; } else if (value instanceof BigDecimal) {
return value.toString(); } else if (value instanceof Boolean) { return value; } else if (value instanceof java.sql.Timestamp) { final LocalDateTime localDateTime = ((Timestamp)value).toLocalDateTime(); final LocalDate localDate = localDateTime.toLocalDate(); if (localDateTime.equals(localDate.atStartOfDay())) { return localDate.toString(); } else { return localDateTime.toLocalTime(); } } else { return value.toString(); } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\handlingunits\JsonHUAttribute.java
2
请完成以下Java代码
public List<JSONDocument> processChanges( @PathVariable("docId") final int docId, @RequestBody final List<JSONDocumentChangedEvent> events) { userSession.assertLoggedIn(); return Execution.callInNewExecution("processChanges", () -> { final IDocumentChangesCollector changesCollector = Execution.getCurrentDocumentChangesCollectorOrNull(); addressRepo.processAddressDocumentChanges(docId, events, changesCollector); return JSONDocument.ofEvents(changesCollector, newJsonDocumentOpts()); }); } @GetMapping("/{docId}/field/{attributeName}/typeahead") public JSONLookupValuesPage getAttributeTypeahead( @PathVariable("docId") final int docId, @PathVariable("attributeName") final String attributeName, @RequestParam(name = "query") final String query) { userSession.assertLoggedIn(); return addressRepo.getAddressDocumentForReading(docId) .getFieldLookupValuesForQuery(attributeName, query) .transform(page -> JSONLookupValuesPage.of(page, userSession.getAD_Language())); } @GetMapping("/{docId}/field/{attributeName}/dropdown") public JSONLookupValuesList getAttributeDropdown( @PathVariable("docId") final int docId, @PathVariable("attributeName") final String attributeName) { userSession.assertLoggedIn(); return addressRepo.getAddressDocumentForReading(docId)
.getFieldLookupValues(attributeName) .transform(list -> JSONLookupValuesList.ofLookupValuesList(list, userSession.getAD_Language())); } @PostMapping("/{docId}/complete") public JSONLookupValue complete( @PathVariable("docId") final int docId, @RequestBody final JSONCompleteASIRequest request) { userSession.assertLoggedIn(); return Execution.callInNewExecution( "complete", () -> addressRepo.complete(docId, request.getEvents()) .transform(lookupValue -> JSONLookupValue.ofLookupValue(lookupValue, userSession.getAD_Language()))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRestController.java
1
请完成以下Java代码
public class WidgetTypeDetailsEntity extends AbstractWidgetTypeEntity<WidgetTypeDetails> { @Column(name = ModelConstants.WIDGET_TYPE_IMAGE_PROPERTY) private String image; @Column(name = ModelConstants.WIDGET_TYPE_DESCRIPTION_PROPERTY) private String description; @Type(StringArrayType.class) @Column(name = ModelConstants.WIDGET_TYPE_TAGS_PROPERTY, columnDefinition = "text[]") private String[] tags; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.WIDGET_TYPE_DESCRIPTOR_PROPERTY) private JsonNode descriptor; @Column(name = ModelConstants.EXTERNAL_ID_PROPERTY) private UUID externalId; public WidgetTypeDetailsEntity() { super(); } public WidgetTypeDetailsEntity(WidgetTypeDetails widgetTypeDetails) { super(widgetTypeDetails);
this.image = widgetTypeDetails.getImage(); this.description = widgetTypeDetails.getDescription(); this.tags = widgetTypeDetails.getTags(); this.descriptor = widgetTypeDetails.getDescriptor(); if (widgetTypeDetails.getExternalId() != null) { this.externalId = widgetTypeDetails.getExternalId().getId(); } } @Override public WidgetTypeDetails toData() { BaseWidgetType baseWidgetType = super.toBaseWidgetType(); WidgetTypeDetails widgetTypeDetails = new WidgetTypeDetails(baseWidgetType); widgetTypeDetails.setImage(image); widgetTypeDetails.setDescription(description); widgetTypeDetails.setTags(tags); widgetTypeDetails.setDescriptor(descriptor); if (externalId != null) { widgetTypeDetails.setExternalId(new WidgetTypeId(externalId)); } return widgetTypeDetails; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\WidgetTypeDetailsEntity.java
1
请完成以下Java代码
public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } public String toEventMessage(String message) { String eventMessage = message.replaceAll("\\s+", " "); if (eventMessage.length() > 163) { eventMessage = eventMessage.substring(0, 160) + "..."; } return eventMessage; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", type=" + type + ", userId=" + userId + ", time=" + time
+ ", taskId=" + taskId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", revision= "+ revision + ", removalTime=" + removalTime + ", action=" + action + ", message=" + message + ", fullMessage=" + fullMessage + ", tenantId=" + tenantId + "]"; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public int getRevision() { return revision; } @Override public int getRevisionNext() { return revision + 1; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentEntity.java
1
请完成以下Java代码
public void setStartImpression (int StartImpression) { set_Value (COLUMNNAME_StartImpression, Integer.valueOf(StartImpression)); } /** Get Start Count Impression. @return For rotation we need a start count */ public int getStartImpression () { Integer ii = (Integer)get_Value(COLUMNNAME_StartImpression); if (ii == null) return 0; return ii.intValue(); } /** Set Target Frame. @param Target_Frame Which target should be used if user clicks? */ public void setTarget_Frame (String Target_Frame) { set_Value (COLUMNNAME_Target_Frame, Target_Frame); } /** Get Target Frame. @return Which target should be used if user clicks? */ public String getTarget_Frame () { return (String)get_Value(COLUMNNAME_Target_Frame); }
/** Set Target URL. @param TargetURL URL for the Target */ public void setTargetURL (String TargetURL) { set_Value (COLUMNNAME_TargetURL, TargetURL); } /** Get Target URL. @return URL for the Target */ public String getTargetURL () { return (String)get_Value(COLUMNNAME_TargetURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Ad.java
1
请在Spring Boot框架中完成以下Java代码
public class PurchaseLastMaxPriceService { @NonNull private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); @NonNull private final IOrderDAO orderDAO = Services.get(IOrderDAO.class); @NonNull private final MoneyService moneyService; private static final String TABLENAME_Recompute = "purchase_order_highestprice_per_day_mv$recompute"; @VisibleForTesting public static PurchaseLastMaxPriceService newInstanceForUnitTesting() { Adempiere.assertUnitTestMode(); return new PurchaseLastMaxPriceService(new MoneyService(new CurrencyRepository())); } public PurchaseLastMaxPriceProvider newProvider() { return PurchaseLastMaxPriceProvider.builder() .sysConfigBL(sysConfigBL) .moneyService(moneyService) .build(); } public void invalidateByOrder(final I_C_Order order) { // Consider only purchase orders if (order.isSOTrx()) { return; } final LocalDate date = extractDate(order); final ImmutableSet<ProductId> productIds = getProductIds(order); invalidateByProducts(productIds, date); } private static LocalDate extractDate(final I_C_Order order) { return order.getDateOrdered().toLocalDateTime().toLocalDate(); } private ImmutableSet<ProductId> getProductIds(final I_C_Order order) { final OrderId orderId = OrderId.ofRepoId(order.getC_Order_ID()); return orderDAO.retrieveOrderLines(orderId) .stream() .map(orderLine -> ProductId.ofRepoId(orderLine.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); }
public void invalidateByProducts(@NonNull Set<ProductId> productIds, @NonNull LocalDate date) { if (productIds.isEmpty()) { return; } final ArrayList<Object> sqlValuesParams = new ArrayList<>(); final StringBuilder sqlValues = new StringBuilder(); for (final ProductId productId : productIds) { if (sqlValues.length() > 0) { sqlValues.append(","); } sqlValues.append("(?,?)"); sqlValuesParams.add(productId); sqlValuesParams.add(date); } final String sql = "INSERT INTO " + TABLENAME_Recompute + " (m_product_id, date)" + "VALUES " + sqlValues; DB.executeUpdateAndThrowExceptionOnFail(sql, sqlValuesParams.toArray(), ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\stats\purchase_max_price\PurchaseLastMaxPriceService.java
2
请完成以下Java代码
public SecurityIdentification4Choice getFinInstrmId() { return finInstrmId; } /** * Sets the value of the finInstrmId property. * * @param value * allowed object is * {@link SecurityIdentification4Choice } * */ public void setFinInstrmId(SecurityIdentification4Choice value) { this.finInstrmId = value; } /** * Gets the value of the tax property. * * @return * possible object is * {@link TaxInformation3 } * */ public TaxInformation3 getTax() { return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxInformation3 } * */ public void setTax(TaxInformation3 value) { this.tax = value; } /** * Gets the value of the rtrInf property. * * @return * possible object is * {@link ReturnReasonInformation10 } * */ public ReturnReasonInformation10 getRtrInf() { return rtrInf; } /** * Sets the value of the rtrInf property. * * @param value * allowed object is * {@link ReturnReasonInformation10 } * */ public void setRtrInf(ReturnReasonInformation10 value) { this.rtrInf = value; } /** * Gets the value of the corpActn property. * * @return * possible object is * {@link CorporateAction1 } * */ public CorporateAction1 getCorpActn() { return corpActn; } /** * Sets the value of the corpActn property. * * @param value * allowed object is * {@link CorporateAction1 } * */ public void setCorpActn(CorporateAction1 value) { this.corpActn = value; } /** * Gets the value of the sfkpgAcct property. * * @return * possible object is * {@link CashAccount16 } *
*/ public CashAccount16 getSfkpgAcct() { return sfkpgAcct; } /** * Sets the value of the sfkpgAcct property. * * @param value * allowed object is * {@link CashAccount16 } * */ public void setSfkpgAcct(CashAccount16 value) { this.sfkpgAcct = value; } /** * Gets the value of the addtlTxInf property. * * @return * possible object is * {@link String } * */ public String getAddtlTxInf() { return addtlTxInf; } /** * Sets the value of the addtlTxInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlTxInf(String value) { this.addtlTxInf = 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\EntryTransaction2.java
1
请在Spring Boot框架中完成以下Java代码
public static void put(String key, Object value) { if(ObjectUtil.isNotEmpty(value)) { DATA_MAP.put(key, value); REQUEST_DATA.set(DATA_MAP); } } /** * 获取请求参数值 * * @param key 请求参数 * @return */ public static <T> T get(String key) { ConcurrentHashMap dataMap = REQUEST_DATA.get(); if (CollectionUtils.isNotEmpty(dataMap)) { return (T) dataMap.get(key);
} return null; } /** * 获取请求参数 * * @return 请求参数 MAP 对象 */ public static void clear() { DATA_MAP.clear(); REQUEST_DATA.remove(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\mybatis\ThreadLocalDataHelper.java
2
请在Spring Boot框架中完成以下Java代码
public Person save(Person person) { Person p = personRepository.save(person); System.out.println("为id、key为:" + p.getId() + "数据做了缓存"); return p; } @Override @CacheEvict(value = "people")//2 public void remove(Long id) { System.out.println("删除了id、key为" + id + "的数据缓存"); //这里不做实际删除操作 } /** * Cacheable * value:缓存key的前缀。 * key:缓存key的后缀。 * sync:设置如果缓存过期是不是只放一个请求去请求数据库,其他请求阻塞,默认是false。 */ @Override @Cacheable(value = "people#${select.cache.timeout:1800}#${select.cache.refresh:600}", key = "#person.id", sync = true) //3 public Person findOne(Person person, String a, String[] b, List<Long> c) { Person p = personRepository.findOne(person.getId()); System.out.println("为id、key为:" + p.getId() + "数据做了缓存"); System.out.println(redisTemplate); return p; } @Override
@Cacheable(value = "people#120#120")//3 public Person findOne1() { Person p = personRepository.findOne(2L); System.out.println("为id、key为:" + p.getId() + "数据做了缓存"); return p; } @Override @Cacheable(value = "people2")//3 public Person findOne2(Person person) { Person p = personRepository.findOne(person.getId()); System.out.println("为id、key为:" + p.getId() + "数据做了缓存"); return p; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\service\impl\PersonServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public byte[] getContent() { return this.encoded.substring(0, this.encoded.lastIndexOf('.')).getBytes(); } public byte[] getSignature() { return Base64.getUrlDecoder().decode(this.signature); } public String getSignatureAlgorithm() { return getRequired(this.header, "alg", String.class); } public String getIssuer() { return getRequired(this.claims, "iss", String.class); } public long getExpiry() { return getRequired(this.claims, "exp", Integer.class).longValue(); } @SuppressWarnings("unchecked") public List<String> getScope() { return getRequired(this.claims, "scope", List.class); } public String getKeyId() { return getRequired(this.header, "kid", String.class);
} @SuppressWarnings("unchecked") private <T> T getRequired(Map<String, Object> map, String key, Class<T> type) { Object value = map.get(key); if (value == null) { throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Unable to get value from key " + key); } if (!type.isInstance(value)) { throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Unexpected value type from key " + key + " value " + value); } return (T) value; } @Override public String toString() { return this.encoded; } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\Token.java
2
请在Spring Boot框架中完成以下Java代码
public LocalContainerEntityManagerFactoryBean userEntityManager() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(userDataSource()); em.setPackagesToScan("com.baeldung.multipledb.model.user"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); final HashMap<String, Object> properties = new HashMap<String, Object>(); properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); em.setJpaPropertyMap(properties); return em; } @Bean
@Primary @ConfigurationProperties(prefix="spring.datasource") public DataSource userDataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean public PlatformTransactionManager userTransactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(userEntityManager().getObject()); return transactionManager; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\multipledb\PersistenceUserAutoConfiguration.java
2
请完成以下Java代码
public void setupEnvironment(Hashtable env, String dn, String password) { super.setupEnvironment(env, dn, password); // Remove the pooling flag unless authenticating as the 'manager' user. if (!DefaultSpringSecurityContextSource.this.getUserDn().equals(dn) && env.containsKey(SUN_LDAP_POOLING_FLAG)) { DefaultSpringSecurityContextSource.this.logger.trace("Removing pooling flag for user " + dn); env.remove(SUN_LDAP_POOLING_FLAG); } } }); } /** * Create and initialize an instance which will connect of the LDAP Spring Security * Context Source. It will connect to any of the provided LDAP server URLs. * @param urls A list of string values which are LDAP server URLs. An example would be * <code>ldap://ldap.company.com:389</code>. LDAPS URLs (SSL-secured) may be used as * well, given that Spring Security is able to connect to the server. Note that these * <b>URLs must not include the base DN</b>! * @param baseDn The common Base DN for all provided servers, e.g. * * <pre> * dc=company,dc=com * </pre> * * . */ public DefaultSpringSecurityContextSource(List<String> urls, String baseDn) { this(buildProviderUrl(urls, baseDn)); } /** * Builds a Spring LDAP-compliant Provider URL string, i.e. a space-separated list of * LDAP servers with their base DNs. As the base DN must be identical for all servers, * it needs to be supplied only once. * @param urls A list of string values which are LDAP server URLs. An example would be * * <pre> * ldap://ldap.company.com:389 * </pre> * * . LDAPS URLs may be used as well, given that Spring Security is able to connect to * the server. * @param baseDn The common Base DN for all provided servers, e.g. * * <pre>
* dc=company,dc=com * </pre> * * . * @return A Spring Security/Spring LDAP-compliant Provider URL string. */ private static String buildProviderUrl(List<String> urls, String baseDn) { Assert.notNull(baseDn, "The Base DN for the LDAP server must not be null."); Assert.notEmpty(urls, "At least one LDAP server URL must be provided."); String encodedBaseDn = encodeUrl(baseDn.trim()); StringBuilder providerUrl = new StringBuilder(); for (String serverUrl : urls) { String trimmedUrl = serverUrl.trim(); if (trimmedUrl.isEmpty()) { continue; } providerUrl.append(trimmedUrl); if (!trimmedUrl.endsWith("/")) { providerUrl.append("/"); } providerUrl.append(encodedBaseDn); providerUrl.append(" "); } return providerUrl.toString(); } private static String encodeUrl(String url) { return URLEncoder.encode(url, StandardCharsets.UTF_8); } private String decodeUrl(String url) { return URLDecoder.decode(url, StandardCharsets.UTF_8); } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\DefaultSpringSecurityContextSource.java
1
请完成以下Java代码
default IInvoiceCandidateEnqueueResult prepareAndEnqueueSelection(@NonNull final PInstanceId pinstanceId) { prepareSelection(pinstanceId); return enqueueSelection(pinstanceId); }; IInvoiceCandidateEnqueueResult enqueueInvoiceCandidateIds(Set<InvoiceCandidateId> invoiceCandidateIds); /** * Context/transaction name to be used when enqueueing. */ IInvoiceCandidateEnqueuer setContext(final Properties ctx); /** * @param failIfNothingEnqueued true if enqueueing shall fail if nothing was enqueued */ IInvoiceCandidateEnqueuer setFailIfNothingEnqueued(boolean failIfNothingEnqueued); /** * Set to <code>true</code> if you want the enqueuer to make sure that the invoice candidates that will be enqueued shall not be changed. * <p> * By default, if you are not setting a particular value the {@link #SYSCONFIG_FailOnChanges} (default {@link #DEFAULT_FailOnChanges}) will be used. */ IInvoiceCandidateEnqueuer setFailOnChanges(boolean failOnChanges); /** * Sets invoicing parameters to be used. */
IInvoiceCandidateEnqueuer setInvoicingParams(IInvoicingParams invoicingParams); /** * Sets the total net amount to invoice checksum. * <p> * If the amount is not null and "FailOnChanges" is set then this checksum will be enforced on enqueued invoice candidates. */ IInvoiceCandidateEnqueuer setTotalNetAmtToInvoiceChecksum(BigDecimal totalNetAmtToInvoiceChecksum); /** * Sets the asyncBatch that the workpackages will be assigned to. */ IInvoiceCandidateEnqueuer setAsyncBatchId(AsyncBatchId asyncBatchId); /** * Sets the priority to be used when processing the WPs */ IInvoiceCandidateEnqueuer setPriority(IWorkpackagePrioStrategy priority); }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\IInvoiceCandidateEnqueuer.java
1
请完成以下Java代码
public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() { return new HistoricProcessInstanceQueryImpl(); } public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(); } public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(); } public HistoricDetailQueryImpl createHistoricDetailQuery() { return new HistoricDetailQueryImpl(); }
public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(); } // getters and setters // ////////////////////////////////////////////////////// public SqlSession getSqlSession() { return sqlSession; } public DbSqlSessionFactory getDbSqlSessionFactory() { return dbSqlSessionFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java
1
请完成以下Java代码
public String getJoinClause() { return m_joinClause; } // getJoinClause /** * Get Main Table Alias * @return Main Table Alias */ public String getMainAlias() { return m_mainAlias; } // getMainAlias /** * Get Join Table Alias * @return Join Table Alias */ public String getJoinAlias() { return m_joinAlias; } // getJoinAlias /** * Is Left Aouter Join * @return true if left outer join */ public boolean isLeft() { return m_left; } // isLeft /** * Get Join condition. * e.g. f.AD_Column_ID = c.AD_Column_ID * @return join condition */ public String getCondition() { return m_condition; } // getCondition /*************************************************************************/ /** * Set Main Table Name. * If table name equals alias, the alias is set to "" * @param mainTable */ public void setMainTable(String mainTable) { if (mainTable == null || mainTable.length() == 0) return; m_mainTable = mainTable; if (m_mainAlias.equals(mainTable)) m_mainAlias = ""; } // setMainTable /** * Get Main Table Name * @return Main Table Name */ public String getMainTable() { return m_mainTable; } // getMainTable /** * Set Main Table Name. * If table name equals alias, the alias is set to "" * @param joinTable */ public void setJoinTable(String joinTable) { if (joinTable == null || joinTable.length() == 0) return; m_joinTable = joinTable; if (m_joinAlias.equals(joinTable)) m_joinAlias = ""; } // setJoinTable /** * Get Join Table Name * @return Join Table Name
*/ public String getJoinTable() { return m_joinTable; } // getJoinTable /*************************************************************************/ /** * This Join is a condition of the first Join. * e.g. tb.AD_User_ID(+)=? or tb.AD_User_ID(+)='123' * @param first * @return true if condition */ public boolean isConditionOf (Join first) { if (m_mainTable == null // did not find Table from "Alias" && (first.getJoinTable().equals(m_joinTable) // same join table || first.getMainAlias().equals(m_joinTable))) // same main table return true; return false; } // isConditionOf /** * String representation * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer ("Join["); sb.append(m_joinClause) .append(" - Main=").append(m_mainTable).append("/").append(m_mainAlias) .append(", Join=").append(m_joinTable).append("/").append(m_joinAlias) .append(", Left=").append(m_left) .append(", Condition=").append(m_condition) .append("]"); return sb.toString(); } // toString } // Join
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\dbPort\Join.java
1
请完成以下Java代码
public int getRelatedProduct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RelatedProduct_ID); if (ii == null) return 0; return ii.intValue(); } /** RelatedProductType AD_Reference_ID=313 */ public static final int RELATEDPRODUCTTYPE_AD_Reference_ID=313; /** Web Promotion = P */ public static final String RELATEDPRODUCTTYPE_WebPromotion = "P"; /** Alternative = A */ public static final String RELATEDPRODUCTTYPE_Alternative = "A"; /** Supplemental = S */ public static final String RELATEDPRODUCTTYPE_Supplemental = "S";
/** Set Related Product Type. @param RelatedProductType Related Product Type */ public void setRelatedProductType (String RelatedProductType) { set_ValueNoCheck (COLUMNNAME_RelatedProductType, RelatedProductType); } /** Get Related Product Type. @return Related Product Type */ public String getRelatedProductType () { return (String)get_Value(COLUMNNAME_RelatedProductType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RelatedProduct.java
1
请完成以下Java代码
BooleanWithReason parseAndUpdateResult(@NonNull final ScannedCode scannedCode, @NonNull final ParsedScannedCodeBuilder result) { try { final String valueStr = extractAsString(scannedCode).orElse(null); if (valueStr == null) { return BooleanWithReason.falseBecause("Cannot extract part " + this); } switch (type) { case Ignored: break; case Constant: if (!Objects.equals(valueStr, constantValue)) { return BooleanWithReason.falseBecause("Invalid constant marker, expected `" + constantValue + "` but was `" + valueStr + "`"); } break; case ProductCode: result.productNo(valueStr); break; case WeightInKg: result.weightKg(toBigDecimal(valueStr)); break; case LotNo: result.lotNo(trimLeadingZeros(valueStr.trim())); break; case BestBeforeDate: result.bestBeforeDate(toLocalDate(valueStr)); break; case ProductionDate: result.productionDate(toLocalDate(valueStr)); break; } return BooleanWithReason.TRUE; } catch (final Exception ex) { return BooleanWithReason.falseBecause("Failed extracting " + this + " because " + ex.getLocalizedMessage()); } } private Optional<String> extractAsString(final ScannedCode scannedCode)
{ int startIndex = startPosition - 1; int endIndex = endPosition - 1 + 1; if (endIndex > scannedCode.length()) { return Optional.empty(); } return Optional.of(scannedCode.substring(startIndex, endIndex)); } private BigDecimal toBigDecimal(final String valueStr) { BigDecimal valueBD = new BigDecimal(valueStr); if (decimalPointPosition > 0) { valueBD = valueBD.scaleByPowerOfTen(-decimalPointPosition); } return valueBD; } private LocalDate toLocalDate(final String valueStr) { final PatternedDateTimeFormatter dateFormat = coalesceNotNull(this.dateFormat, DEFAULT_DATE_FORMAT); return dateFormat.parseLocalDate(valueStr); } private static String trimLeadingZeros(final String valueStr) { int index = 0; while (index < valueStr.length() && valueStr.charAt(index) == '0') { index++; } return index == 0 ? valueStr : valueStr.substring(index); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\ScannableCodeFormatPart.java
1
请在Spring Boot框架中完成以下Java代码
public class ApiService { private final RestTemplate restTemplate; private final String baseUrl; public ApiService(RestTemplate restTemplate, String baseUrl) { this.restTemplate = restTemplate; this.baseUrl = baseUrl; } public List<User> fetchUserList() { ParameterizedTypeReference<List<User>> typeRef = new ParameterizedTypeReference<List<User>>() { }; ResponseEntity<List<User>> response = restTemplate.exchange(baseUrl + "/api/users", HttpMethod.GET, null, typeRef); return response.getBody(); } public List<User> fetchUsersWrongApproach() { ResponseEntity<List> response = restTemplate.getForEntity(baseUrl + "/api/users", List.class); return (List<User>) response.getBody(); } public List<User> fetchUsersCorrectApproach() { ParameterizedTypeReference<List<User>> typeRef = new ParameterizedTypeReference<List<User>>() { };
ResponseEntity<List<User>> response = restTemplate.exchange(baseUrl + "/api/users", HttpMethod.GET, null, typeRef); return response.getBody(); } public User fetchUser(Long id) { return restTemplate.getForObject(baseUrl + "/api/users/" + id, User.class); } public User[] fetchUsersArray() { return restTemplate.getForObject(baseUrl + "/api/users", User[].class); } public List<User> fetchUsersList() { ParameterizedTypeReference<List<User>> typeRef = new ParameterizedTypeReference<List<User>>() { }; ResponseEntity<List<User>> response = restTemplate.exchange(baseUrl + "/api/users", HttpMethod.GET, null, typeRef); return response.getBody(); } public List<User> fetchUsersListWithExistingReference() { ResponseEntity<List<User>> response = restTemplate.exchange(baseUrl + "/api/users", HttpMethod.GET, null, USER_LIST); return response.getBody(); } }
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\parametrizedtypereference\ApiService.java
2
请完成以下Java代码
public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } @Override public Boolean getDisplay() { return display; } public void setDisplay(Boolean display) { this.display = display; } @Override public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @Override public boolean isAnalytics() { return analytics; } public void setAnalytics(boolean analytics) { this.analytics = analytics; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VariableDefinitionImpl that = (VariableDefinitionImpl) o; return ( required == that.required && Objects.equals(display, that.display) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(type, that.type) && Objects.equals(displayName, that.displayName) && Objects.equals(analytics, that.analytics) ); }
@Override public int hashCode() { return Objects.hash(id, name, description, type, required, display, displayName, analytics); } @Override public String toString() { return ( "VariableDefinitionImpl{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", type='" + type + '\'' + ", required=" + required + ", display=" + display + ", displayName='" + displayName + '\'' + ", analytics='" + analytics + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\VariableDefinitionImpl.java
1
请在Spring Boot框架中完成以下Java代码
private Properties getContext() { Check.assumeNotNull(_ctx, "ctx not null"); return _ctx; } public JXlsExporter setLoader(final ClassLoader loader) { this._loader = loader; return this; } public ClassLoader getLoader() { return _loader == null ? getClass().getClassLoader() : _loader; } public JXlsExporter setAD_Language(final String adLanguage) { this._adLanguage = adLanguage; return this; } private Language getLanguage() { if (!Check.isEmpty(_adLanguage, true)) { return Language.getLanguage(_adLanguage); } return Env.getLanguage(getContext()); } public Locale getLocale() { final Language language = getLanguage(); if (language != null) { return language.getLocale(); } return Locale.getDefault(); } public JXlsExporter setTemplateResourceName(final String templateResourceName) { this._templateResourceName = templateResourceName; return this; } private InputStream getTemplate() { if (_template != null) { return _template; } if (!Check.isEmpty(_templateResourceName, true)) { final ClassLoader loader = getLoader(); final InputStream template = loader.getResourceAsStream(_templateResourceName); if (template == null) { throw new JXlsExporterException("Could not find template for name: " + _templateResourceName + " using " + loader); } return template; } throw new JXlsExporterException("Template is not configured"); } public JXlsExporter setTemplate(final InputStream template)
{ this._template = template; return this; } private IXlsDataSource getDataSource() { Check.assumeNotNull(_dataSource, "dataSource not null"); return _dataSource; } public JXlsExporter setDataSource(final IXlsDataSource dataSource) { this._dataSource = dataSource; return this; } public JXlsExporter setResourceBundle(final ResourceBundle resourceBundle) { this._resourceBundle = resourceBundle; return this; } private ResourceBundle getResourceBundle() { if (_resourceBundle != null) { return _resourceBundle; } if (!Check.isEmpty(_templateResourceName, true)) { String baseName = null; try { final int dotIndex = _templateResourceName.lastIndexOf('.'); baseName = dotIndex <= 0 ? _templateResourceName : _templateResourceName.substring(0, dotIndex); return ResourceBundle.getBundle(baseName, getLocale(), getLoader()); } catch (final MissingResourceException e) { logger.debug("No resource found for {}", baseName); } } return null; } public Map<String, String> getResourceBundleAsMap() { final ResourceBundle bundle = getResourceBundle(); if (bundle == null) { return ImmutableMap.of(); } return ResourceBundleMapWrapper.of(bundle); } public JXlsExporter setProperty(@NonNull final String name, @NonNull final Object value) { Check.assumeNotEmpty(name, "name not empty"); _properties.put(name, value); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\JXlsExporter.java
2
请完成以下Java代码
public static AttributesKeyPattern attributeId(@NonNull final AttributeId attributeId) { return ofPart(AttributesKeyPartPattern.ofAttributeId(attributeId)); } @Getter private final ImmutableList<AttributesKeyPartPattern> partPatterns; private String _sqlLikeString; // lazy private AttributesKeyPattern(@NonNull final Collection<AttributesKeyPartPattern> partPatterns) { Check.assumeNotEmpty(partPatterns, "partPatterns is not empty"); this.partPatterns = partPatterns.stream() .sorted() .collect(ImmutableList.toImmutableList()); } private AttributesKeyPattern(@NonNull final AttributesKeyPartPattern partPattern) { this.partPatterns = ImmutableList.of(partPattern); } @Override @Deprecated public String toString() { final ToStringHelper builder = MoreObjects.toStringHelper(this) .omitNullValues(); if(isAll()) { builder.addValue("ALL"); } else if(isOther()) { builder.addValue("OTHERS"); } else if(isNone()) { builder.addValue("NONE"); } else // { builder.addValue(partPatterns); } return builder.toString(); } public boolean isAll() { return ALL.equals(this); } public boolean isOther() { return OTHER.equals(this); } private boolean isNone() { return NONE.equals(this); } public boolean isSpecific() { return !isAll() && !isOther() && !isNone(); } public String getSqlLikeString() { String sqlLikeString = _sqlLikeString; if (sqlLikeString == null) { sqlLikeString = _sqlLikeString = computeSqlLikeString(); } return sqlLikeString; } private String computeSqlLikeString() { final StringBuilder sb = new StringBuilder(); sb.append("%"); boolean lastCharIsWildcard = true; for (final AttributesKeyPartPattern partPattern : partPatterns) { final String partSqlLike = partPattern.getSqlLikePart(); if (lastCharIsWildcard) {
if (partSqlLike.startsWith("%")) { sb.append(partSqlLike.substring(1)); } else { sb.append(partSqlLike); } } else { if (partSqlLike.startsWith("%")) { sb.append(partSqlLike); } else { sb.append("%").append(partSqlLike); } } lastCharIsWildcard = partSqlLike.endsWith("%"); } if (!lastCharIsWildcard) { sb.append("%"); } return sb.toString(); } public boolean matches(@NonNull final AttributesKey attributesKey) { for (final AttributesKeyPartPattern partPattern : partPatterns) { boolean partPatternMatched = false; if (AttributesKey.NONE.getAsString().equals(attributesKey.getAsString())) { partPatternMatched = partPattern.matches(AttributesKeyPart.NONE); } else { for (final AttributesKeyPart part : attributesKey.getParts()) { if (partPattern.matches(part)) { partPatternMatched = true; break; } } } if (!partPatternMatched) { return false; } } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPattern.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "http://localhost:8182/management/jobs/8") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "3") public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } @ApiModelProperty(example = "null") public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } @ApiModelProperty(example = "cmmn") public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @ApiModelProperty(example = "async-history") public String getJobHandlerType() { return jobHandlerType; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; }
@ApiModelProperty(example = "myCfg") public String getJobHandlerConfiguration() { return jobHandlerConfiguration; } public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } @ApiModelProperty(example = "myAdvancedCfg") public String getAdvancedJobHandlerConfiguration() { return advancedJobHandlerConfiguration; } public void setAdvancedJobHandlerConfiguration(String advancedJobHandlerConfiguration) { this.advancedJobHandlerConfiguration = advancedJobHandlerConfiguration; } @ApiModelProperty(example = "custom value") public String getCustomValues() { return customValues; } public void setCustomValues(String customValues) { this.customValues = customValues; } @ApiModelProperty(example = "node1") public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\HistoryJobResponse.java
2
请在Spring Boot框架中完成以下Java代码
public String getToken(HttpServletRequest request) { return TokenUtils.getTokenByRequest(request); } @Override public String getUsername(String token) { return JwtUtil.getUsername(token); } @Override public String[] getRoles(String token) { String username = JwtUtil.getUsername(token); Set roles = sysBaseApi.getUserRoleSet(username); if(CollectionUtils.isEmpty(roles)){ return null; } return (String[]) roles.toArray(new String[roles.size()]); } @Override public Boolean verifyToken(String token) { return TokenUtils.verifyToken(token, sysBaseApi, redisUtil); } @Override public Map<String, Object> getUserInfo(String token) { Map<String, Object> map = new HashMap(5); String username = JwtUtil.getUsername(token); //此处通过token只能拿到一个信息 用户账号 后面的就是根据账号获取其他信息 查询数据或是走redis 用户根据自身业务可自定义 SysUserCacheInfo userInfo = null; try { userInfo = sysBaseApi.getCacheUser(username); } catch (Exception e) { log.error("获取用户信息异常:"+ e.getMessage()); return map; } //设置账号名 map.put(SYS_USER_CODE, userInfo.getSysUserCode()); //设置部门编码 map.put(SYS_ORG_CODE, userInfo.getSysOrgCode()); // 将所有信息存放至map 解析sql/api会根据map的键值解析 return map;
} /** * 将jeecgboot平台的权限传递给积木报表 * @param token * @return */ @Override public String[] getPermissions(String token) { // 获取用户信息 String username = JwtUtil.getUsername(token); SysUserCacheInfo userInfo = null; try { userInfo = sysBaseApi.getCacheUser(username); } catch (Exception e) { log.error("获取用户信息异常:"+ e.getMessage()); } if(userInfo == null){ return null; } // 查询权限 Set<String> userPermissions = sysBaseApi.getUserPermissionSet(userInfo.getSysUserId()); if(CollectionUtils.isEmpty(userPermissions)){ return null; } return userPermissions.toArray(new String[0]); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\config\jimureport\JimuReportTokenService.java
2
请完成以下Java代码
public boolean isHandled(final GenericDataExportAuditRequest genericDataExportAuditRequest) { final AntPathMatcher antPathMatcher = new AntPathMatcher(); return Arrays.stream(HANDLING_UNITS_RESOURCES) .anyMatch(resource -> antPathMatcher.match(resource, genericDataExportAuditRequest.getRequestURI())); } private void auditHUResponse( @NonNull final JsonGetSingleHUResponse jsonGetSingleHUResponse, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { final JsonHU jsonHU = jsonGetSingleHUResponse.getResult(); auditHU(jsonHU, /*parentExportAuditId*/ null, externalSystemParentConfigId, pInstanceId); } private void auditHU( @NonNull final JsonHU jsonHU, @Nullable final DataExportAuditId parentExportAuditId, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { if(jsonHU.getId() == null) { return;
} final HuId huId = HuId.ofObject(jsonHU.getId()); final Action exportAction = parentExportAuditId != null ? Action.AlongWithParent : Action.Standalone; final DataExportAuditRequest huDataExportAuditRequest = DataExportAuditRequest.builder() .tableRecordReference(TableRecordReference.of(I_M_HU.Table_Name, huId.getRepoId())) .action(exportAction) .externalSystemConfigId(externalSystemParentConfigId) .adPInstanceId(pInstanceId) .parentExportAuditId(parentExportAuditId) .build(); final DataExportAuditId dataExportAuditId = dataExportAuditService.createExportAudit(huDataExportAuditRequest); if (jsonHU.getIncludedHUs() == null) { return; } jsonHU.getIncludedHUs().forEach(includedHU -> auditHU(includedHU, dataExportAuditId, externalSystemParentConfigId, pInstanceId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\HUAuditService.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalReferenceQuery { @NonNull OrgId orgId; @NonNull ExternalSystem externalSystem; @NonNull IExternalReferenceType externalReferenceType; @Nullable String externalReference; @Nullable MetasfreshId metasfreshId; @Builder public ExternalReferenceQuery( @NonNull final OrgId orgId, @NonNull final ExternalSystem externalSystem, @NonNull final IExternalReferenceType externalReferenceType, @Nullable final String externalReference, @Nullable final MetasfreshId metasfreshId) { if (externalReference == null && metasfreshId == null) { throw new AdempiereException("externalReference && metasfreshId cannot be both null!"); } if (externalReference != null && metasfreshId != null) { throw new AdempiereException("Only one of externalReference && metasfreshId must be provided!"); } this.orgId = orgId; this.externalSystem = externalSystem; this.externalReferenceType = externalReferenceType; this.externalReference = externalReference; this.metasfreshId = metasfreshId; } public boolean matches(@NonNull final ExternalReference externalReference) {
boolean matches = this.externalReferenceType.equals(externalReference.getExternalReferenceType()) && this.orgId.equals(externalReference.getOrgId()) && this.externalSystem.equals(externalReference.getExternalSystem()); if (this.externalReference != null) { matches = matches && this.externalReference.equals(externalReference.getExternalReference()); } if (this.metasfreshId != null) { matches = matches && this.metasfreshId.getValue() == externalReference.getRecordId(); } return matches; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalReferenceQuery.java
2
请在Spring Boot框架中完成以下Java代码
public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; ownerSet = true; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; assigneeSet = true; } public String getDelegationState() { return delegationState; } public void setDelegationState(String delegationState) { this.delegationState = delegationState; delegationStateSet = true; } public String getName() { return name; } public void setName(String name) { this.name = name; nameSet = true; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; descriptionSet = true; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; duedateSet = true; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; prioritySet = true; } 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 class SysDepartRolePermission { /**id*/ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "id") private java.lang.String id; /**部门id*/ @Excel(name = "部门id", width = 15) @Schema(description = "部门id") private java.lang.String departId; /**角色id*/ @Excel(name = "角色id", width = 15) @Schema(description = "角色id") private java.lang.String roleId; /**权限id*/ @Excel(name = "权限id", width = 15) @Schema(description = "权限id") private java.lang.String permissionId; /**dataRuleIds*/
@Excel(name = "dataRuleIds", width = 15) @Schema(description = "dataRuleIds") private java.lang.String dataRuleIds; /** 操作时间 */ @Excel(name = "操作时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") @Schema(description = "操作时间") private java.util.Date operateDate; /** 操作ip */ private java.lang.String operateIp; public SysDepartRolePermission() { } public SysDepartRolePermission(String roleId, String permissionId) { this.roleId = roleId; this.permissionId = permissionId; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysDepartRolePermission.java
1
请完成以下Java代码
public class JsonRequestPriceListVersion { @ApiModelProperty(required = true, value = PRICE_LIST_IDENTIFIER) private String priceListIdentifier; @ApiModelProperty(required = true) private String orgCode; @ApiModelProperty(required = true) private Instant validFrom; @Getter private Boolean active; @ApiModelProperty(hidden = true) @Getter private boolean activeSet; @Getter private String description; @ApiModelProperty(hidden = true) @Getter private boolean descriptionSet; @Getter private SyncAdvise syncAdvise; @ApiModelProperty(hidden = true) @Getter private boolean syncAdviseSet; public void setOrgCode(final String orgCode) { this.orgCode = orgCode; } @NonNull public String getOrgCode() { return orgCode; } public void setPriceListIdentifier(final String priceListIdentifier) { this.priceListIdentifier = priceListIdentifier; } @NonNull
public String getPriceListIdentifier() { return priceListIdentifier; } public void setDescription(final String description) { this.description = description; this.descriptionSet = true; } public void setValidFrom(final Instant validFrom) { this.validFrom = validFrom; } @NonNull public Instant getValidFrom() { return validFrom; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-pricing\src\main\java\de\metas\common\pricing\v2\pricelist\request\JsonRequestPriceListVersion.java
1
请完成以下Java代码
public class ZipPostProcessor extends AbstractDeflaterPostProcessor { public ZipPostProcessor() { } public ZipPostProcessor(boolean autoDecompress) { super(autoDecompress); } @Override protected OutputStream getCompressorStream(OutputStream zipped) throws IOException { ZipOutputStream zipper = new SettableLevelZipOutputStream(zipped, getLevel()); zipper.putNextEntry(new ZipEntry("amqp")); return zipper; }
@Override protected String getEncoding() { return "zip"; } private static final class SettableLevelZipOutputStream extends ZipOutputStream { SettableLevelZipOutputStream(OutputStream zipped, int level) { super(zipped); this.setLevel(level); } } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\postprocessor\ZipPostProcessor.java
1
请完成以下Java代码
public boolean hasTaskFormKeyChanged() { return hasStringFieldChanged(TaskInfo::getFormKey); } public boolean hasTaskParentIdChanged() { return hasStringFieldChanged(TaskInfo::getParentTaskId); } private boolean hasStringFieldChanged(Function<TaskInfo, String> comparableTaskGetter) { if (originalTask != null && updatedTask != null) { return !StringUtils.equals( comparableTaskGetter.apply(originalTask), comparableTaskGetter.apply(updatedTask) ); } return false; } private boolean hasIntegerFieldChanged(Function<TaskInfo, Integer> comparableTaskGetter) { if (originalTask != null && updatedTask != null) { return !Objects.equals(comparableTaskGetter.apply(originalTask), comparableTaskGetter.apply(updatedTask)); } return false; } private boolean hasDateFieldChanged(Function<TaskInfo, Date> comparableTaskGetter) { if (originalTask != null && updatedTask != null) { Date originalDate = comparableTaskGetter.apply(originalTask); Date newDate = comparableTaskGetter.apply(updatedTask); return ( (originalDate == null && newDate != null) || (originalDate != null && newDate == null) ||
(originalDate != null && !originalDate.equals(newDate)) ); } return false; } private TaskInfo copyInformationFromTaskInfo(TaskInfo task) { if (task != null) { TaskEntityImpl duplicatedTask = new TaskEntityImpl(); duplicatedTask.setName(task.getName()); duplicatedTask.setDueDate(task.getDueDate()); duplicatedTask.setDescription(task.getDescription()); duplicatedTask.setId(task.getId()); duplicatedTask.setOwner(task.getOwner()); duplicatedTask.setPriority(task.getPriority()); duplicatedTask.setCategory(task.getCategory()); duplicatedTask.setFormKey(task.getFormKey()); duplicatedTask.setAssignee(task.getAssignee()); duplicatedTask.setTaskDefinitionKey(task.getTaskDefinitionKey()); duplicatedTask.setParentTaskId(task.getParentTaskId()); return duplicatedTask; } throw new IllegalArgumentException("task must be non-null"); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\task\TaskComparatorImpl.java
1
请完成以下Java代码
public void execute() { build().execute(); } } public void execute() { final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(sourceModel); if (asiAware == null) { return; } final ProductId productId = ProductId.ofRepoIdOrNull(asiAware.getM_Product_ID()); if (productId == null) { return; } final AttributeId attributeId = attributeDAO.retrieveActiveAttributeIdByValueOrNull(attributeCode); if (attributeId == null)
{ return; } attributeSetInstanceBL.getCreateASI(asiAware); final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNull(asiAware.getM_AttributeSetInstance_ID()); final I_M_AttributeInstance ai = attributeSetInstanceBL.getAttributeInstance(asiId, attributeId); if (ai != null) { // If it was set, just leave it as it is return; } attributeSetInstanceBL.getCreateAttributeInstance(asiId, attributeId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\UpdateASIAttributeFromModelCommand.java
1
请完成以下Java代码
protected boolean beforeDelete () { return delete_Accounting("M_Product_Category_Acct"); } // beforeDelete /** * FiFo Material Movement Policy * @return true if FiFo */ public boolean isFiFo() { return MMPOLICY_FiFo.equals(getMMPolicy()); } // isFiFo static void assertNoLoopInTree(final I_M_Product_Category productCategory) { if (hasLoopInTree(productCategory)) { throw new AdempiereException("@ProductCategoryLoopDetected@"); } } /** * Loop detection of product category tree. */ private static boolean hasLoopInTree (final I_M_Product_Category productCategory) { final int productCategoryId = productCategory.getM_Product_Category_ID(); final int newParentCategoryId = productCategory.getM_Product_Category_Parent_ID(); // get values ResultSet rs = null; PreparedStatement pstmt = null; final String sql = " SELECT M_Product_Category_ID, M_Product_Category_Parent_ID FROM M_Product_Category"; final Vector<SimpleTreeNode> categories = new Vector<>(100); try { pstmt = DB.prepareStatement(sql, null); rs = pstmt.executeQuery(); while (rs.next()) { if (rs.getInt(1) == productCategoryId) categories.add(new SimpleTreeNode(rs.getInt(1), newParentCategoryId)); categories.add(new SimpleTreeNode(rs.getInt(1), rs.getInt(2))); } if (hasLoop(newParentCategoryId, categories, productCategoryId)) return true; } catch (final SQLException e) { log.error(sql, e); return true; } finally { DB.close(rs, pstmt); } return false; } // hasLoopInTree /** * Recursive search for parent nodes - climbs the to the root. * If there is a circle there is no root but it comes back to the start node. */ private static boolean hasLoop(final int parentCategoryId, final Vector<SimpleTreeNode> categories, final int loopIndicatorId) {
final Iterator<SimpleTreeNode> iter = categories.iterator(); boolean ret = false; while (iter.hasNext()) { final SimpleTreeNode node = iter.next(); if(node.getNodeId()==parentCategoryId){ if (node.getParentId()==0) { //root node, all fine return false; } if(node.getNodeId()==loopIndicatorId){ //loop found return true; } ret = hasLoop(node.getParentId(), categories, loopIndicatorId); } } return ret; } //hasLoop /** * Simple class for tree nodes. * @author Karsten Thiemann, kthiemann@adempiere.org * */ private static class SimpleTreeNode { /** id of the node */ private final int nodeId; /** id of the nodes parent */ private final int parentId; public SimpleTreeNode(final int nodeId, final int parentId) { this.nodeId = nodeId; this.parentId = parentId; } public int getNodeId() { return nodeId; } public int getParentId() { return parentId; } } } // MProductCategory
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MProductCategory.java
1
请完成以下Java代码
private void toggleCurrency() { if (currencyPanel.isVisible()) { currencyPanel.setVisible(false); } else { if (!m_currencyOK) { loadCurrency(); } currencyPanel.setVisible(true); } pack(); } // toggleCurrency /** * Load Currency */ private void loadCurrency() { // Get Default int C_Currency_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Currency_ID"); if (C_Currency_ID == 0) { C_Currency_ID = Env.getContextAsInt(Env.getCtx(), "$C_Currency_ID"); } String sql = "SELECT C_Currency_ID, ISO_Code FROM C_Currency " + "WHERE IsActive='Y' ORDER BY 2"; KeyNamePair defaultValue = null; try { Statement stmt = DB.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { int id = rs.getInt("C_Currency_ID"); String s = rs.getString("ISO_Code"); KeyNamePair p = new KeyNamePair(id, s); curFrom.addItem(p); curTo.addItem(p); // Default if (id == C_Currency_ID) { defaultValue = p; } } rs.close(); stmt.close(); } catch (SQLException e) { log.error("Calculator.loadCurrency", e); } // Set Defaults if (defaultValue != null) { curFrom.setSelectedItem(defaultValue); curTo.setSelectedItem(defaultValue); } // Set Listener curTo.addActionListener(this); m_currencyOK = true; } // loadCurrency /** * Return Number * @return result */ public BigDecimal getNumber() { if (m_abort) { return null; } return m_number; } // getNumber public boolean isDisposeOnEqual() { return p_disposeOnEqual; } public void setDisposeOnEqual(boolean b) { p_disposeOnEqual = b; } /*************************************************************************/
/** * KeyPressed Listener * @param e event */ @Override public void keyPressed(KeyEvent e) { // sequence: pressed - typed(no KeyCode) - released char input = e.getKeyChar(); int code = e.getKeyCode(); e.consume(); // does not work on JTextField if (code == KeyEvent.VK_DELETE) { input = 'A'; } else if (code == KeyEvent.VK_BACK_SPACE) { input = 'C'; } else if (code == KeyEvent.VK_ENTER) { input = '='; } else if (code == KeyEvent.VK_CANCEL || code == KeyEvent.VK_ESCAPE) { m_abort = true; dispose(); return; } handleInput(input); } /** * KeyTyped Listener (nop) * @param e event */ @Override public void keyTyped(KeyEvent e) {} /** * KeyReleased Listener (nop) * @param e event */ @Override public void keyReleased(KeyEvent e) {} } // Calculator
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\Calculator.java
1
请完成以下Java代码
public class ApplicationClient { private Socket clientSocket; private PrintWriter out; private BufferedReader in; public void connect(String ip, int port) throws IOException { clientSocket = new Socket(ip, port); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } public void sendGreetings(String msg) throws IOException { out.println(msg); String reply = in.readLine();
System.out.println("Reply received from the server :: " + reply); } public void disconnect() throws IOException { in.close(); out.close(); clientSocket.close(); } public static void main(String[] args) throws IOException { ApplicationClient client = new ApplicationClient(); client.connect(args[0], Integer.parseInt(args[1])); // IP address and port number of the server client.sendGreetings(args[2]); // greetings message client.disconnect(); } }
repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\clientaddress\ApplicationClient.java
1
请完成以下Java代码
public Collection<I_M_PriceList_Version> getPriceListVersions() { return getPricingInfo().getPriceListVersions(); } @Override public IVendorInvoicingInfo getVendorInvoicingInfoForPLV(final I_M_PriceList_Version plv) { final MaterialTrackingAsVendorInvoicingInfo materialTrackingAsVendorInvoicingInfo = new MaterialTrackingAsVendorInvoicingInfo(getM_Material_Tracking()); materialTrackingAsVendorInvoicingInfo.setM_PriceList_Version(plv); return materialTrackingAsVendorInvoicingInfo; } private MaterialTrackingDocumentsPricingInfo getPricingInfo() { if (pricingInfo == null) { final I_M_Material_Tracking materialTracking = getM_Material_Tracking(); final I_C_Flatrate_Term flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID()); final I_M_PricingSystem pricingSystem = priceListsRepo.getPricingSystemById(PricingSystemId.ofRepoIdOrNull(flatrateTerm .getC_Flatrate_Conditions() .getM_PricingSystem_ID())); pricingInfo = MaterialTrackingDocumentsPricingInfo .builder() .setM_Material_Tracking(materialTracking) // note that we give to the builder also those that were already processed into invoice candidates, // because it needs that information to distinguish InOutLines that were not yet issued // from those that were issued and whose issue-PP_Order already have IsInvoiceCanidate='Y' .setAllProductionOrders(getAllProductionOrders()) .setNotYetInvoicedProductionOrders(getNotInvoicedProductionOrders()) .setM_PricingSystem(pricingSystem) .build(); } return pricingInfo; } @Override public List<IQualityInspectionOrder> getProductionOrdersForPLV(final I_M_PriceList_Version plv) { return getPricingInfo().getQualityInspectionOrdersForPLV(plv); } @Override public IVendorReceipt<I_M_InOutLine> getVendorReceiptForPLV(final I_M_PriceList_Version plv) { return getPricingInfo().getVendorReceiptForPLV(plv); } @Override public IQualityInspectionOrder getQualityInspectionOrderOrNull() { final List<IQualityInspectionOrder> qualityInspectionOrders = getQualityInspectionOrders(); if (qualityInspectionOrders.isEmpty()) { return null;
} // as of now, return the last one // TODO: consider returning an aggregated/averaged one return qualityInspectionOrders.get(qualityInspectionOrders.size() - 1); } @Override public void linkModelToMaterialTracking(final Object model) { final I_M_Material_Tracking materialTracking = getM_Material_Tracking(); materialTrackingBL.linkModelToMaterialTracking( MTLinkRequest.builder() .model(model) .materialTrackingRecord(materialTracking) .build()); } @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\MaterialTrackingDocuments.java
1
请在Spring Boot框架中完成以下Java代码
public Declarables topicBindings() { Queue topicQueue1 = new Queue(TOPIC_QUEUE_1_NAME, NON_DURABLE); Queue topicQueue2 = new Queue(TOPIC_QUEUE_2_NAME, NON_DURABLE); TopicExchange topicExchange = new TopicExchange(TOPIC_EXCHANGE_NAME, NON_DURABLE, false); return new Declarables(topicQueue1, topicQueue2, topicExchange, BindingBuilder .bind(topicQueue1) .to(topicExchange) .with(BINDING_PATTERN_IMPORTANT), BindingBuilder .bind(topicQueue2) .to(topicExchange) .with(BINDING_PATTERN_ERROR)); }
@Bean public Declarables fanoutBindings() { Queue fanoutQueue1 = new Queue(FANOUT_QUEUE_1_NAME, NON_DURABLE); Queue fanoutQueue2 = new Queue(FANOUT_QUEUE_2_NAME, NON_DURABLE); FanoutExchange fanoutExchange = new FanoutExchange(FANOUT_EXCHANGE_NAME, NON_DURABLE, false); return new Declarables(fanoutQueue1, fanoutQueue2, fanoutExchange, BindingBuilder .bind(fanoutQueue1) .to(fanoutExchange), BindingBuilder .bind(fanoutQueue2) .to(fanoutExchange)); } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\broadcast\BroadcastConfig.java
2
请在Spring Boot框架中完成以下Java代码
public ToDo getOne(Long aLong) { return null; } @Override public <S extends ToDo> Optional<S> findOne(Example<S> example) { return Optional.empty(); } @Override public <S extends ToDo> List<S> findAll(Example<S> example) { return null; } @Override public <S extends ToDo> List<S> findAll(Example<S> example, Sort sort) { return null; }
@Override public <S extends ToDo> Page<S> findAll(Example<S> example, Pageable pageable) { return null; } @Override public <S extends ToDo> long count(Example<S> example) { return 0; } @Override public <S extends ToDo> boolean exists(Example<S> example) { return false; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\3.TodoProjectDB\src\main\java\spring\project\repository\LogicRepository.java
2
请在Spring Boot框架中完成以下Java代码
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client oAuth2Client) { OAuth2MapperConfig config = oAuth2Client.getMapperConfig(); Map<String, Object> attributes = updateAttributesFromRequestParams(request, token.getPrincipal().getAttributes()); String email = BasicMapperUtils.getStringAttributeByKey(attributes, config.getBasic().getEmailAttributeKey()); OAuth2User oauth2User = BasicMapperUtils.getOAuth2User(email, attributes, config); return getOrCreateSecurityUserFromOAuth2User(oauth2User, oAuth2Client); } private static Map<String, Object> updateAttributesFromRequestParams(HttpServletRequest request, Map<String, Object> attributes) { Map<String, Object> updated = attributes; MultiValueMap<String, String> params = toMultiMap(request.getParameterMap()); String userValue = params.getFirst(USER); if (StringUtils.hasText(userValue)) { JsonNode user = null; try { user = JacksonUtil.toJsonNode(userValue); } catch (Exception e) {} if (user != null) { updated = new HashMap<>(attributes); if (user.has(NAME)) { JsonNode name = user.get(NAME); if (name.isObject()) { JsonNode firstName = name.get(FIRST_NAME); if (firstName != null && firstName.isTextual()) { updated.put(FIRST_NAME, firstName.asText()); } JsonNode lastName = name.get(LAST_NAME); if (lastName != null && lastName.isTextual()) { updated.put(LAST_NAME, lastName.asText());
} } } if (user.has(EMAIL)) { JsonNode email = user.get(EMAIL); if (email != null && email.isTextual()) { updated.put(EMAIL, email.asText()); } } } } return updated; } private static MultiValueMap<String, String> toMultiMap(Map<String, String[]> map) { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(map.size()); map.forEach((key, values) -> { if (values.length > 0) { for (String value : values) { params.add(key, value); } } }); return params; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\AppleOAuth2ClientMapper.java
2
请在Spring Boot框架中完成以下Java代码
public IEditablePricingContext setForcePricingConditionsBreak(@Nullable final PricingConditionsBreak forcePricingConditionsBreak) { this.forcePricingConditionsBreak = forcePricingConditionsBreak; return this; } @Override public Optional<IAttributeSetInstanceAware> getAttributeSetInstanceAware() { final Object referencedObj = getReferencedObject(); if (referencedObj == null) { return Optional.empty(); } final IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class); final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(referencedObj); return Optional.ofNullable(asiAware); }
@Override public Quantity getQuantity() { final BigDecimal ctxQty = getQty(); if (ctxQty == null) { return null; } final UomId ctxUomId = getUomId(); if (ctxUomId == null) { return null; } return Quantitys.of(ctxQty, ctxUomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingContext.java
2
请完成以下Java代码
public Integer getConnectorPort() { return connectorPort; } public void setConnectorPort(Integer connectorPort) { this.connectorPort = connectorPort; } @Override public void beforeInit(AbstractEngineConfiguration engineConfiguration) { // nothing to do } @Override public void configure(AbstractEngineConfiguration engineConfiguration) {
try { this.processEngineConfig = (ProcessEngineConfiguration) engineConfiguration; if (!disabled) { managementAgent = new DefaultManagementAgent(this); managementAgent.doStart(); managementAgent.findAndRegisterMbeans(); } } catch (Exception e) { LOGGER.warn("error in initializing jmx. Continue with partial or no JMX configuration", e); } } }
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\JMXConfigurator.java
1
请完成以下Java代码
private static DocTypePrintOptionsKey toDocTypePrintOptionsKey(@NonNull final I_C_DocType_PrintOptions record) { final DocTypeId docTypeId = DocTypeId.ofRepoId(record.getC_DocType_ID()); final DocumentReportFlavor flavor = DocumentReportFlavor.ofNullableCode(record.getDocumentFlavor()); return DocTypePrintOptionsKey.of(docTypeId, flavor); } @NonNull private static DocumentPrintOptions toDocumentPrintOptions(@NonNull final I_C_DocType_PrintOptions record) { return DocumentPrintOptions.builder() .sourceName("DocType options: C_DocType_ID=" + record.getC_DocType_ID() + ", flavor=" + DocumentReportFlavor.ofNullableCode(record.getDocumentFlavor())) .option(DocumentPrintOptions.OPTION_IsPrintLogo, record.isPRINTER_OPTS_IsPrintLogo()) .option(DocumentPrintOptions.OPTION_IsPrintTotals, record.isPRINTER_OPTS_IsPrintTotals()) .build(); } @Value(staticConstructor = "of") private static class DocTypePrintOptionsKey { @NonNull DocTypeId docTypeId; @Nullable DocumentReportFlavor flavor; } private static class DocTypePrintOptionsMap { public static final DocTypePrintOptionsMap EMPTY = new DocTypePrintOptionsMap(ImmutableMap.of());
private final ImmutableMap<DocTypePrintOptionsKey, DocumentPrintOptions> map; DocTypePrintOptionsMap(final Map<DocTypePrintOptionsKey, DocumentPrintOptions> map) { this.map = ImmutableMap.copyOf(map); } public DocumentPrintOptions getByDocTypeAndFlavor( @NonNull final DocTypeId docTypeId, @NonNull final DocumentReportFlavor flavor) { return CoalesceUtil.coalesceSuppliers( () -> map.get(DocTypePrintOptionsKey.of(docTypeId, flavor)), () -> map.get(DocTypePrintOptionsKey.of(docTypeId, null)), () -> DocumentPrintOptions.NONE); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocTypePrintOptionsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public Object bodyJson(HttpServletRequest request) { printReq(request); return null; } /** * text/xml * * @return */ @RequestMapping("textXml") public Object textXml(HttpServletRequest request) { printReq(request); return null; } private void printReq(HttpServletRequest request) { //获取请求头信息 Enumeration headerNames = request.getHeaderNames(); //使用循环遍历请求头,并通过getHeader()方法获取一个指定名称的头字段 while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); System.out.println(headerName + " : " + request.getHeader(headerName)); } System.out.println("============================================================================================"); //获取请求行的相关信息 System.out.println("getMethod:" + request.getMethod()); System.out.println("getQueryString:" + request.getQueryString()); System.out.println("getProtocol:" + request.getProtocol()); System.out.println("getContextPath" + request.getContextPath()); System.out.println("getPathInfo:" + request.getPathInfo()); System.out.println("getPathTranslated:" + request.getPathTranslated()); System.out.println("getServletPath:" + request.getServletPath()); System.out.println("getRemoteAddr:" + request.getRemoteAddr()); System.out.println("getRemoteHost:" + request.getRemoteHost()); System.out.println("getRemotePort:" + request.getRemotePort()); System.out.println("getLocalAddr:" + request.getLocalAddr()); System.out.println("getLocalName:" + request.getLocalName()); System.out.println("getLocalPort:" + request.getLocalPort()); System.out.println("getServerName:" + request.getServerName()); System.out.println("getServerPort:" + request.getServerPort()); System.out.println("getScheme:" + request.getScheme()); System.out.println("getRequestURL:" + request.getRequestURL());
Enumeration<?> temp = request.getParameterNames(); if (null != temp) { while (temp.hasMoreElements()) { String en = (String) temp.nextElement(); String value = request.getParameter(en); System.out.println(en + "===>" + value); } } // StringBuffer jb = new StringBuffer(); // String line = null; // try { // BufferedReader reader = request.getReader(); // while ((line = reader.readLine()) != null) // jb.append(line); // } catch (Exception e) { /*report an error*/ } // // try { // System.out.println(JSONUtil.toJsonPrettyStr(jb.toString())); // } catch (Exception e) { // // crash and burn // e.printStackTrace(); // } } }
repos\spring-boot-quick-master\quick-hmac\src\main\java\com\quick\hmac\controller\PostController.java
2
请完成以下Java代码
public int getParent_HU_Trx_Line_ID() { return get_ValueAsInt(COLUMNNAME_Parent_HU_Trx_Line_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void 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; } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Trx_Line getReversalLine() { return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class); } @Override public void setReversalLine(final de.metas.handlingunits.model.I_M_HU_Trx_Line ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class, ReversalLine); } @Override public void setReversalLine_ID (final int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID);
} @Override public int getReversalLine_ID() { return get_ValueAsInt(COLUMNNAME_ReversalLine_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Item getVHU_Item() { return get_ValueAsPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class); } @Override public void setVHU_Item(final de.metas.handlingunits.model.I_M_HU_Item VHU_Item) { set_ValueFromPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, VHU_Item); } @Override public void setVHU_Item_ID (final int VHU_Item_ID) { if (VHU_Item_ID < 1) set_Value (COLUMNNAME_VHU_Item_ID, null); else set_Value (COLUMNNAME_VHU_Item_ID, VHU_Item_ID); } @Override public int getVHU_Item_ID() { return get_ValueAsInt(COLUMNNAME_VHU_Item_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trx_Line.java
1
请完成以下Java代码
public CacheInvalidateMultiRequestsCollector collect(@NonNull final CacheInvalidateMultiRequest multiRequest) { multiRequest.getRequests().forEach(this::collect); return this; } private void collect(@NonNull final CacheInvalidateRequest request) { logger.trace("Collecting request on `{}`: {}", name, request); final TableRecordReference rootDocumentRef = request.getRootRecordOrNull(); if (rootDocumentRef == null) { return; } // // If we are still collecting document, we will collect this event. // If not, we will have to fire this event directly. final DocumentToInvalidateMap documentsToCollect = this.documents; final DocumentToInvalidateMap documents; final boolean autoflush; if (documentsToCollect != null) { documents = documentsToCollect; autoflush = false; } else { // Basically this shall not happen, but for some reason it's happening. // So, for that case, instead of just ignoring event, better to fire it directly. documents = new DocumentToInvalidateMap(); autoflush = true; } // final DocumentToInvalidate documentToInvalidate = documents.getDocumentToInvalidate(rootDocumentRef); final String childTableName = request.getChildTableName(); if (childTableName == null) { documentToInvalidate.invalidateDocument(); } else if (request.isAllRecords()) { documentToInvalidate.invalidateAllIncludedDocuments(childTableName); // NOTE: as a workaround to solve the problem of https://github.com/metasfresh/metasfresh-webui-api/issues/851, // we are invalidating the whole root document to make sure that in case there were any virtual columns on header, // those get refreshed too. documentToInvalidate.invalidateDocument(); } else { final int childRecordId = request.getChildRecordId(); documentToInvalidate.addIncludedDocument(childTableName, childRecordId);
} // if (autoflush && !documents.isEmpty()) { logger.trace("Auto-flushing {} collected requests for on `{}`", documents.size(), name); DocumentCacheInvalidationDispatcher.this.resetAsync(documents); } } public void resetAsync() { final DocumentToInvalidateMap documents = this.documents; this.documents = null; // just to prevent adding more events if (documents == null) { // it was already executed return; } logger.trace("Flushing {} collected requests for on `{}`", documents.size(), name); if (documents.isEmpty()) { return; } DocumentCacheInvalidationDispatcher.this.resetAsync(documents); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\invalidation\DocumentCacheInvalidationDispatcher.java
1
请在Spring Boot框架中完成以下Java代码
public ExcelToMapListConverter build() { return new ExcelToMapListConverter(this); } /** * Sets the header prefix to be used if the header columns is null or black. * * Set it to <code>null</code> to turn it off and get rid of columns without header. * * @see #setDiscardNoNameHeaders() */ public Builder setNoNameHeaderPrefix(@Nullable final String noNameHeaderPrefix) { this.noNameHeaderPrefix = noNameHeaderPrefix; return this; } public Builder setDiscardNoNameHeaders() { setNoNameHeaderPrefix(null); return this; } /** * Sets if a cell value which is a null string (i.e. {@link ExcelToMapListConverter#NULLStringMarker}) shall be considered as <code>null</code>. */ public Builder setConsiderNullStringAsNull(final boolean considerNullStringAsNull) { this.considerNullStringAsNull = considerNullStringAsNull; return this; } public Builder setConsiderEmptyStringAsNull(final boolean considerEmptyStringAsNull) { this.considerEmptyStringAsNull = considerEmptyStringAsNull; return this; } public Builder setRowNumberMapKey(final String rowNumberMapKey) { this.rowNumberMapKey = rowNumberMapKey; return this; }
/** * Sets if we shall detect repeating headers and discard them. */ public Builder setDiscardRepeatingHeaders(final boolean discardRepeatingHeaders) { this.discardRepeatingHeaders = discardRepeatingHeaders; return this; } /** * If enabled, the XLS converter will look for first not null column and it will expect to have one of the codes from {@link RowType}. * If no row type would be found, the row would be ignored entirely. * * task 09045 */ public Builder setUseRowTypeColumn(final boolean useTypeColumn) { this.useTypeColumn = useTypeColumn; return this; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\ExcelToMapListConverter.java
2
请完成以下Java代码
public class LoginParam { @NotEmpty(message="姓名不能为空") private String loginName; @NotEmpty(message="密码不能为空") @Length(min=6,message="密码长度不能小于6位") private String password; public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; }
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "LoginParam{" + "loginName='" + loginName + '\'' + ", password='" + password + '\'' + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 5-7 课: 综合实战客户管理系统(一)\user-manage\src\main\java\com\neo\param\LoginParam.java
1
请完成以下Java代码
public HttpStatus getStatusCode() { return statusCode; } public Config setStatusCode(HttpStatus statusCode) { this.statusCode = statusCode; return this; } public @Nullable Boolean getDenyEmptyKey() { return denyEmptyKey; } public Config setDenyEmptyKey(Boolean denyEmptyKey) { this.denyEmptyKey = denyEmptyKey; return this; } public @Nullable String getEmptyKeyStatus() { return emptyKeyStatus; } public Config setEmptyKeyStatus(String emptyKeyStatus) { this.emptyKeyStatus = emptyKeyStatus; return this;
} @Override public void setRouteId(String routeId) { this.routeId = routeId; } @Override public @Nullable String getRouteId() { return this.routeId; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestRateLimiterGatewayFilterFactory.java
1
请完成以下Java代码
public static class CommandLineOptions { @Nullable String dbHost; @Nullable Integer dbPort; @Nullable String dbName; @Nullable String dbUser; @Nullable
String dbPassword; @Nullable String rabbitHost; @Nullable Integer rabbitPort; @Nullable String rabbitUser; @Nullable String rabbitPassword; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\CommandLineParser.java
1