instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class ClassPathChangedEvent extends ApplicationEvent {
private final Set<ChangedFiles> changeSet;
private final boolean restartRequired;
/**
* Create a new {@link ClassPathChangedEvent}.
* @param source the source of the event
* @param changeSet the changed files
* @param restartRequired if a restart is required due to the change
*/
public ClassPathChangedEvent(Object source, Set<ChangedFiles> changeSet, boolean restartRequired) {
super(source);
Assert.notNull(changeSet, "'changeSet' must not be null");
this.changeSet = changeSet;
this.restartRequired = restartRequired;
}
/**
* Return details of the files that changed.
* @return the changed files
*/
public Set<ChangedFiles> getChangeSet() {
return this.changeSet;
}
/**
* Return if an application restart is required due to the change.
* @return if an application restart is required
*/
public boolean isRestartRequired() {
return this.restartRequired;
}
@Override
public String toString() {
return new ToStringCreator(this).append("changeSet", this.changeSet)
.append("restartRequired", this.restartRequired)
.toString();
}
/**
* Return an overview of the changes that triggered this event.
* @return an overview of the changes
* @since 2.6.11
*/
public String overview() {
int added = 0;
int deleted = 0;
|
int modified = 0;
for (ChangedFiles changedFiles : this.changeSet) {
for (ChangedFile changedFile : changedFiles) {
Type type = changedFile.getType();
if (type == Type.ADD) {
added++;
}
else if (type == Type.DELETE) {
deleted++;
}
else if (type == Type.MODIFY) {
modified++;
}
}
}
int size = added + deleted + modified;
return String.format("%s (%s, %s, %s)", quantityOfUnit(size, "class path change"),
quantityOfUnit(added, "addition"), quantityOfUnit(deleted, "deletion"),
quantityOfUnit(modified, "modification"));
}
private String quantityOfUnit(int quantity, String unit) {
return quantity + " " + ((quantity != 1) ? unit + "s" : unit);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\classpath\ClassPathChangedEvent.java
| 1
|
请完成以下Java代码
|
public void setBackground (Color bg)
{
if (bg.equals(getBackground()))
return;
super.setBackground(bg);
} // setBackground
/**
* Set Editor to value
* @param value value of the editor
*/
@Override
public void setValue (Object value)
{
if (value == null)
setText("");
else
setText(value.toString());
} // setValue
/**
* Return Editor value
* @return current value
*/
@Override
public Object getValue()
{
return getText();
} // getValue
/**
* Return Display Value
* @return displayed String value
*/
@Override
public String getDisplay()
{
return getText();
} // getDisplay
/**
* key Pressed
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
* @param e
|
*/
@Override
public void keyPressed(KeyEvent e)
{
} // keyPressed
/**
* key Released
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
* @param e
*/
@Override
public void keyReleased(KeyEvent e)
{
} // keyReleased
/**
* key Typed
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
* @param e
*/
@Override
public void keyTyped(KeyEvent e)
{
} // keyTyped
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
@Override
public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)
{
// NOTE: overridden just to make it public
return super.processKeyBinding(ks, e, condition, pressed);
}
} // CTextField
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextField.java
| 1
|
请完成以下Java代码
|
public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne getMSV3_VerfuegbarkeitsanfrageEinzelne() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class);
}
@Override
public void setMSV3_VerfuegbarkeitsanfrageEinzelne(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne MSV3_VerfuegbarkeitsanfrageEinzelne)
{
set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class, MSV3_VerfuegbarkeitsanfrageEinzelne);
}
/** Set MSV3_VerfuegbarkeitsanfrageEinzelne.
@param MSV3_VerfuegbarkeitsanfrageEinzelne_ID MSV3_VerfuegbarkeitsanfrageEinzelne */
@Override
public void setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_ID)
{
if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_ID));
}
/** Get MSV3_VerfuegbarkeitsanfrageEinzelne.
@return MSV3_VerfuegbarkeitsanfrageEinzelne */
@Override
public int getMSV3_VerfuegbarkeitsanfrageEinzelne_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel.java
| 1
|
请完成以下Java代码
|
public Mono<MultipleArticlesView> findArticles(String tag, String author, String favoritedByUser, int offset, int limit, Optional<User> currentUser) {
return articlesFinder.findArticles(tag, author, favoritedByUser, offset, limit, currentUser);
}
public Mono<ArticleView> getArticle(String slug, Optional<User> currentUser) {
return articleRepository.findBySlug(slug)
.flatMap(article -> articleMapper.mapToArticleView(article, currentUser));
}
public Mono<ArticleView> updateArticle(String slug, UpdateArticleRequest request, User currentUser) {
return articleRepository.findBySlugOrFail(slug)
.map(article -> updateArticle(request, currentUser, article));
}
public Mono<Void> deleteArticle(String slug, User articleAuthor) {
return articleRepository.findBySlug(slug)
.flatMap(article -> {
if (!article.isAuthor(articleAuthor)) {
return Mono.error(new InvalidRequestException("Article", "only author can delete article"));
}
return articleRepository.deleteArticleBySlug(slug).then();
});
}
public Mono<CommentView> addComment(String slug, CreateCommentRequest request, User currentUser) {
return commentService.addComment(slug, request, currentUser);
}
public Mono<Void> deleteComment(String commentId, String slug, User user) {
return commentService.deleteComment(commentId, slug, user);
}
public Mono<MultipleCommentsView> getComments(String slug, Optional<User> user) {
return commentService.getComments(slug, user);
}
|
public Mono<ArticleView> favoriteArticle(String slug, User currentUser) {
return articleRepository.findBySlug(slug)
.map(article -> {
currentUser.favorite(article);
return ArticleView.ofOwnArticle(article, currentUser);
});
}
public Mono<ArticleView> unfavoriteArticle(String slug, User currentUser) {
return articleRepository.findBySlug(slug)
.map(article -> {
currentUser.unfavorite(article);
return ArticleView.ofOwnArticle(article, currentUser);
});
}
private ArticleView updateArticle(UpdateArticleRequest request, User currentUser, Article article) {
if (!article.isAuthor(currentUser)) {
throw new InvalidRequestException("Article", "only author can update article");
}
ofNullable(request.getBody())
.ifPresent(article::setBody);
ofNullable(request.getDescription())
.ifPresent(article::setDescription);
ofNullable(request.getTitle())
.ifPresent(article::setTitle);
return ArticleView.ofOwnArticle(article, currentUser);
}
}
|
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\ArticleFacade.java
| 1
|
请完成以下Java代码
|
public int getAD_WF_NodeNext_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_NodeNext_ID);
}
/**
* AndOr AD_Reference_ID=204
* Reference name: AD_Find AndOr
*/
public static final int ANDOR_AD_Reference_ID=204;
/** And = A */
public static final String ANDOR_And = "A";
/** OR = O */
public static final String ANDOR_OR = "O";
@Override
public void setAndOr (final java.lang.String AndOr)
{
set_Value (COLUMNNAME_AndOr, AndOr);
}
@Override
public java.lang.String getAndOr()
{
return get_ValueAsString(COLUMNNAME_AndOr);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
/**
* Operation AD_Reference_ID=205
* Reference name: AD_Find Operation
*/
public static final int OPERATION_AD_Reference_ID=205;
/** = = == */
public static final String OPERATION_Eq = "==";
/** >= = >= */
public static final String OPERATION_GtEq = ">=";
/** > = >> */
public static final String OPERATION_Gt = ">>";
/** < = << */
public static final String OPERATION_Le = "<<";
/** ~ = ~~ */
public static final String OPERATION_Like = "~~";
/** <= = <= */
public static final String OPERATION_LeEq = "<=";
/** |<x>| = AB */
public static final String OPERATION_X = "AB";
/** sql = SQ */
public static final String OPERATION_Sql = "SQ";
/** != = != */
public static final String OPERATION_NotEq = "!=";
@Override
public void setOperation (final java.lang.String Operation)
{
set_Value (COLUMNNAME_Operation, Operation);
}
@Override
public java.lang.String getOperation()
{
|
return get_ValueAsString(COLUMNNAME_Operation);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValue2 (final java.lang.String Value2)
{
set_Value (COLUMNNAME_Value2, Value2);
}
@Override
public java.lang.String getValue2()
{
return get_ValueAsString(COLUMNNAME_Value2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_NextCondition.java
| 1
|
请完成以下Java代码
|
public List<String> map(ConfigurationPropertyName configurationPropertyName) {
// Use a local copy in case another thread changes things
LastMapping<ConfigurationPropertyName, List<String>> last = this.lastMappedConfigurationPropertyName;
if (last != null && last.isFrom(configurationPropertyName)) {
return last.getMapping();
}
String convertedName = configurationPropertyName.toString();
List<String> mapping = Collections.singletonList(convertedName);
this.lastMappedConfigurationPropertyName = new LastMapping<>(configurationPropertyName, mapping);
return mapping;
}
@Override
public ConfigurationPropertyName map(String propertySourceName) {
// Use a local copy in case another thread changes things
LastMapping<String, ConfigurationPropertyName> last = this.lastMappedPropertyName;
if (last != null && last.isFrom(propertySourceName)) {
return last.getMapping();
}
ConfigurationPropertyName mapping = tryMap(propertySourceName);
this.lastMappedPropertyName = new LastMapping<>(propertySourceName, mapping);
return mapping;
}
private ConfigurationPropertyName tryMap(String propertySourceName) {
try {
ConfigurationPropertyName convertedName = ConfigurationPropertyName.adapt(propertySourceName, '.');
if (!convertedName.isEmpty()) {
return convertedName;
}
}
catch (Exception ex) {
// Ignore
}
return ConfigurationPropertyName.EMPTY;
}
|
private static class LastMapping<T, M> {
private final T from;
private final M mapping;
LastMapping(T from, M mapping) {
this.from = from;
this.mapping = mapping;
}
boolean isFrom(T from) {
return ObjectUtils.nullSafeEquals(from, this.from);
}
M getMapping() {
return this.mapping;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\DefaultPropertyMapper.java
| 1
|
请完成以下Java代码
|
public final void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
if (recordRefs.isEmpty())
{
return; // nothing to do, but shall not happen
}
final TableRecordReferenceSet recordRefsEligible = recordRefs.filter(this::isEligibleInvalidateEvent);
if (recordRefsEligible.isEmpty())
{
return; // nothing to do
}
final DocumentIdsSelection documentIdsToInvalidate = getDocumentIdsToInvalidate(recordRefsEligible);
if (documentIdsToInvalidate.isEmpty())
{
return; // nothing to do
}
rowsData.invalidate(documentIdsToInvalidate);
ViewChangesCollector.getCurrentOrAutoflush()
.collectRowsChanged(this, documentIdsToInvalidate);
}
protected boolean isEligibleInvalidateEvent(final TableRecordReference recordRef)
{
return true;
|
}
protected final DocumentIdsSelection getDocumentIdsToInvalidate(@NonNull final TableRecordReferenceSet recordRefs)
{
return rowsData.getDocumentIdsToInvalidate(recordRefs);
}
// extends IEditableView.patchViewRow
public final void patchViewRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
Check.assumeNotEmpty(fieldChangeRequests, "fieldChangeRequests is not empty");
if (rowsData instanceof IEditableRowsData)
{
final IEditableRowsData<T> editableRowsData = (IEditableRowsData<T>)rowsData;
editableRowsData.patchRow(ctx, fieldChangeRequests);
}
else
{
throw new AdempiereException("View is not editable");
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\AbstractCustomView.java
| 1
|
请完成以下Java代码
|
public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
}
/**
* Get an empty DOM document
*
* @param documentBuilderFactory the factory to build to DOM document
* @return the new empty document
* @throws ModelParseException if unable to create a new document
*/
public static DomDocument getEmptyDocument(DocumentBuilderFactory documentBuilderFactory) {
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
return new DomDocumentImpl(documentBuilder.newDocument());
} catch (ParserConfigurationException e) {
throw new ModelParseException("Unable to create a new document", e);
}
}
/**
* Create a new DOM document from the input stream
*
* @param documentBuilderFactory the factory to build to DOM document
* @param inputStream the input stream to parse
* @return the new DOM document
|
* @throws ModelParseException if a parsing or IO error is triggered
*/
public static DomDocument parseInputStream(DocumentBuilderFactory documentBuilderFactory, InputStream inputStream) {
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setErrorHandler(new DomErrorHandler());
return new DomDocumentImpl(documentBuilder.parse(inputStream));
} catch (ParserConfigurationException e) {
throw new ModelParseException("ParserConfigurationException while parsing input stream", e);
} catch (SAXException e) {
throw new ModelParseException("SAXException while parsing input stream", e);
} catch (IOException e) {
throw new ModelParseException("IOException while parsing input stream", e);
}
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\DomUtil.java
| 1
|
请完成以下Java代码
|
public class ExtendedReflectionToStringBuilder extends org.apache.commons.lang3.builder.ReflectionToStringBuilder
{
public ExtendedReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer)
{
super(object, style, buffer);
}
public ExtendedReflectionToStringBuilder(Object object, ToStringStyle style)
{
super(object, style);
}
public ExtendedReflectionToStringBuilder(Object object)
{
super(object);
}
public <T> ExtendedReflectionToStringBuilder(T object, ToStringStyle style, StringBuffer buffer, Class<? super T> reflectUpToClass, boolean outputTransients, boolean outputStatics)
{
super(object, style, buffer, reflectUpToClass, outputTransients, outputStatics);
}
@Override
protected boolean accept(Field field)
|
{
if (!super.accept(field))
{
return false;
}
final ToStringBuilder toStringBuilder = field.getAnnotation(ToStringBuilder.class);
if (toStringBuilder != null && toStringBuilder.skip())
{
return false;
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\ExtendedReflectionToStringBuilder.java
| 1
|
请完成以下Java代码
|
public boolean isCreateOverviewVariable() {
return createOverviewVariable;
}
public void setCreateOverviewVariable(boolean createOverviewVariable) {
this.createOverviewVariable = createOverviewVariable;
}
@Override
public VariableAggregationDefinition clone() {
VariableAggregationDefinition aggregation = new VariableAggregationDefinition();
aggregation.setValues(this);
return aggregation;
}
public void setValues(VariableAggregationDefinition otherVariableDefinitionAggregation) {
setImplementationType(otherVariableDefinitionAggregation.getImplementationType());
setImplementation(otherVariableDefinitionAggregation.getImplementation());
setTarget(otherVariableDefinitionAggregation.getTarget());
setTargetExpression(otherVariableDefinitionAggregation.getTargetExpression());
List<Variable> otherDefinitions = otherVariableDefinitionAggregation.getDefinitions();
if (otherDefinitions != null) {
List<Variable> newDefinitions = new ArrayList<>(otherDefinitions.size());
for (Variable otherDefinition : otherDefinitions) {
newDefinitions.add(otherDefinition.clone());
}
setDefinitions(newDefinitions);
}
setStoreAsTransientVariable(otherVariableDefinitionAggregation.isStoreAsTransientVariable());
setCreateOverviewVariable(otherVariableDefinitionAggregation.isCreateOverviewVariable());
}
public static class Variable {
protected String source;
protected String target;
protected String targetExpression;
protected String sourceExpression;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
|
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getTargetExpression() {
return targetExpression;
}
public void setTargetExpression(String targetExpression) {
this.targetExpression = targetExpression;
}
public String getSourceExpression() {
return sourceExpression;
}
public void setSourceExpression(String sourceExpression) {
this.sourceExpression = sourceExpression;
}
@Override
public Variable clone() {
Variable definition = new Variable();
definition.setValues(this);
return definition;
}
public void setValues(Variable otherDefinition) {
setSource(otherDefinition.getSource());
setSourceExpression(otherDefinition.getSourceExpression());
setTarget(otherDefinition.getTarget());
setTargetExpression(otherDefinition.getTargetExpression());
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\VariableAggregationDefinition.java
| 1
|
请完成以下Java代码
|
public static int findLargestNumberUsingArithmetic(int num, int k) {
for (int j = 0; j < k; j++) {
int result = 0;
int i = 1;
while (num / i > 0) {
int temp = (num / (i * 10))
* i
+ (num % i);
i *= 10;
result = Math.max(result, temp);
}
num = result;
}
return num;
}
public static int findLargestNumberUsingStack(int num, int k) {
String numStr = Integer.toString(num);
int length = numStr.length();
if (k == length) return 0;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < length; i++) {
char digit = numStr.charAt(i);
|
while (k > 0 && !stack.isEmpty() && stack.peek() < digit) {
stack.pop();
k--;
}
stack.push(digit);
}
while (k > 0) {
stack.pop();
k--;
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.insert(0, stack.pop());
}
return Integer.parseInt(result.toString());
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\largestNumberRemovingK\LargestNumberRemoveKDigits.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private JSONArray getItemHintProviders(ItemHint hint) throws Exception {
JSONArray providers = new JSONArray();
for (ItemHint.ValueProvider provider : hint.getProviders()) {
providers.put(getItemHintProvider(provider));
}
return providers;
}
private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception {
JSONObject result = new JSONObject();
result.put("name", provider.getName());
if (provider.getParameters() != null && !provider.getParameters().isEmpty()) {
JSONObject parameters = new JSONObject();
for (Map.Entry<String, Object> entry : provider.getParameters().entrySet()) {
parameters.put(entry.getKey(), extractItemValue(entry.getValue()));
}
result.put("parameters", parameters);
}
return result;
}
private void putHintValue(JSONObject jsonObject, Object value) throws Exception {
Object hintValue = extractItemValue(value);
jsonObject.put("value", hintValue);
}
private void putDefaultValue(JSONObject jsonObject, Object value) throws Exception {
Object defaultValue = extractItemValue(value);
jsonObject.put("defaultValue", defaultValue);
}
private Object extractItemValue(Object value) {
Object defaultValue = value;
if (value.getClass().isArray()) {
|
JSONArray array = new JSONArray();
int length = Array.getLength(value);
for (int i = 0; i < length; i++) {
array.put(Array.get(value, i));
}
defaultValue = array;
}
return defaultValue;
}
private static final class ItemMetadataComparator implements Comparator<ItemMetadata> {
private static final Comparator<ItemMetadata> GROUP = Comparator.comparing(ItemMetadata::getName)
.thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder()));
private static final Comparator<ItemMetadata> ITEM = Comparator.comparing(ItemMetadataComparator::isDeprecated)
.thenComparing(ItemMetadata::getName)
.thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder()));
@Override
public int compare(ItemMetadata o1, ItemMetadata o2) {
if (o1.isOfItemType(ItemType.GROUP)) {
return GROUP.compare(o1, o2);
}
return ITEM.compare(o1, o2);
}
private static boolean isDeprecated(ItemMetadata item) {
return item.getDeprecation() != null;
}
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\JsonConverter.java
| 2
|
请完成以下Java代码
|
public @Nullable OneTimeToken consume(OneTimeTokenAuthenticationToken authenticationToken) {
OneTimeToken ott = this.oneTimeTokenByToken.remove(authenticationToken.getTokenValue());
if (ott == null || isExpired(ott)) {
return null;
}
return ott;
}
private void cleanExpiredTokensIfNeeded() {
if (this.oneTimeTokenByToken.size() < 100) {
return;
}
for (Map.Entry<String, OneTimeToken> entry : this.oneTimeTokenByToken.entrySet()) {
if (isExpired(entry.getValue())) {
this.oneTimeTokenByToken.remove(entry.getKey());
}
}
}
|
private boolean isExpired(OneTimeToken ott) {
return this.clock.instant().isAfter(ott.getExpiresAt());
}
/**
* Sets the {@link Clock} used when generating one-time token and checking token
* expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ott\InMemoryOneTimeTokenService.java
| 1
|
请完成以下Java代码
|
public void receive(Message message) {
// Print source and dest with message
String line = "Message received from: " + message.getSrc() + " to: " + message.getDest() + " -> " + message.getObject();
// Only track the count of broadcast messages
// Tracking direct message would make for a pointless state
if (message.getDest() == null) {
messageCount++;
System.out.println("Message count: " + messageCount);
}
System.out.println(line);
}
@Override
public void getState(OutputStream output) throws Exception {
// Serialize into the stream
Util.objectToStream(messageCount, new DataOutputStream(output));
}
@Override
public void setState(InputStream input) {
// NOTE: since we know that incrementing the count and transferring the state
|
// is done inside the JChannel's thread, we don't have to worry about synchronizing
// messageCount. For production code it should be synchronized!
try {
// Deserialize
messageCount = Util.objectFromStream(new DataInputStream(input));
} catch (Exception e) {
System.out.println("Error deserialing state!");
}
System.out.println(messageCount + " is the current messagecount.");
}
private Optional<Address> getAddress(String name) {
View view = channel.view();
return view.getMembers().stream().filter(address -> name.equals(address.toString())).findFirst();
}
}
|
repos\tutorials-master\messaging-modules\jgroups\src\main\java\com\baeldung\jgroups\JGroupsMessenger.java
| 1
|
请完成以下Java代码
|
public void filter(final List<IQualityInvoiceLineGroup> groups)
{
for (final Iterator<IQualityInvoiceLineGroup> it = groups.iterator(); it.hasNext();)
{
final IQualityInvoiceLineGroup group = it.next();
final QualityInvoiceLineGroupType type = group.getQualityInvoiceLineGroupType();
if (!hasType(type))
{
it.remove();
}
}
}
/**
* Sort given lines with this comparator.
*
* NOTE: we assume the list is read-write.
*
* @param lines
*/
|
public void sort(final List<IQualityInvoiceLineGroup> lines)
{
Collections.sort(lines, this);
}
/**
* Remove from given lines those which their type is not specified in our list. Then sort the result.
*
* NOTE: we assume the list is read-write.
*
* @param lines
*/
public void filterAndSort(final List<IQualityInvoiceLineGroup> lines)
{
filter(lines);
sort(lines);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\QualityInvoiceLineGroupByTypeComparator.java
| 1
|
请完成以下Java代码
|
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
|
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_M_InOutLine_HU_IPA_SSCC18_v.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
# datasource 数据源配置内容
datasource:
# 订单数据源配置
orders:
url: jdbc:mysql://127.0.0.1:3306/test_orders?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
# HikariCP 自定义配置,对应 HikariConfig 配置属性类
hikari:
minimum-idle: 20 # 池中维护的最小空闲连接数,默认为 10 个。
maximum-pool-size: 20 # 池中最大连接数,包括闲置和使用中的连接,默认为 10 个。
# 用户数据源配置
users:
url: jdbc:mysql://127.0.0.1:3306/test_users?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driv
|
er-class-name: com.mysql.jdbc.Driver
username: root
password:
# HikariCP 自定义配置,对应 HikariConfig 配置属性类
hikari:
minimum-idle: 15 # 池中维护的最小空闲连接数,默认为 10 个。
maximum-pool-size: 15 # 池中最大连接数,包括闲置和使用中的连接,默认为 10 个。
|
repos\SpringBoot-Labs-master\lab-19\lab-19-datasource-pool-hikaricp-multiple\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
class InvalidConfigurationPropertyNameFailureAnalyzer
extends AbstractFailureAnalyzer<InvalidConfigurationPropertyNameException> {
@Override
protected FailureAnalysis analyze(Throwable rootFailure, InvalidConfigurationPropertyNameException cause) {
BeanCreationException exception = findCause(rootFailure, BeanCreationException.class);
String action = String.format("Modify '%s' so that it conforms to the canonical names requirements.",
cause.getName());
return new FailureAnalysis(buildDescription(cause, exception), action, cause);
}
private String buildDescription(InvalidConfigurationPropertyNameException cause,
@Nullable BeanCreationException exception) {
StringBuilder description = new StringBuilder(
String.format("Configuration property name '%s' is not valid:%n", cause.getName()));
|
String invalid = cause.getInvalidCharacters().stream().map(this::quote).collect(Collectors.joining(", "));
description.append(String.format("%n Invalid characters: %s", invalid));
if (exception != null) {
description.append(String.format("%n Bean: %s", exception.getBeanName()));
}
description.append(String.format("%n Reason: Canonical names should be "
+ "kebab-case ('-' separated), lowercase alpha-numeric characters and must start with a letter"));
return description.toString();
}
private String quote(Character c) {
return "'" + c + "'";
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\InvalidConfigurationPropertyNameFailureAnalyzer.java
| 1
|
请完成以下Java代码
|
public class MChatType extends X_CM_ChatType
{
/**
*
*/
private static final long serialVersionUID = -7933150405119053730L;
/**
* Get MChatType from Cache
* @param ctx context
* @param CM_ChatType_ID id
* @return MChatType
*/
public static MChatType get (Properties ctx, int CM_ChatType_ID)
{
Integer key = new Integer (CM_ChatType_ID);
MChatType retValue = (MChatType)s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MChatType (ctx, CM_ChatType_ID, null);
if (retValue.get_ID () != CM_ChatType_ID)
s_cache.put (key, retValue);
return retValue;
} // get
/** Cache */
private static CCache<Integer, MChatType> s_cache
= new CCache<Integer, MChatType> ("CM_ChatType", 20);
/**
|
* Standard Constructor
* @param ctx context
* @param CM_ChatType_ID id
* @param trxName transaction
*/
public MChatType (Properties ctx, int CM_ChatType_ID, String trxName)
{
super (ctx, CM_ChatType_ID, trxName);
if (CM_ChatType_ID == 0)
setModerationType (MODERATIONTYPE_NotModerated);
} // MChatType
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MChatType (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MChatType
} // MChatType
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MChatType.java
| 1
|
请完成以下Java代码
|
public void add_M_HU_PI_Item_Product(final I_M_ForecastLine forecastLine)
{
final IHUDocumentHandlerFactory huDocumentHandlerFactory = Services.get(IHUDocumentHandlerFactory.class);
final IHUDocumentHandler handler = huDocumentHandlerFactory.createHandler(I_M_ForecastLine.Table_Name);
if (null != handler)
{
handler.applyChangesFor(forecastLine);
updateQtyPacks(forecastLine);
updateQtyCalculated(forecastLine);
}
}
@CalloutMethod(columnNames = { I_M_ForecastLine.COLUMNNAME_Qty })
public void updateQtyTU(final I_M_ForecastLine forecastLine)
{
updateQtyPacks(forecastLine);
updateQtyCalculated(forecastLine);
}
@CalloutMethod(columnNames = { I_M_ForecastLine.COLUMNNAME_QtyEnteredTU, I_M_ForecastLine.COLUMNNAME_M_HU_PI_Item_Product_ID })
public void updateQtyCU(final I_M_ForecastLine forecastLine)
|
{
final IHUPackingAware packingAware = new ForecastLineHUPackingAware(forecastLine);
final Integer qtyPacks = packingAware.getQtyTU().intValue();
Services.get(IHUPackingAwareBL.class).setQtyCUFromQtyTU(packingAware, qtyPacks);
}
private void updateQtyPacks(final I_M_ForecastLine forecastLine)
{
final IHUPackingAware packingAware = new ForecastLineHUPackingAware(forecastLine);
Services.get(IHUPackingAwareBL.class).setQtyTU(packingAware);
}
private void updateQtyCalculated(final I_M_ForecastLine forecastLine)
{
final IHUPackingAware packingAware = new ForecastLineHUPackingAware(forecastLine);
final BigDecimal qty = packingAware.getQty();
packingAware.setQty(qty);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_ForecastLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void deleteTable(String tableName) {
StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS ").append(tableName);
final String query = sb.toString();
session.execute(query);
}
private ResultSet executeStatement(SimpleStatement statement, String keyspace) {
if (keyspace != null) {
statement.setKeyspace(CqlIdentifier.fromCql(keyspace));
}
return session.execute(statement);
}
private BoundStatement getProductVariantInsertStatement(Product product,UUID productId) {
String insertQuery = new StringBuilder("").append("INSERT INTO ").append(PRODUCT_TABLE_NAME)
.append("(product_id,variant_id,product_name,description,price) ").append("VALUES (").append(":product_id")
.append(", ").append(":variant_id").append(", ").append(":product_name").append(", ")
.append(":description").append(", ").append(":price").append(");").toString();
PreparedStatement preparedStatement = session.prepare(insertQuery);
|
return preparedStatement.bind(productId, UUID.randomUUID(),
product.getProductName(),
product.getDescription(),
product.getPrice());
}
private BoundStatement getProductInsertStatement(Product product,UUID productId,String productTableName) {
String cqlQuery1 = new StringBuilder("").append("INSERT INTO ").append(productTableName)
.append("(product_id,product_name,description,price) ").append("VALUES (").append(":product_id")
.append(", ").append(":product_name").append(", ").append(":description").append(", ")
.append(":price").append(");").toString();
PreparedStatement preparedStatement = session.prepare(cqlQuery1);
return preparedStatement.bind(productId,
product.getProductName(),
product.getDescription(),
product.getPrice());
}
}
|
repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\batch\repository\ProductRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public List<ProductOrderEntity> getProductOrderList() {
return productOrderList;
}
public void setProductOrderList(List<ProductOrderEntity> productOrderList) {
this.productOrderList = productOrderList;
}
public OrderStateEnum getOrderStateEnum() {
return orderStateEnum;
}
public void setOrderStateEnum(OrderStateEnum orderStateEnum) {
this.orderStateEnum = orderStateEnum;
}
public List<OrderStateTimeEntity> getOrderStateTimeList() {
return orderStateTimeList;
}
public void setOrderStateTimeList(List<OrderStateTimeEntity> orderStateTimeList) {
this.orderStateTimeList = orderStateTimeList;
}
public PayModeEnum getPayModeEnum() {
return payModeEnum;
}
public void setPayModeEnum(PayModeEnum payModeEnum) {
this.payModeEnum = payModeEnum;
}
public String getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}
public ReceiptEntity getReceiptEntity() {
return receiptEntity;
}
public void setReceiptEntity(ReceiptEntity receiptEntity) {
this.receiptEntity = receiptEntity;
}
public LocationEntity getLocationEntity() {
return locationEntity;
}
public void setLocationEntity(LocationEntity locationEntity) {
|
this.locationEntity = locationEntity;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getExpressNo() {
return expressNo;
}
public void setExpressNo(String expressNo) {
this.expressNo = expressNo;
}
public UserEntity getBuyer() {
return buyer;
}
public void setBuyer(UserEntity buyer) {
this.buyer = buyer;
}
@Override
public String toString() {
return "OrdersEntity{" +
"id='" + id + '\'' +
", buyer=" + buyer +
", company=" + company +
", productOrderList=" + productOrderList +
", orderStateEnum=" + orderStateEnum +
", orderStateTimeList=" + orderStateTimeList +
", payModeEnum=" + payModeEnum +
", totalPrice='" + totalPrice + '\'' +
", receiptEntity=" + receiptEntity +
", locationEntity=" + locationEntity +
", remark='" + remark + '\'' +
", expressNo='" + expressNo + '\'' +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\OrdersEntity.java
| 2
|
请完成以下Java代码
|
public Builder withId(String id) {
this.id = id;
return this;
}
/**
* Builder method for eventName parameter.
* @param eventName field to set
* @return builder
*/
public Builder withEventName(String eventName) {
this.eventName = eventName;
return this;
}
/**
* Builder method for executionId parameter.
* @param executionId field to set
* @return builder
*/
public Builder withExecutionId(String executionId) {
this.executionId = executionId;
return this;
}
/**
* Builder method for processInstanceId parameter.
* @param processInstanceId field to set
* @return builder
*/
public Builder withProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
return this;
}
/**
* Builder method for processDefinitionId parameter.
* @param processDefinitionId field to set
* @return builder
*/
public Builder withProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
return this;
}
/**
* Builder method for businessKey parameter.
* @param businessKey field to set
* @return builder
*/
public Builder withBusinessKey(String businessKey) {
this.businessKey = businessKey;
return this;
}
/**
* Builder method for configuration parameter.
* @param configuration field to set
* @return builder
*/
public Builder withConfiguration(String configuration) {
this.configuration = configuration;
return this;
}
|
/**
* Builder method for activityId parameter.
* @param activityId field to set
* @return builder
*/
public Builder withActivityId(String activityId) {
this.activityId = activityId;
return this;
}
/**
* Builder method for created parameter.
* @param created field to set
* @return builder
*/
public Builder withCreated(Date created) {
this.created = created;
return this;
}
/**
* Builder method of the builder.
* @return built class
*/
public MessageSubscriptionImpl build() {
return new MessageSubscriptionImpl(this);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\MessageSubscriptionImpl.java
| 1
|
请完成以下Java代码
|
public boolean isBlocking() {
return blocking;
}
public void setBlocking(boolean blocking) {
this.blocking = blocking;
}
public String getBlockingExpression() {
return blockingExpression;
}
public void setBlockingExpression(String blockingExpression) {
this.blockingExpression = blockingExpression;
}
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public boolean isExclusive() {
return exclusive;
}
public void setExclusive(boolean exclusive) {
this.exclusive = exclusive;
}
public boolean isAsyncLeave() {
return asyncLeave;
}
public void setAsyncLeave(boolean asyncLeave) {
this.asyncLeave = asyncLeave;
}
|
public boolean isAsyncLeaveExclusive() {
return asyncLeaveExclusive;
}
public void setAsyncLeaveExclusive(boolean asyncLeaveExclusive) {
this.asyncLeaveExclusive = asyncLeaveExclusive;
}
public void setValues(Task otherElement) {
super.setValues(otherElement);
setBlocking(otherElement.isBlocking());
setBlockingExpression(otherElement.getBlockingExpression());
setAsync(otherElement.isAsync());
setAsyncLeave(otherElement.isAsync());
setExclusive(otherElement.isExclusive());
setAsyncLeaveExclusive(otherElement.isAsyncLeaveExclusive());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Task.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity<Foo> postFoo(@RequestBody final Foo foo) {
fooRepository.put(foo.getId(), foo);
final URI location = ServletUriComponentsBuilder
.fromCurrentServletMapping()
.path("/foos/{id}")
.build()
.expand(foo.getId())
.toUri();
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(location);
final ResponseEntity<Foo> entity = new ResponseEntity<Foo>(foo, headers, HttpStatus.CREATED);
return entity;
}
@RequestMapping(method = RequestMethod.HEAD, value = "/foos")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo headFoo() {
return new Foo(1, randomAlphabetic(4));
}
@RequestMapping(method = RequestMethod.POST, value = "/foos/new")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo createFoo(@RequestBody final Foo foo) {
fooRepository.put(foo.getId(), foo);
return foo;
|
}
@RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public long deleteFoo(@PathVariable final long id) {
fooRepository.remove(id);
return id;
}
@RequestMapping(method = RequestMethod.POST, value = "/foos/form", produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public String submitFoo(@RequestParam("id") String id) {
return id;
}
}
|
repos\tutorials-master\spring-web-modules\spring-resttemplate\src\main\java\com\baeldung\resttemplate\configuration\FooController.java
| 2
|
请完成以下Java代码
|
public void setSource(final Object model)
{
if (model instanceof IHUPackingAware)
{
record = (IHUPackingAware)model;
}
else if (InterfaceWrapperHelper.isInstanceOf(model, I_C_Order.class))
{
final I_C_Order order = InterfaceWrapperHelper.create(model, I_C_Order.class);
record = new OrderHUPackingAware(order);
}
else
{
record = null;
}
}
@Override
public void apply(final Object model)
{
if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_OrderLine.class))
{
logger.debug("Skip applying because it's not an order line: {}", model);
return;
}
final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(model, I_C_OrderLine.class);
|
applyOnOrderLine(orderLine);
}
public void applyOnOrderLine(final I_C_OrderLine orderLine)
{
final IHUPackingAware to = new OrderLineHUPackingAware(orderLine);
Services.get(IHUPackingAwareBL.class).prepareCopyFrom(record)
.overridePartner(false)
.copyTo(to);
}
@Override
public boolean isCreateNewRecord()
{
if (isValid())
{
return true;
}
return false;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderLineHUPackingGridRowBuilder.java
| 1
|
请完成以下Java代码
|
protected void validateParams(String userId, String groupId, String processInstanceId, String type) {
if (processInstanceId == null) {
throw new ActivitiIllegalArgumentException("processInstanceId is null");
}
if (type == null) {
throw new ActivitiIllegalArgumentException("type is required when deleting a process identity link");
}
if (userId == null && groupId == null) {
throw new ActivitiIllegalArgumentException("userId and groupId cannot both be null");
}
}
public Void execute(CommandContext commandContext) {
ExecutionEntity processInstance = commandContext.getExecutionEntityManager().findById(processInstanceId);
|
if (processInstance == null) {
throw new ActivitiObjectNotFoundException(
"Cannot find process instance with id " + processInstanceId,
ExecutionEntity.class
);
}
executeInternal(commandContext, processInstance);
return null;
}
protected void executeInternal(CommandContext commandContext, ExecutionEntity processInstance) {
commandContext.getIdentityLinkEntityManager().deleteIdentityLink(processInstance, userId, groupId, type);
commandContext
.getHistoryManager()
.createProcessInstanceIdentityLinkComment(processInstanceId, userId, groupId, type, false);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteIdentityLinkForProcessInstanceCmd.java
| 1
|
请完成以下Java代码
|
public void setRef_RMA_ID (int Ref_RMA_ID)
{
if (Ref_RMA_ID < 1)
set_Value (COLUMNNAME_Ref_RMA_ID, null);
else
set_Value (COLUMNNAME_Ref_RMA_ID, Integer.valueOf(Ref_RMA_ID));
}
/** Get Referenced RMA.
@return Referenced RMA */
@Override
public int getRef_RMA_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_RMA_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Vertriebsbeauftragter.
@param SalesRep_ID
Sales Representative or Company Agent
*/
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
|
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Vertriebsbeauftragter.
@return Sales Representative or Company Agent
*/
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RMA.java
| 1
|
请完成以下Spring Boot application配置
|
#primary
spring.datasource.druid.one.url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.druid.one.username=root
spring.datasource.druid.one.password=root
spring.datasource.druid.one.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.one.initialSize=3
spring.datasource.druid.one.minIdle=3
spring.datasource.druid.one.maxActive=10
#secondary
spring.datasource.druid.two.url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.druid.two.username=root
spring.datasource.druid.two.password=root
spring.datasource.druid.two.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.two.initialSize=6
spring.datasource.druid.two.minIdle=20
spring.datasource.druid.two.maxActive=30
#\u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4
spring.datasource.druid.maxWait=60000
#\u914D\u7F6E\u95F4\u9694\u591A\u4E45\u624D\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B\uFF0C\u68C0\u6D4B\u9700\u8981\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
#\u914D\u7F6E\u4E00\u4E2A\u8FDE\u63A5\u5728\u6C60\u4E2D\u6700\u5C0F\u751F\u5B58\u7684\u65F6\u95F4\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2
spring.datasource.druid.minEvictableIdleTimeMillis=600000
spring.datasource.druid.maxEvictableIdleTimeMillis=900000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
#y\u68C0\u6D4B\u8FDE\u63A5\u662F\u5426\u6709\u6548
spring.datasource.druid.testWhileIdle=true
#\u662F\u5426\u5728\u4ECE\u6C60\u4E2D\u53D6\u51FA\u8FDE\u63A5\u524D\u8FDB\u884C\u68C0\u9A8C\u8FDE\u63A5\u6C60\u7684\u53EF\u7528\u6027
spring.datasource.druid.testOnBorrow=false
#\u662F\u5426\u5728\u5F52\u8FD8\u5230\u6C60\u4E2D\u524D\u8FDB\u884C\u68C0\u9A8C\u8FDE\u63A5\u6C60\u7684\u53EF\u7528\u6027
spring.datasource.druid.testOnReturn
|
=false
# \u662F\u5426\u6253\u5F00PSCache\uFF0C
spring.datasource.druid.poolPreparedStatements=true
#\u5E76\u4E14\u6307\u5B9A\u6BCF\u4E2A\u8FDE\u63A5\u4E0APSCache\u7684\u5927\u5C0F
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
#\u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters
spring.datasource.druid.filters=stat,wall,log4j
#\u901A\u8FC7connectProperties\u5C5E\u6027\u6765\u6253\u5F00mergeSql\u529F\u80FD\uFF1B\u6162SQL\u8BB0\u5F55
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=600
spring.jpa.properties.hibernate.hbm2ddl.auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#sql\u8F93\u51FA
spring.jpa.show-sql=true
#format\u4E00\u4E0Bsql\u8FDB\u884C\u8F93\u51FA
spring.jpa.properties.hibernate.format_sql=true
|
repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public ResponseEntity<Foo> getFooById(@Parameter(description = "id of foo to be searched") @PathVariable("id") String id) {
Optional<Foo> foo = repository.findById(Long.valueOf(id));
return foo.isPresent() ? new ResponseEntity<>(foo.get(), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@Operation(summary = "Create a foo")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "foo created", content = { @
Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}),
@ApiResponse(responseCode = "404", description = "Bad request", content = @Content) })
@PostMapping
public ResponseEntity<Foo> addFoo(@Parameter(description = "foo object to be created") @RequestBody @Valid Foo foo) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(linkTo(FooBarController.class).slash(foo.getId()).toUri());
Foo savedFoo;
try {
savedFoo = repository.save(foo);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED);
}
@Operation(summary = "Delete a foo")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "foo deleted"),
@ApiResponse(responseCode = "404", description = "Bad request", content = @Content) })
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteFoo(@Parameter(description = "id of foo to be deleted") @PathVariable("id") long id) {
try {
|
repository.deleteById(id);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Operation(summary = "Update a foo")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "foo updated successfully", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}),
@ApiResponse(responseCode = "404", description = "No Foo exists with given id", content = @Content) })
@PutMapping("/{id}")
public ResponseEntity<Foo> updateFoo(@Parameter(description = "id of foo to be updated") @PathVariable("id") long id, @RequestBody Foo foo) {
boolean isFooPresent = repository.existsById(Long.valueOf(id));
if (!isFooPresent) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Foo updatedFoo = repository.save(foo);
return new ResponseEntity<>(updatedFoo, HttpStatus.OK);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\restdocopenapi\springdoc\FooBarController.java
| 1
|
请完成以下Java代码
|
public class Weather {
@SerializedName(value = "location", alternate = "place")
private String location;
@SerializedName(value = "temp", alternate = "temperature")
private int temp;
@SerializedName(value = "outlook", alternate = "weather")
private String outlook;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getTemp() {
|
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
public String getOutlook() {
return outlook;
}
public void setOutlook(String outlook) {
this.outlook = outlook;
}
}
|
repos\tutorials-master\json-modules\gson\src\main\java\com\baeldung\gson\entities\Weather.java
| 1
|
请完成以下Java代码
|
private static void updateBillToAndShipToFlags(
@NonNull final I_I_BPartner importRecord,
@NonNull final I_C_BPartner_Location bpartnerLocation)
{
bpartnerLocation.setIsShipToDefault(importRecord.isShipToDefault());
bpartnerLocation.setIsShipTo(extractIsShipTo(importRecord));
bpartnerLocation.setIsBillToDefault(importRecord.isBillToDefault());
bpartnerLocation.setIsBillTo(extractIsBillTo(importRecord));
}
private static void updatePhoneAndFax(
@NonNull final I_I_BPartner importRecord,
@NonNull final I_C_BPartner_Location bpartnerLocation)
{
if (importRecord.getPhone() != null)
{
bpartnerLocation.setPhone(importRecord.getPhone());
}
if (importRecord.getPhone2() != null)
{
bpartnerLocation.setPhone2(importRecord.getPhone2());
}
if (importRecord.getFax() != null)
|
{
bpartnerLocation.setFax(importRecord.getFax());
}
}
private void fireImportValidator(
@NonNull final I_I_BPartner importRecord,
@NonNull final I_C_BPartner_Location bpartnerLocation)
{
ModelValidationEngine.get().fireImportValidate(process, importRecord, bpartnerLocation, IImportInterceptor.TIMING_AFTER_IMPORT);
}
@VisibleForTesting
static boolean extractIsShipTo(@NonNull final I_I_BPartner importRecord)
{
return importRecord.isShipToDefault() || importRecord.isShipTo();
}
@VisibleForTesting
static boolean extractIsBillTo(@NonNull final I_I_BPartner importRecord)
{
return importRecord.isBillToDefault() || importRecord.isBillTo();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerLocationImportHelper.java
| 1
|
请完成以下Java代码
|
private void createNotice(final I_M_Product product, final String msg)
{
final String productValue = product != null ? product.getValue() : "-";
addLog("WARNING: Product " + productValue + ": " + msg);
}
@lombok.Value(staticConstructor = "of")
private static class Context
{
@NonNull I_M_Product product;
@NonNull ProductPlanning productPlanning;
@NonNull PPRouting routing;
}
@lombok.Getter
@lombok.ToString
private static class RoutingDurationsAndYield
{
private Percent yield = Percent.ONE_HUNDRED;
private Duration queuingTime = Duration.ZERO;
private Duration setupTime = Duration.ZERO;
private Duration durationPerOneUnit = Duration.ZERO;
private Duration waitingTime = Duration.ZERO;
private Duration movingTime = Duration.ZERO;
public void addActivity(final PPRoutingActivity activity)
{
if (!activity.getYield().isZero())
{
yield = yield.multiply(activity.getYield(), 0);
}
queuingTime = queuingTime.plus(activity.getQueuingTime());
setupTime = setupTime.plus(activity.getSetupTime());
waitingTime = waitingTime.plus(activity.getWaitingTime());
movingTime = movingTime.plus(activity.getMovingTime());
// We use node.getDuration() instead of m_routingService.estimateWorkingTime(node) because
// this will be the minimum duration of this node. So even if the node have defined units/cycle
// we consider entire duration of the node.
durationPerOneUnit = durationPerOneUnit.plus(activity.getDurationPerOneUnit());
}
}
@lombok.Value(staticConstructor = "of")
|
private static class RoutingActivitySegmentCost
{
public static Collector<RoutingActivitySegmentCost, ?, Map<CostElementId, BigDecimal>> groupByCostElementId()
{
return Collectors.groupingBy(RoutingActivitySegmentCost::getCostElementId, sumCostsAsBigDecimal());
}
private static Collector<RoutingActivitySegmentCost, ?, BigDecimal> sumCostsAsBigDecimal()
{
return Collectors.reducing(BigDecimal.ZERO, RoutingActivitySegmentCost::getCostAsBigDecimal, BigDecimal::add);
}
@NonNull
CostAmount cost;
@NonNull
PPRoutingActivityId routingActivityId;
@NonNull
CostElementId costElementId;
public BigDecimal getCostAsBigDecimal()
{
return cost.toBigDecimal();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\RollupWorkflow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UniqueFieldController {
@Autowired
private SaleRepository saleRepo;
@Autowired
private CompanyRepository companyRepo;
@Autowired
private CustomerRepository customerRepo;
@Autowired
private AssetRepository assetRepo;
@PostMapping("/sale")
public Sale post(@RequestBody Sale sale) {
return saleRepo.insert(sale);
}
@GetMapping("/sale")
public Optional<Sale> getSale(SaleId id) {
return saleRepo.findBySaleId(id);
}
@PostMapping("/company")
public Company post(@RequestBody Company company) {
return companyRepo.insert(company);
}
@PutMapping("/company")
public Company put(@RequestBody Company company) {
return companyRepo.save(company);
}
@GetMapping("/company/{id}")
public Optional<Company> getCompany(@PathVariable String id) {
|
return companyRepo.findById(id);
}
@PostMapping("/customer")
public Customer post(@RequestBody Customer customer) {
return customerRepo.insert(customer);
}
@GetMapping("/customer/{id}")
public Optional<Customer> getCustomer(@PathVariable String id) {
return customerRepo.findById(id);
}
@PostMapping("/asset")
public Asset post(@RequestBody Asset asset) {
return assetRepo.insert(asset);
}
@GetMapping("/asset/{id}")
public Optional<Asset> getAsset(@PathVariable String id) {
return assetRepo.findById(id);
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\unique\field\web\UniqueFieldController.java
| 2
|
请完成以下Java代码
|
public final int getM_LocatorTo_ID()
{
final I_M_MovementLine movementLine = getModel(I_M_MovementLine.class);
return movementLine.getM_LocatorTo_ID();
}
@Value
@Builder
private static class MovementLineCostAmounts
{
AggregatedCostAmount outboundCosts;
AggregatedCostAmount inboundCosts;
}
public final MoveCostsResult getCreateCosts(@NonNull final AcctSchema as)
{
if (isReversalLine())
{
final AggregatedCostAmount outboundCosts = services.createReversalCostDetails(
CostDetailReverseRequest.builder()
.acctSchemaId(as.getId())
.reversalDocumentRef(CostingDocumentRef.ofOutboundMovementLineId(get_ID()))
.initialDocumentRef(CostingDocumentRef.ofOutboundMovementLineId(getReversalLine_ID()))
.date(getDateAcctAsInstant())
.build())
.toAggregatedCostAmount();
final AggregatedCostAmount inboundCosts = services.createReversalCostDetails(
CostDetailReverseRequest.builder()
.acctSchemaId(as.getId())
.reversalDocumentRef(CostingDocumentRef.ofInboundMovementLineId(get_ID()))
.initialDocumentRef(CostingDocumentRef.ofInboundMovementLineId(getReversalLine_ID()))
|
.date(getDateAcctAsInstant())
.build())
.toAggregatedCostAmount();
return MoveCostsResult.builder()
.outboundCosts(outboundCosts)
.inboundCosts(inboundCosts)
.build();
}
else
{
return services.moveCosts(MoveCostsRequest.builder()
.acctSchemaId(as.getId())
.clientId(getClientId())
.date(getDateAcctAsInstant())
// .costElement(null) // all cost elements
.productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId())
.qtyToMove(getQty())
//
.outboundOrgId(getFromOrgId())
.outboundDocumentRef(CostingDocumentRef.ofOutboundMovementLineId(get_ID()))
//
.inboundOrgId(getToOrgId())
.inboundDocumentRef(CostingDocumentRef.ofInboundMovementLineId(get_ID()))
//
.build());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_Movement.java
| 1
|
请完成以下Java代码
|
class NameOffsetLookups {
public static final NameOffsetLookups NONE = new NameOffsetLookups(0, 0);
private final int offset;
private final BitSet enabled;
NameOffsetLookups(int offset, int size) {
this.offset = offset;
this.enabled = (size != 0) ? new BitSet(size) : null;
}
void swap(int i, int j) {
if (this.enabled != null) {
boolean temp = this.enabled.get(i);
this.enabled.set(i, this.enabled.get(j));
this.enabled.set(j, temp);
}
}
int get(int index) {
return isEnabled(index) ? this.offset : 0;
}
|
int enable(int index, boolean enable) {
if (this.enabled != null) {
this.enabled.set(index, enable);
}
return (!enable) ? 0 : this.offset;
}
boolean isEnabled(int index) {
return (this.enabled != null && this.enabled.get(index));
}
boolean hasAnyEnabled() {
return this.enabled != null && this.enabled.cardinality() > 0;
}
NameOffsetLookups emptyCopy() {
return new NameOffsetLookups(this.offset, this.enabled.size());
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\NameOffsetLookups.java
| 1
|
请完成以下Java代码
|
public <T> T[] toArray(T[] a) {
return deque.toArray(a);
}
@Override
public boolean add(E e) {
return deque.add(e);
}
@Override
public boolean remove(Object o) {
return deque.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return deque.containsAll(c);
}
@Override
|
public boolean addAll(Collection<? extends E> c) {
return deque.addAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return deque.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return deque.retainAll(c);
}
@Override
public void clear() {
deque.clear();
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\dequestack\ArrayLifoStack.java
| 1
|
请完成以下Java代码
|
protected void applyFilters(BatchQuery query) {
if (batchId != null) {
query.batchId(batchId);
}
if (type != null) {
query.type(type);
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
if (TRUE.equals(suspended)) {
query.suspended();
|
}
if (FALSE.equals(suspended)) {
query.active();
}
}
protected void applySortBy(BatchQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) {
query.orderById();
}
else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchQueryDto.java
| 1
|
请完成以下Java代码
|
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 class CustomQueryBook {
@Id
private Long id;
private String title;
public CustomQueryBook() {
}
public CustomQueryBook(long id, String title) {
this.id = id;
this.title = title;
}
public void setId(Long id) {
|
this.id = id;
}
public Long getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\insertableonly\query\CustomQueryBook.java
| 2
|
请完成以下Java代码
|
public static Collector<Quantity, ?, MixedQuantity> collectAndSum()
{
return GuavaCollectors.collectUsingListAccumulator(de.metas.quantity.MixedQuantity::sumOf);
}
public static MixedQuantity sumOf(@NonNull final Collection<Quantity> collection)
{
if (collection.isEmpty())
{
return EMPTY;
}
final HashMap<UomId, Quantity> map = new HashMap<>();
for (final Quantity qty : collection)
{
map.compute(qty.getUomId(), (currencyId, currentQty) -> currentQty == null ? qty : currentQty.add(qty));
}
return new MixedQuantity(map);
}
@Override
public String toString()
{
if (map.isEmpty())
{
return "0";
}
return map.values()
.stream()
.map(Quantity::toShortString)
.collect(Collectors.joining("+"));
}
public Optional<Quantity> toNoneOrSingleValue()
|
{
if (map.isEmpty())
{
return Optional.empty();
}
else if (map.size() == 1)
{
return map.values().stream().findFirst();
}
else
{
throw new AdempiereException("Expected none or single value but got many: " + map.values());
}
}
public MixedQuantity add(@NonNull final Quantity qtyToAdd)
{
if (qtyToAdd.isZero())
{
return this;
}
return new MixedQuantity(
CollectionUtils.merge(map, qtyToAdd.getUomId(), qtyToAdd, Quantity::add)
);
}
public Quantity getByUOM(@NonNull final UomId uomId)
{
final Quantity qty = map.get(uomId);
return qty != null ? qty : Quantitys.zero(uomId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\MixedQuantity.java
| 1
|
请完成以下Java代码
|
public long countByTenantId(TenantId tenantId) {
return dashboardDao.countByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.DASHBOARD;
}
private class CustomerDashboardsRemover extends PaginatedRemover<Customer, DashboardInfo> {
private final Customer customer;
CustomerDashboardsRemover(Customer customer) {
this.customer = customer;
}
@Override
protected PageData<DashboardInfo> findEntities(TenantId tenantId, Customer customer, PageLink pageLink) {
return dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(customer.getTenantId().getId(), customer.getId().getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, DashboardInfo entity) {
unassignDashboardFromCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer.getId());
}
|
}
private class CustomerDashboardsUpdater extends PaginatedRemover<Customer, DashboardInfo> {
private final Customer customer;
CustomerDashboardsUpdater(Customer customer) {
this.customer = customer;
}
@Override
protected PageData<DashboardInfo> findEntities(TenantId tenantId, Customer customer, PageLink pageLink) {
return dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(customer.getTenantId().getId(), customer.getId().getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, DashboardInfo entity) {
updateAssignedCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer);
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\dashboard\DashboardServiceImpl.java
| 1
|
请完成以下Java代码
|
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
|
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
}
|
repos\tutorials-master\spring-web-modules\spring-resttemplate-3\src\main\java\com\baeldung\xmlpost\model\PaymentRequest.java
| 1
|
请完成以下Java代码
|
public class BlueprintELResolver extends ELResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(BlueprintELResolver.class);
private Map<String, JavaDelegate> delegateMap = new HashMap<>();
private Map<String, ActivityBehavior> activityBehaviourMap = new HashMap<>();
@Override
public Object getValue(ELContext context, Object base, Object property) {
if (base == null) {
// according to javadoc, can only be a String
String key = (String) property;
for (String name : delegateMap.keySet()) {
if (name.equalsIgnoreCase(key)) {
context.setPropertyResolved(true);
return delegateMap.get(name);
}
}
for (String name : activityBehaviourMap.keySet()) {
if (name.equalsIgnoreCase(key)) {
context.setPropertyResolved(true);
return activityBehaviourMap.get(name);
}
}
}
return null;
}
@SuppressWarnings("rawtypes")
public void bindService(JavaDelegate delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
delegateMap.put(name, delegate);
LOGGER.info("added Flowable service to delegate cache {}", name);
}
@SuppressWarnings("rawtypes")
public void unbindService(JavaDelegate delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
if (delegateMap.containsKey(name)) {
delegateMap.remove(name);
}
LOGGER.info("removed Flowable service from delegate cache {}", name);
}
@SuppressWarnings("rawtypes")
public void bindActivityBehaviourService(ActivityBehavior delegate, Map props) {
String name = (String) props.get("osgi.service.blueprint.compname");
activityBehaviourMap.put(name, delegate);
LOGGER.info("added Flowable service to activity behaviour cache {}", name);
}
@SuppressWarnings("rawtypes")
public void unbindActivityBehaviourService(ActivityBehavior delegate, Map props) {
|
String name = (String) props.get("osgi.service.blueprint.compname");
if (activityBehaviourMap.containsKey(name)) {
activityBehaviourMap.remove(name);
}
LOGGER.info("removed Flowable service from activity behaviour cache {}", name);
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return true;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object arg) {
return Object.class;
}
@Override
public Class<?> getType(ELContext context, Object arg1, Object arg2) {
return Object.class;
}
}
|
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\BlueprintELResolver.java
| 1
|
请完成以下Java代码
|
public class QuickSort {
public static void quickSort(int arr[], int begin, int end)
{
if (begin < end) {
int partitionIndex = partition(arr, begin, end);
// Recursively sort elements of the 2 sub-arrays
quickSort(arr, begin, partitionIndex-1);
quickSort(arr, partitionIndex+1, end);
}
}
private static int partition(int arr[], int begin, int end)
{
int pivot = arr[end];
int i = (begin-1);
|
for (int j=begin; j<end; j++)
{
if (arr[j] <= pivot) {
i++;
int swapTemp = arr[i];
arr[i] = arr[j];
arr[j] = swapTemp;
}
}
int swapTemp = arr[i+1];
arr[i+1] = arr[end];
arr[end] = swapTemp;
return i+1;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-sorting\src\main\java\com\baeldung\algorithms\quicksort\QuickSort.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) throws Exception
{
if (Check.isEmpty(System.getProperty("PropertyFile"), true))
{
throw new AdempiereException("Please set the PropertyFile");
}
final String outputFolder = System.getProperty("OutputFolder");
if (Check.isEmpty(outputFolder, true))
{
throw new AdempiereException("Please set the OutputFolder");
}
final String entityType = System.getProperty(PARAM_EntityType);
if (Check.isEmpty(entityType, true))
{
throw new AdempiereException("Please set the EntityType");
}
LogManager.initialize(true); // just to make sure we are using the client side settings
AdempiereToolsHelper.getInstance().startupMinimal();
final ProcessInfo pi = ProcessInfo.builder()
.setCtx(Env.getCtx())
.setTitle("GenerateCanonicalXSD")
|
.setAD_Process_ID(-1) // N/A
.setClassname(GenerateCanonicalXSD.class.getName())
.addParameter(PARAM_Target_Directory, outputFolder)
.addParameter(PARAM_EntityType, entityType)
.build();
final GenerateCanonicalXSD process = new GenerateCanonicalXSD();
process.p_FilterBy_AD_Client_ID = false;
LogManager.setLevel(Level.INFO);
process.startProcess(pi, ITrx.TRX_None);
//
// CanonicalXSDGenerator.validateXML(new File("d:/tmp/C_BPartner.xml"), proc.getSchemaFile());
// CanonicalXSDGenerator.validateXML(new File("d:/tmp/clientPartners.xml"), proc.getSchemaFile());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\esb\process\GenerateCanonicalXSD.java
| 1
|
请完成以下Java代码
|
public List<Fact> createFacts(final AcctSchema as)
{
final Fact fact = new Fact(this, as, PostingType.Actual);
setC_Currency_ID(as.getCurrencyId());
getDocLines().forEach(line -> createFactsForMovementLine(fact, line));
return ImmutableList.of(fact);
}
private void createFactsForMovementLine(final Fact fact, final DocLine_Movement line)
{
final AcctSchema as = fact.getAcctSchema();
final MoveCostsResult costs = line.getCreateCosts(as);
//
// Inventory CR/DR (from locator)
final CostAmount outboundCosts = costs.getOutboundAmountToPost(as);
fact.createLine()
.setDocLine(line)
.setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as))
.setAmtSourceDrOrCr(outboundCosts.toMoney()) // from (-) CR
.setQty(line.getQty().negate()) // outgoing
.locatorId(line.getM_Locator_ID())
.activityId(line.getActivityFromId())
.buildAndAdd();
|
//
// InventoryTo DR/CR (to locator)
final CostAmount inboundCosts = costs.getInboundAmountToPost(as);
fact.createLine()
.setDocLine(line)
.setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as))
.setAmtSourceDrOrCr(inboundCosts.toMoney()) // to (+) DR
.setQty(line.getQty()) // incoming
.locatorId(line.getM_LocatorTo_ID())
.activityId(line.getActivityId())
.buildAndAdd();
}
} // Doc_Movement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Movement.java
| 1
|
请完成以下Java代码
|
public static class CustomerHolder {
public static CustomerHolder from(Customer customer) {
return new CustomerHolder(customer);
}
private boolean cacheMiss = true;
private final Customer customer;
protected CustomerHolder(Customer customer) {
Assert.notNull(customer, "Customer must not be null");
this.customer = customer;
}
public CustomerHolder setCacheMiss(boolean cacheMiss) {
|
this.cacheMiss = cacheMiss;
return this;
}
public boolean isCacheMiss() {
return this.cacheMiss;
}
public Customer getCustomer() {
return customer;
}
}
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\caching\multi-site\src\main\java\example\app\caching\multisite\client\web\CustomerController.java
| 1
|
请完成以下Java代码
|
public String getCostCalculationMethod()
{
return get_ValueAsString(COLUMNNAME_CostCalculationMethod);
}
@Override
public void setCostCalculation_Percentage (final @Nullable BigDecimal CostCalculation_Percentage)
{
set_Value (COLUMNNAME_CostCalculation_Percentage, CostCalculation_Percentage);
}
@Override
public BigDecimal getCostCalculation_Percentage()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostCalculation_Percentage);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* CostDistributionMethod AD_Reference_ID=541712
* Reference name: CostDistributionMethod
*/
public static final int COSTDISTRIBUTIONMETHOD_AD_Reference_ID=541712;
/** Quantity = Q */
public static final String COSTDISTRIBUTIONMETHOD_Quantity = "Q";
/** Amount = A */
public static final String COSTDISTRIBUTIONMETHOD_Amount = "A";
@Override
public void setCostDistributionMethod (final String CostDistributionMethod)
{
set_Value (COLUMNNAME_CostDistributionMethod, CostDistributionMethod);
}
@Override
public String getCostDistributionMethod()
{
return get_ValueAsString(COLUMNNAME_CostDistributionMethod);
}
@Override
public I_C_OrderLine getCreated_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_Created_OrderLine_ID, I_C_OrderLine.class);
}
@Override
public void setCreated_OrderLine(final I_C_OrderLine Created_OrderLine)
{
set_ValueFromPO(COLUMNNAME_Created_OrderLine_ID, I_C_OrderLine.class, Created_OrderLine);
}
@Override
public void setCreated_OrderLine_ID (final int Created_OrderLine_ID)
{
|
if (Created_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, Created_OrderLine_ID);
}
@Override
public int getCreated_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_Created_OrderLine_ID);
}
@Override
public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public I_M_CostElement getM_CostElement()
{
return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class);
}
@Override
public void setM_CostElement(final I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class, M_CostElement);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost.java
| 1
|
请完成以下Java代码
|
public void setDLM_Referencing_Column_ID(final int DLM_Referencing_Column_ID)
{
if (DLM_Referencing_Column_ID < 1)
{
set_Value(COLUMNNAME_DLM_Referencing_Column_ID, null);
}
else
{
set_Value(COLUMNNAME_DLM_Referencing_Column_ID, Integer.valueOf(DLM_Referencing_Column_ID));
}
}
/**
* Get Referenzierende Spalte.
*
* @return Referenzierende Spalte
*/
@Override
public int getDLM_Referencing_Column_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Column_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Partitionsgrenze.
*
* @param IsPartitionBoundary
* Falls ja, dann gehören Datensatze, die über die jeweilige Referenz verknüpft sind nicht zur selben Partition.
*/
@Override
public void setIsPartitionBoundary(final boolean IsPartitionBoundary)
|
{
set_Value(COLUMNNAME_IsPartitionBoundary, Boolean.valueOf(IsPartitionBoundary));
}
/**
* Get Partitionsgrenze.
*
* @return Falls ja, dann gehören Datensatze, die über die jeweilige Referenz verknüpft sind nicht zur selben Partition.
*/
@Override
public boolean isPartitionBoundary()
{
final Object oo = get_Value(COLUMNNAME_IsPartitionBoundary);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Reference.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected CassandraToSqlColumn getColumn(String sqlColumnName) {
return this.columns.stream().filter(col -> col.getSqlColumnName().equals(sqlColumnName)).findFirst().get();
}
protected CassandraToSqlColumnData getColumnData(CassandraToSqlColumnData[] data, String sqlColumnName) {
CassandraToSqlColumn column = this.getColumn(sqlColumnName);
return data[column.getIndex()];
}
private Optional<String> extractConstraintName(SQLException ex) {
final String sqlState = JdbcExceptionHelper.extractSqlState( ex );
if (sqlState != null) {
String sqlStateClassCode = JdbcExceptionHelper.determineSqlStateClassCode( sqlState );
if ( sqlStateClassCode != null ) {
if (Arrays.asList(
"23", // "integrity constraint violation"
"27", // "triggered data change violation"
"44" // "with check option violation"
).contains(sqlStateClassCode)) {
if (ex instanceof PSQLException) {
return Optional.of(((PSQLException)ex).getServerErrorMessage().getConstraint());
}
}
}
}
return Optional.empty();
}
protected Statement createCassandraSelectStatement() {
StringBuilder selectStatementBuilder = new StringBuilder();
selectStatementBuilder.append("SELECT ");
for (CassandraToSqlColumn column : columns) {
selectStatementBuilder.append(column.getCassandraColumnName()).append(",");
}
selectStatementBuilder.deleteCharAt(selectStatementBuilder.length() - 1);
selectStatementBuilder.append(" FROM ").append(cassandraCf);
return SimpleStatement.newInstance(selectStatementBuilder.toString());
}
private PreparedStatement createSqlInsertStatement(Connection conn) throws SQLException {
|
StringBuilder insertStatementBuilder = new StringBuilder();
insertStatementBuilder.append("INSERT INTO ").append(this.sqlTableName).append(" (");
for (CassandraToSqlColumn column : columns) {
insertStatementBuilder.append(column.getSqlColumnName()).append(",");
}
insertStatementBuilder.deleteCharAt(insertStatementBuilder.length() - 1);
insertStatementBuilder.append(") VALUES (");
for (CassandraToSqlColumn column : columns) {
if (column.getType() == CassandraToSqlColumnType.JSON) {
insertStatementBuilder.append("cast(? AS json)");
} else {
insertStatementBuilder.append("?");
}
insertStatementBuilder.append(",");
}
insertStatementBuilder.deleteCharAt(insertStatementBuilder.length() - 1);
insertStatementBuilder.append(")");
return conn.prepareStatement(insertStatementBuilder.toString());
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\migrate\CassandraToSqlTable.java
| 2
|
请完成以下Java代码
|
public boolean isSecretRequired() {
return this.clientSecret != null;
}
/**
* 是否有 scopes
*
* @return 结果
*/
@Override
public boolean isScoped() {
return this.scopes != null && !this.scopes.isEmpty();
}
/**
* scopes
*
* @return scopes
*/
@Override
public Set<String> getScope() {
return stringToSet(scopes);
}
/**
* 授权类型
*
* @return 结果
*/
@Override
public Set<String> getAuthorizedGrantTypes() {
return stringToSet(grantTypes);
}
@Override
public Set<String> getResourceIds() {
return stringToSet(resourceIds);
}
/**
* 获取回调地址
*
* @return redirectUrl
*/
@Override
public Set<String> getRegisteredRedirectUri() {
return stringToSet(redirectUrl);
}
/**
* 这里需要提一下
* 个人觉得这里应该是客户端所有的权限
* 但是已经有 scope 的存在可以很好的对客户端的权限进行认证了
* 那么在 oauth2 的四个角色中,这里就有可能是资源服务器的权限
* 但是一般资源服务器都有自己的权限管理机制,比如拿到用户信息后做 RBAC
|
* 所以在 spring security 的默认实现中直接给的是空的一个集合
* 这里我们也给他一个空的把
*
* @return GrantedAuthority
*/
@Override
public Collection<GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
/**
* 判断是否自动授权
*
* @param scope scope
* @return 结果
*/
@Override
public boolean isAutoApprove(String scope) {
if (autoApproveScopes == null || autoApproveScopes.isEmpty()) {
return false;
}
Set<String> authorizationSet = stringToSet(authorizations);
for (String auto : authorizationSet) {
if ("true".equalsIgnoreCase(auto) || scope.matches(auto)) {
return true;
}
}
return false;
}
/**
* additional information 是 spring security 的保留字段
* 暂时用不到,直接给个空的即可
*
* @return map
*/
@Override
public Map<String, Object> getAdditionalInformation() {
return Collections.emptyMap();
}
private Set<String> stringToSet(String s) {
return Arrays.stream(s.split(",")).collect(Collectors.toSet());
}
}
|
repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\entity\SysClientDetails.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8088
spring:
datasource:
quartz:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo?serverTimezone=GMT%2B8
username: root
password: 123456
quartz:
job-store-type: jdbc # 使用数据库存储
scheduler-name: hyhScheduler # 相同 Scheduler 名字的节点,形成一个 Quartz 集群
wait-for-jobs-to-complete-on-shutdown: true # 应用关闭时,是否等待定时任务执行完成。默认为 false ,建议设置为 true
jdbc:
initialize-schema: never # 是否自动使用 SQL 初始化 Quartz 表结构。这里设置成 never ,我们手动创建表结构。
properties:
org:
quartz:
# JobStore 相关配置
jobStore:
dataSource: quartzDataSource # 使用的数据源
class: org.quartz.impl.jdbcjobstore.JobStoreTX # JobStore 实现类
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelega
|
te
tablePrefix: QRTZ_ # Quartz 表前缀
isClustered: true # 是集群模式
clusterCheckinInterval: 1000
useProperties: false
# 线程池相关配置
threadPool:
threadCount: 25 # 线程池大小。默认为 10 。
threadPriority: 5 # 线程优先级
class: org.quartz.simpl.SimpleThreadPool # 线程池类型
|
repos\springboot-demo-master\quartz\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public String getDatabaseCatalog() {
return databaseCatalog;
}
public ProcessEngineConfiguration setDatabaseCatalog(String databaseCatalog) {
this.databaseCatalog = databaseCatalog;
return this;
}
public String getDatabaseSchema() {
return databaseSchema;
}
public ProcessEngineConfiguration setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
return this;
}
public String getXmlEncoding() {
return xmlEncoding;
}
public ProcessEngineConfiguration setXmlEncoding(String xmlEncoding) {
this.xmlEncoding = xmlEncoding;
return this;
}
public Clock getClock() {
return clock;
}
public ProcessEngineConfiguration setClock(Clock clock) {
this.clock = clock;
return this;
}
public AsyncExecutor getAsyncExecutor() {
return asyncExecutor;
}
public ProcessEngineConfiguration setAsyncExecutor(AsyncExecutor asyncExecutor) {
this.asyncExecutor = asyncExecutor;
return this;
}
public int getLockTimeAsyncJobWaitTime() {
return lockTimeAsyncJobWaitTime;
}
public ProcessEngineConfiguration setLockTimeAsyncJobWaitTime(int lockTimeAsyncJobWaitTime) {
this.lockTimeAsyncJobWaitTime = lockTimeAsyncJobWaitTime;
return this;
}
public int getDefaultFailedJobWaitTime() {
return defaultFailedJobWaitTime;
}
public ProcessEngineConfiguration setDefaultFailedJobWaitTime(int defaultFailedJobWaitTime) {
this.defaultFailedJobWaitTime = defaultFailedJobWaitTime;
|
return this;
}
public int getAsyncFailedJobWaitTime() {
return asyncFailedJobWaitTime;
}
public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) {
this.asyncFailedJobWaitTime = asyncFailedJobWaitTime;
return this;
}
public boolean isEnableProcessDefinitionInfoCache() {
return enableProcessDefinitionInfoCache;
}
public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) {
this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache;
return this;
}
public ProcessEngineConfiguration setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) {
this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks;
return this;
}
public boolean isCopyVariablesToLocalForTasks() {
return copyVariablesToLocalForTasks;
}
public void setEngineAgendaFactory(ActivitiEngineAgendaFactory engineAgendaFactory) {
this.engineAgendaFactory = engineAgendaFactory;
}
public ActivitiEngineAgendaFactory getEngineAgendaFactory() {
return engineAgendaFactory;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getId() {
return id;
}
public String getBatchType() {
return batchType;
}
public Collection<String> getBatchTypes() {
return batchTypes;
}
public String getSearchKey() {
return searchKey;
}
public String getSearchKey2() {
return searchKey2;
}
public Date getCreateTimeHigherThan() {
return createTimeHigherThan;
}
public Date getCreateTimeLowerThan() {
return createTimeLowerThan;
|
}
public String getStatus() {
return status;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchQueryImpl.java
| 2
|
请完成以下Java代码
|
private I_M_ShipperTransportation getCreateShipperTransportation(final I_M_Tour_Instance tourInstance)
{
if (_shipperTransportation != null)
{
return _shipperTransportation;
}
//
// Use the shipper transportation passed by paramters if any
_shipperTransportation = getM_ShipperTransportation_Param();
if (_shipperTransportation != null)
{
return _shipperTransportation;
}
//
// Create a new shipper transportation
_shipperTransportation = createShipperTransportation(tourInstance);
return _shipperTransportation;
}
private I_M_ShipperTransportation createShipperTransportation(final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
final I_M_ShipperTransportation shipperTransportation = InterfaceWrapperHelper.newInstance(I_M_ShipperTransportation.class, this);
shipperTransportation.setDateDoc(tourInstance.getDeliveryDate());
shipperTransportation.setShipper_BPartner_ID(p_Shipper_BPartner_ID);
shipperTransportation.setShipper_Location_ID(p_Shipper_Location_ID);
|
final ShipperId shipperId = ShipperId.ofRepoIdOrNull(p_M_Shipper_ID);
if (shipperId != null)
{
shipperTransportationBL.setShipper(shipperTransportation, shipperId);
}
shipperTransportationBL.setC_DocType(shipperTransportation);
shipperTransportation.setIsSOTrx(true);
// 07958
// also set the tour id
shipperTransportation.setM_Tour(tourInstance.getM_Tour());
InterfaceWrapperHelper.save(shipperTransportation);
return shipperTransportation;
}
private Iterator<I_M_DeliveryDay> retrieveSelectedDeliveryDays()
{
return retrieveSelectedRecordsQueryBuilder(I_M_DeliveryDay.class)
//
.orderBy()
.clear()
.addColumn(I_M_DeliveryDay.COLUMN_SeqNo)
.endOrderBy()
//
.create()
.iterate(I_M_DeliveryDay.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\process\M_Tour_Instance_CreateFromSelectedDeliveryDays.java
| 1
|
请完成以下Java代码
|
public void setIsConsiderAttributes (final boolean IsConsiderAttributes)
{
set_Value (COLUMNNAME_IsConsiderAttributes, IsConsiderAttributes);
}
@Override
public boolean isConsiderAttributes()
{
return get_ValueAsBoolean(COLUMNNAME_IsConsiderAttributes);
}
@Override
public void setIsPickingReviewRequired (final boolean IsPickingReviewRequired)
{
set_Value (COLUMNNAME_IsPickingReviewRequired, IsPickingReviewRequired);
}
@Override
public boolean isPickingReviewRequired()
{
return get_ValueAsBoolean(COLUMNNAME_IsPickingReviewRequired);
}
|
@Override
public void setM_Picking_Config_V2_ID (final int M_Picking_Config_V2_ID)
{
if (M_Picking_Config_V2_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Config_V2_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Picking_Config_V2_ID, M_Picking_Config_V2_ID);
}
@Override
public int getM_Picking_Config_V2_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Config_V2_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_Picking_Config_V2.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected ClassLoader createReportClassLoader(final ReportContext reportContext)
{
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader parentClassLoader;
if (developerModeBL.isEnabled())
{
parentClassLoader = JasperCompileClassLoader.builder()
.parentClassLoader(contextClassLoader)
.additionalResourceDirNames(getConfiguredReportsDirs())
.additionalResourceDirNames(getDevelopmentWorkspaceReportsDirs())
.build();
logger.info("Using compile class loader: {}", parentClassLoader);
}
else
{
parentClassLoader = contextClassLoader;
}
final OrgId adOrgId = reportContext.getOrgId();
final JasperClassLoader jasperLoader = JasperClassLoader.builder()
.attachmentEntryService(attachmentEntryService)
.parent(parentClassLoader)
.adOrgId(adOrgId)
.printFormatId(getPrintFormatIdOrNull(reportContext))
.build();
logger.debug("Created jasper loader: {}", jasperLoader);
return jasperLoader;
}
private PrintFormatId getPrintFormatIdOrNull(final ReportContext reportContext)
{
for (final ProcessInfoParameter param : reportContext.getProcessInfoParameters())
{
final String parameterName = param.getParameterName();
if (PARAM_AD_PRINTFORMAT_ID.equals(parameterName))
{
return PrintFormatId.ofRepoIdOrNull(param.getParameterAsInt());
}
}
return null;
}
private List<File> getDevelopmentWorkspaceReportsDirs()
{
|
final File developmentWorkspaceDir = developerModeBL.getDevelopmentWorkspaceDir().orElse(null);
if (developmentWorkspaceDir != null)
{
return DevelopmentWorkspaceJasperDirectoriesFinder.getReportsDirectoriesForWorkspace(developmentWorkspaceDir);
}
else
{
logger.warn("No development workspace directory configured. Not considering workspace reports directories");
return ImmutableList.of();
}
}
private ImmutableList<File> getConfiguredReportsDirs()
{
final String reportsDirs = StringUtils.trimBlankToNull(sysConfigBL.getValue(SYSCONFIG_ReportsDirs));
if (reportsDirs == null)
{
return ImmutableList.of();
}
return Splitter.on(",")
.omitEmptyStrings()
.splitToList(reportsDirs.trim())
.stream()
.map(File::new)
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\server\AbstractReportEngine.java
| 2
|
请完成以下Spring Boot application配置
|
server:
port: 8888
spring:
application:
name: gateway-application
cloud:
# Spring Cloud Gateway 配置项,对应 GatewayProperties 类
gateway:
# 路由配置项,对应 RouteDefinition 数组
routes:
- id: feign
|
-service-route
uri: http://127.0.0.1:8081
predicates:
- Path=/**
|
repos\SpringBoot-Labs-master\labx-14\labx-14-sc-skywalking-springcloudgateway\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* LayoutSection AD_Reference_ID=541981
* Reference name: MobileUI_HUManager_LayoutSection LayoutSection
*/
public static final int LAYOUTSECTION_AD_Reference_ID=541981;
/** DisplayName = DisplayName */
public static final String LAYOUTSECTION_DisplayName = "DisplayName";
/** QR Code = QRCode */
public static final String LAYOUTSECTION_QRCode = "QRCode";
/** EAN Code = EANCode */
public static final String LAYOUTSECTION_EANCode = "EANCode";
/** Locator = Locator */
public static final String LAYOUTSECTION_Locator = "Locator";
/** HUStatus = HUStatus */
public static final String LAYOUTSECTION_HUStatus = "HUStatus";
/** Product = Product */
public static final String LAYOUTSECTION_Product = "Product";
/** Qty = Qty */
public static final String LAYOUTSECTION_Qty = "Qty";
/** Attributes = Attributes */
public static final String LAYOUTSECTION_Attributes = "Attributes";
/** ClearanceStatus = ClearanceStatus */
public static final String LAYOUTSECTION_ClearanceStatus = "ClearanceStatus";
@Override
public void setLayoutSection (final java.lang.String LayoutSection)
{
set_Value (COLUMNNAME_LayoutSection, LayoutSection);
}
@Override
public java.lang.String getLayoutSection()
{
return get_ValueAsString(COLUMNNAME_LayoutSection);
}
@Override
public org.compiere.model.I_MobileUI_HUManager getMobileUI_HUManager()
{
return get_ValueAsPO(COLUMNNAME_MobileUI_HUManager_ID, org.compiere.model.I_MobileUI_HUManager.class);
}
@Override
public void setMobileUI_HUManager(final org.compiere.model.I_MobileUI_HUManager MobileUI_HUManager)
{
set_ValueFromPO(COLUMNNAME_MobileUI_HUManager_ID, org.compiere.model.I_MobileUI_HUManager.class, MobileUI_HUManager);
}
@Override
public void setMobileUI_HUManager_ID (final int MobileUI_HUManager_ID)
{
if (MobileUI_HUManager_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_ID, MobileUI_HUManager_ID);
}
@Override
public int getMobileUI_HUManager_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_ID);
}
@Override
public void setMobileUI_HUManager_LayoutSection_ID (final int MobileUI_HUManager_LayoutSection_ID)
{
if (MobileUI_HUManager_LayoutSection_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_LayoutSection_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_LayoutSection_ID, MobileUI_HUManager_LayoutSection_ID);
}
@Override
public int getMobileUI_HUManager_LayoutSection_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_LayoutSection_ID);
}
@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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_HUManager_LayoutSection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setTimeForPayment(BigInteger value) {
this.timeForPayment = value;
}
/**
* Gets the value of the ordrspReference property.
*
* @return
* possible object is
* {@link ReferenceType }
*
*/
public ReferenceType getOrdrspReference() {
return ordrspReference;
}
/**
* Sets the value of the ordrspReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setOrdrspReference(ReferenceType value) {
this.ordrspReference = value;
}
/**
* DEPRICATED: please use DocumentExtension/MessageFunction instead.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageFunction() {
return messageFunction;
}
/**
* Sets the value of the messageFunction property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageFunction(String value) {
this.messageFunction = value;
}
/**
* Gets the value of the billOfLadingReference property.
*
* @return
* possible object is
* {@link ReferenceType }
*
*/
public ReferenceType getBillOfLadingReference() {
return billOfLadingReference;
}
/**
* Sets the value of the billOfLadingReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setBillOfLadingReference(ReferenceType value) {
this.billOfLadingReference = value;
}
/**
* Gets the value of the supplierOrderReference property.
*
* @return
* possible object is
* {@link ReferenceType }
|
*
*/
public ReferenceType getSupplierOrderReference() {
return supplierOrderReference;
}
/**
* Sets the value of the supplierOrderReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setSupplierOrderReference(ReferenceType value) {
this.supplierOrderReference = value;
}
/**
* Reference to the consignment.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConsignmentReference() {
return consignmentReference;
}
/**
* Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DESADVExtensionType.java
| 2
|
请完成以下Java代码
|
public boolean isAvailable()
{
final GridField gridField = getEditor().getField();
if (gridField == null)
{
return false;
}
final int displayType = gridField.getDisplayType();
if (displayType == DisplayType.Text || displayType == DisplayType.URL)
{
if (gridField.getFieldLength() > gridField.getDisplayLength())
{
return true;
}
else
{
return false;
}
}
else if (displayType == DisplayType.TextLong
|| displayType == DisplayType.Memo)
{
return true;
}
else
{
return false;
}
}
@Override
public boolean isRunnable()
{
return true;
}
@Override
public void run()
{
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
final Object value = editor.getValue();
final String text = value == null ? null : value.toString();
|
final boolean editable = editor.isReadWrite();
final String textNew = startEditor(gridField, text, editable);
if (editable)
{
gridField.getGridTab().setValue(gridField, textNew);
}
// TODO: i think is handled above
// Data Binding
// try
// {
// fireVetoableChange(m_columnName, m_oldText, getText());
// }
// catch (PropertyVetoException pve)
// {
// }
}
protected String startEditor(final GridField gridField, final String text, final boolean editable)
{
final Properties ctx = Env.getCtx();
final String columnName = gridField.getColumnName();
final String title = Services.get(IMsgBL.class).translate(ctx, columnName);
final int windowNo = gridField.getWindowNo();
final Frame frame = Env.getWindow(windowNo);
final String textNew;
if (gridField.getDisplayType() == DisplayType.TextLong)
{
// Start it
HTMLEditor ed = new HTMLEditor (frame, title, text, editable);
textNew = ed.getHtmlText();
}
else
{
final Container comp = (Container)getEditor();
final int fieldLength = gridField.getFieldLength();
textNew = Editor.startEditor(comp, title, text, editable, fieldLength);
}
return textNew;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\TextEditorContextMenuAction.java
| 1
|
请完成以下Java代码
|
public Filter addAttribute(String attribute,Object entity)
{
put(attribute,entity);
return(this);
}
/**
Get rid of a current filter.
*/
public Filter removeAttribute(String attribute)
{
try
{
remove(attribute);
}
catch(NullPointerException exc)
{ // don't really care if this throws a null pointer exception
}
return(this);
}
/**
Does the filter filter this?
*/
public boolean hasAttribute(String attribute)
{
return(containsKey(attribute));
}
/**
Need a way to parse the stream so we can do string comparisons instead
of character comparisons.
*/
private String[] split(String to_split)
{
if ( to_split == null || to_split.length() == 0 )
{
String[] array = new String[0];
return array;
|
}
StringBuffer sb = new StringBuffer(to_split.length()+50);
StringCharacterIterator sci = new StringCharacterIterator(to_split);
int length = 0;
for (char c = sci.first(); c != CharacterIterator.DONE; c = sci.next())
{
if(String.valueOf(c).equals(" "))
length++;
else if(sci.getEndIndex()-1 == sci.getIndex())
length++;
}
String[] array = new String[length];
length = 0;
String tmp = new String();
for (char c = sci.first(); c!= CharacterIterator.DONE; c = sci.next())
{
if(String.valueOf(c).equals(" "))
{
array[length] = tmp;
tmp = new String();
length++;
}
else if(sci.getEndIndex()-1 == sci.getIndex())
{
tmp = tmp+String.valueOf(sci.last());
array[length] = tmp;
tmp = new String();
length++;
}
else
tmp += String.valueOf(c);
}
return(array);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\StringFilter.java
| 1
|
请完成以下Java代码
|
public HistoricActivityInstanceQueryImpl orderByTenantId() {
orderBy(HistoricActivityInstanceQueryProperty.TENANT_ID);
return this;
}
public HistoricActivityInstanceQueryImpl activityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
return this;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getActivityId() {
return activityId;
}
public String getActivityName() {
return activityName;
}
|
public String getActivityType() {
return activityType;
}
public String getAssignee() {
return assignee;
}
public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getDeleteReason() {
return deleteReason;
}
public String getDeleteReasonLike() {
return deleteReasonLike;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricActivityInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public boolean containsValue(Object value) {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsValue() is not supported.");
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException("ProcessVariableMap.remove is unsupported. Use ProcessVariableMap.put(key, null)");
}
@Override
public void clear() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".clear() is not supported.");
}
@Override
|
public Set<String> keySet() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".keySet() is not supported.");
}
@Override
public Collection<Object> values() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".values() is not supported.");
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".entrySet() is not supported.");
}
}
|
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\ProcessVariableMap.java
| 1
|
请完成以下Java代码
|
public static OrderedDocumentsList of(@NonNull final Document document, @NonNull final DocumentQueryOrderByList orderBys) {return new OrderedDocumentsList(ImmutableList.of(document), orderBys);}
@NonNull
public static OrderedDocumentsList ofNullable(@Nullable final Document document)
{
return document != null ? of(document) : newEmpty();
}
public static OrderedDocumentsList newEmpty()
{
return new OrderedDocumentsList(ImmutableList.of(), DocumentQueryOrderByList.EMPTY);
}
public static OrderedDocumentsList newEmpty(@NonNull final DocumentQueryOrderByList orderBys)
{
return new OrderedDocumentsList(ImmutableList.of(), orderBys);
}
public ArrayList<Document> toList()
{
return documents;
}
public ImmutableMap<DocumentId, Document> toImmutableMap()
{
return Maps.uniqueIndex(documents, Document::getDocumentId);
}
public void addDocument(@NonNull final Document document)
{
documents.add(document);
}
public void addDocuments(@NonNull final Collection<Document> documents)
{
if (documents.isEmpty())
{
return;
}
|
documents.forEach(this::addDocument);
}
public int size()
{
return documents.size();
}
public boolean isEmpty()
{
return documents.isEmpty();
}
public Document get(final int index)
{
return documents.get(index);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\OrderedDocumentsList.java
| 1
|
请完成以下Java代码
|
public class DiskSpaceErrorChecker implements ErrorChecker {
private static final Logger LOG = LoggerFactory.getLogger(DiskSpaceErrorChecker.class);
private final ErrorReporter errorReporter;
private final double limit;
public DiskSpaceErrorChecker(ErrorReporter errorReporter, double limit) {
this.errorReporter = errorReporter;
this.limit = limit;
}
@Override
public void check() {
LOG.info("Checking disk space");
FileSystems.getDefault().getFileStores().forEach(fileStore -> {
try {
long totalSpace = fileStore.getTotalSpace();
|
long usableSpace = fileStore.getUsableSpace();
double usablePercentage = ((double) usableSpace) / totalSpace;
LOG.debug("File store {} has {} of {} ({}) usable space",
fileStore, usableSpace, totalSpace, usablePercentage);
if (totalSpace > 0 && usablePercentage < limit) {
String error = String.format("File store %s only has %d%% usable disk space",
fileStore.name(), (int)(usablePercentage * 100));
errorReporter.reportProblem(error);
}
} catch (IOException e) {
LOG.error("Error getting disk space for file store {}", fileStore, e);
}
});
}
}
|
repos\tutorials-master\saas-modules\slack\src\main\java\com\baeldung\examples\slack\DiskSpaceErrorChecker.java
| 1
|
请完成以下Java代码
|
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
|
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootFetchJoinAndQueries\src\main\java\com\bookstore\entity\Author.java
| 1
|
请完成以下Java代码
|
public static InvoiceDocBaseType ofDocBaseType(@NonNull final DocBaseType docBaseType)
{
return ofCode(docBaseType.getCode());
}
@Override
public String getCode()
{
return getDocBaseType().getCode();
}
public boolean isSales()
{
return getSoTrx().isSales();
}
public boolean isPurchase()
{
return getSoTrx().isPurchase();
}
/**
* @return is Account Payable (AP), aka purchase
* @see #isPurchase()
*/
public boolean isAP() {return isPurchase();}
public boolean isCustomerInvoice()
{
return this == CustomerInvoice;
}
public boolean isCustomerCreditMemo()
{
return this == CustomerCreditMemo;
}
|
public boolean isVendorCreditMemo()
{
return this == VendorCreditMemo;
}
public boolean isIncomingCash()
{
return (isSales() && !isCreditMemo()) // ARI
|| (isPurchase() && isCreditMemo()) // APC
;
}
public boolean isOutgoingCash()
{
return !isIncomingCash();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceDocBaseType.java
| 1
|
请完成以下Java代码
|
public void setA_User3 (String A_User3)
{
set_Value (COLUMNNAME_A_User3, A_User3);
}
/** Get A_User3.
@return A_User3 */
public String getA_User3 ()
{
return (String)get_Value(COLUMNNAME_A_User3);
}
/** Set A_User4.
@param A_User4 A_User4 */
public void setA_User4 (String A_User4)
{
set_Value (COLUMNNAME_A_User4, A_User4);
}
/** Get A_User4.
@return A_User4 */
public String getA_User4 ()
{
return (String)get_Value(COLUMNNAME_A_User4);
}
/** Set A_User5.
@param A_User5 A_User5 */
public void setA_User5 (String A_User5)
{
set_Value (COLUMNNAME_A_User5, A_User5);
}
/** Get A_User5.
@return A_User5 */
public String getA_User5 ()
{
return (String)get_Value(COLUMNNAME_A_User5);
}
/** Set A_User6.
@param A_User6 A_User6 */
public void setA_User6 (String A_User6)
{
set_Value (COLUMNNAME_A_User6, A_User6);
}
/** Get A_User6.
@return A_User6 */
public String getA_User6 ()
{
return (String)get_Value(COLUMNNAME_A_User6);
}
/** Set A_User7.
@param A_User7 A_User7 */
public void setA_User7 (String A_User7)
{
set_Value (COLUMNNAME_A_User7, A_User7);
}
/** Get A_User7.
@return A_User7 */
public String getA_User7 ()
{
return (String)get_Value(COLUMNNAME_A_User7);
}
|
/** Set A_User8.
@param A_User8 A_User8 */
public void setA_User8 (String A_User8)
{
set_Value (COLUMNNAME_A_User8, A_User8);
}
/** Get A_User8.
@return A_User8 */
public String getA_User8 ()
{
return (String)get_Value(COLUMNNAME_A_User8);
}
/** Set A_User9.
@param A_User9 A_User9 */
public void setA_User9 (String A_User9)
{
set_Value (COLUMNNAME_A_User9, A_User9);
}
/** Get A_User9.
@return A_User9 */
public String getA_User9 ()
{
return (String)get_Value(COLUMNNAME_A_User9);
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Oth.java
| 1
|
请完成以下Java代码
|
public void setM_DistributionRun_ID (int M_DistributionRun_ID)
{
if (M_DistributionRun_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionRun_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionRun_ID, Integer.valueOf(M_DistributionRun_ID));
}
/** Get Distribution Run.
@return Distribution Run create Orders to distribute products to a selected list of partners
*/
public int getM_DistributionRun_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionRun_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_DistributionRun_ID()));
}
/** Set Distribution Run Line.
@param M_DistributionRunLine_ID
Distribution Run Lines define Distribution List, the Product and Quantiries
*/
public void setM_DistributionRunLine_ID (int M_DistributionRunLine_ID)
{
if (M_DistributionRunLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionRunLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionRunLine_ID, Integer.valueOf(M_DistributionRunLine_ID));
}
/** Get Distribution Run Line.
@return Distribution Run Lines define Distribution List, the Product and Quantiries
*/
public int getM_DistributionRunLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionRunLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Minimum Quantity.
@param MinQty
Minimum quantity for the business partner
*/
public void setMinQty (BigDecimal MinQty)
{
set_Value (COLUMNNAME_MinQty, MinQty);
}
/** Get Minimum Quantity.
@return Minimum quantity for the business partner
*/
public BigDecimal getMinQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinQty);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
|
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Total Quantity.
@param TotalQty
Total Quantity
*/
public void setTotalQty (BigDecimal TotalQty)
{
set_Value (COLUMNNAME_TotalQty, TotalQty);
}
/** Get Total Quantity.
@return Total Quantity
*/
public BigDecimal getTotalQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalQty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionRunLine.java
| 1
|
请完成以下Java代码
|
boolean isEndOfFile() {
return this.character == -1;
}
boolean isEndOfLine() {
return this.character == -1 || (!this.escaped && this.character == '\n');
}
boolean isListDelimiter() {
return !this.escaped && this.character == ',';
}
boolean isPropertyDelimiter() {
return !this.escaped && (this.character == '=' || this.character == ':');
}
char getCharacter() {
return (char) this.character;
}
Location getLocation() {
return new Location(this.reader.getLineNumber(), this.columnNumber);
}
boolean isSameLastLineCommentPrefix() {
return this.lastLineCommentPrefixCharacter == this.character;
}
boolean isCommentPrefixCharacter() {
return this.character == '#' || this.character == '!';
}
boolean isHyphenCharacter() {
return this.character == '-';
|
}
}
/**
* A single document within the properties file.
*/
static class Document {
private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>();
void put(String key, OriginTrackedValue value) {
if (!key.isEmpty()) {
this.values.put(key, value);
}
}
boolean isEmpty() {
return this.values.isEmpty();
}
Map<String, OriginTrackedValue> asMap() {
return this.values;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java
| 1
|
请完成以下Java代码
|
public boolean isCriteriaChanged() {
return criteriaChanged;
}
public boolean hasNewChildPlanItemInstances() {
return newChildPlanItemInstances != null && newChildPlanItemInstances.size() > 0;
}
public List<PlanItemInstanceEntity> getNewChildPlanItemInstances() {
return newChildPlanItemInstances;
}
public boolean criteriaChangedOrNewActiveChildren() {
return criteriaChanged || activeChildren > 0;
}
public List<PlanItemInstanceEntity> getAllChildPlanItemInstances() {
return allChildPlanItemInstances;
}
/**
|
* Returns true, if the given plan item instance has at least one instance in completed state (only possible of course for repetition based plan items).
*
* @param planItemInstance the plan item instance to check for a completed instance of the same plan item
* @return true, if a completed instance was found, false otherwise
*/
public boolean hasCompletedPlanItemInstance(PlanItemInstanceEntity planItemInstance) {
if (allChildPlanItemInstances == null || allChildPlanItemInstances.size() == 0) {
return false;
}
for (PlanItemInstanceEntity childPlanItemInstance : allChildPlanItemInstances) {
if (childPlanItemInstance.getPlanItemDefinitionId().equals(planItemInstance.getPlanItemDefinitionId()) && PlanItemInstanceState.COMPLETED
.equals(childPlanItemInstance.getState())) {
return true;
}
}
return false;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\PlanItemEvaluationResult.java
| 1
|
请完成以下Java代码
|
public Collection<Decision> getOutputDecisions() {
return outputDecisionRefCollection.getReferenceTargetElements(this);
}
public Collection<Decision> getEncapsulatedDecisions() {
return encapsulatedDecisionRefCollection.getReferenceTargetElements(this);
}
public Collection<Decision> getInputDecisions() {
return inputDecisionRefCollection.getReferenceTargetElements(this);
}
public Collection<InputData> getInputData() {
return inputDataRefCollection.getReferenceTargetElements(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionService.class, DMN_ELEMENT_DECISION_SERVICE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(NamedElement.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionService>() {
public DecisionService newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionServiceImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
outputDecisionRefCollection = sequenceBuilder.elementCollection(OutputDecisionReference.class)
.required()
.uriElementReferenceCollection(Decision.class)
|
.build();
encapsulatedDecisionRefCollection = sequenceBuilder.elementCollection(EncapsulatedDecisionReference.class)
.uriElementReferenceCollection(Decision.class)
.build();
inputDecisionRefCollection = sequenceBuilder.elementCollection(InputDecisionReference.class)
.uriElementReferenceCollection(Decision.class)
.build();
inputDataRefCollection = sequenceBuilder.elementCollection(InputDataReference.class)
.uriElementReferenceCollection(InputData.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
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 LocalDate getParameterAsLocalDate()
{
return TimeUtil.asLocalDate(m_Parameter);
}
@Nullable
public LocalDate getParameter_ToAsLocalDate()
{
return TimeUtil.asLocalDate(m_Parameter_To);
}
@Nullable
public ZonedDateTime getParameterAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter);
}
@Nullable
public Instant getParameterAsInstant()
{
return TimeUtil.asInstant(m_Parameter);
}
@Nullable
public ZonedDateTime getParameter_ToAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter_To);
}
@Nullable
public BigDecimal getParameterAsBigDecimal()
{
return toBigDecimal(m_Parameter);
|
}
@Nullable
public BigDecimal getParameter_ToAsBigDecimal()
{
return toBigDecimal(m_Parameter_To);
}
@Nullable
private static BigDecimal toBigDecimal(@Nullable final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof BigDecimal)
{
return (BigDecimal)value;
}
else if (value instanceof Integer)
{
return BigDecimal.valueOf((Integer)value);
}
else
{
return new BigDecimal(value.toString());
}
}
} // ProcessInfoParameter
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfoParameter.java
| 1
|
请完成以下Java代码
|
public void skipAdminUserCreation(User existingUser) {
logDebug("011", "Skip creating initial Admin User, user does exist: {}", existingUser);
}
public void createInitialFilter(Filter filter) {
logInfo("015", "Create initial filter: id={} name={}", filter.getId(), filter.getName());
}
public void skipCreateInitialFilter(String filterName) {
logInfo("016",
"Skip initial filter creation, the filter with this name already exists: {}",
filterName);
}
public void skipAutoDeployment() {
logInfo("020", "ProcessApplication enabled: autoDeployment via springConfiguration#deploymentResourcePattern is disabled");
}
public void autoDeployResources(Set<Resource> resources) {
// Only log the description of `Resource` objects since log libraries that serialize them and
// therefore consume the input stream make the deployment fail since the input stream has
// already been consumed.
Set<String> resourceDescriptions = resources.stream()
.filter(Objects::nonNull)
.map(Resource::getDescription)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
logInfo("021", "Auto-Deploying resources: {}", resourceDescriptions);
}
public void enterLicenseKey(String licenseKeySource) {
logInfo("030", "Setting up license key: {}", licenseKeySource);
}
|
public void enterLicenseKeyFailed(URL licenseKeyFile, Exception e) {
logWarn("031", "Failed setting up license key: {}", licenseKeyFile, e);
}
public void configureJobExecutorPool(Integer corePoolSize, Integer maxPoolSize) {
logInfo("040", "Setting up jobExecutor with corePoolSize={}, maxPoolSize:{}", corePoolSize, maxPoolSize);
}
public SpringBootStarterException exceptionDuringBinding(String message) {
return new SpringBootStarterException(exceptionMessage(
"050", message));
}
public void propertiesApplied(GenericProperties genericProperties) {
logDebug("051", "Properties bound to configuration: {}", genericProperties);
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\SpringBootProcessEngineLogger.java
| 1
|
请完成以下Java代码
|
public int getGL_Fund_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
|
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Fund.java
| 1
|
请完成以下Java代码
|
public String toString()
{
// return "Graph{" +
// "vertexes=" + Arrays.toString(vertexes) +
// '}';
StringBuilder sb = new StringBuilder();
int line = 0;
for (List<Vertex> vertexList : vertexes)
{
sb.append(String.valueOf(line++) + ':' + vertexList.toString()).append("\n");
}
return sb.toString();
}
/**
* 将连续的ns节点合并为一个
*/
public void mergeContinuousNsIntoOne()
{
for (int row = 0; row < vertexes.length - 1; ++row)
{
List<Vertex> vertexListFrom = vertexes[row];
ListIterator<Vertex> listIteratorFrom = vertexListFrom.listIterator();
while (listIteratorFrom.hasNext())
{
Vertex from = listIteratorFrom.next();
if (from.getNature() == Nature.ns)
{
int toIndex = row + from.realWord.length();
ListIterator<Vertex> listIteratorTo = vertexes[toIndex].listIterator();
while (listIteratorTo.hasNext())
{
Vertex to = listIteratorTo.next();
if (to.getNature() == Nature.ns)
{
// 我们不能直接改,因为很多条线路在公用指针
// from.realWord += to.realWord;
logger.info("合并【" + from.realWord + "】和【" + to.realWord + "】");
listIteratorFrom.set(Vertex.newAddressInstance(from.realWord + to.realWord));
// listIteratorTo.remove();
break;
}
}
}
}
}
}
|
/**
* 清空词图
*/
public void clear()
{
for (List<Vertex> vertexList : vertexes)
{
vertexList.clear();
}
size = 0;
}
/**
* 清理from属性
*/
public void clean()
{
for (List<Vertex> vertexList : vertexes)
{
for (Vertex vertex : vertexList)
{
vertex.from = null;
}
}
}
/**
* 获取内部顶点表格,谨慎操作!
*
* @return
*/
public LinkedList<Vertex>[] getVertexes()
{
return vertexes;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\common\WordNet.java
| 1
|
请完成以下Java代码
|
public class GetProcessDefinitionInfoCmd implements Command<ObjectNode>, Serializable {
private static final long serialVersionUID = 1L;
protected String processDefinitionId;
protected ProcessDefinition processDefinition;
public GetProcessDefinitionInfoCmd(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public GetProcessDefinitionInfoCmd(ProcessDefinition processDefinition) {
this(processDefinition.getId());
this.processDefinition = processDefinition;
}
public ObjectNode execute(CommandContext commandContext) {
if (processDefinitionId == null) {
throw new ActivitiIllegalArgumentException("process definition id is null");
}
DeploymentManager deploymentManager = commandContext.getProcessEngineConfiguration().getDeploymentManager();
// make sure the process definition is in the cache
var processDefinition = resolveProcessDefinition(deploymentManager);
return executeInternal(deploymentManager, commandContext, processDefinition);
}
|
protected ProcessDefinition resolveProcessDefinition(DeploymentManager deploymentManager) {
return Optional.ofNullable(processDefinition).orElseGet(() ->
deploymentManager.findDeployedProcessDefinitionById(processDefinitionId)
);
}
protected ObjectNode executeInternal(
DeploymentManager deploymentManager,
CommandContext commandContext,
ProcessDefinition processDefinition
) {
ObjectNode resultNode = null;
ProcessDefinitionInfoCacheObject definitionInfoCacheObject = deploymentManager
.getProcessDefinitionInfoCache()
.get(processDefinitionId);
if (definitionInfoCacheObject != null) {
resultNode = definitionInfoCacheObject.getInfoNode();
}
return resultNode;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetProcessDefinitionInfoCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private IPricingResult computePricesForBasePricingSystem(@NonNull final PricingSystemId basePricingSystemId)
{
final IPricingContext pricingCtx = request.getPricingCtx();
Check.assumeNotNull(pricingCtx, "pricingCtx shall not be null for {}", request);
final IPricingContext basePricingSystemPricingCtx = createBasePricingSystemPricingCtx(pricingCtx, basePricingSystemId);
try
{
return pricingBL.calculatePrice(basePricingSystemPricingCtx);
}
catch (@NonNull final ProductNotOnPriceListException e)
{
Loggables.get().addLog(CalculatePricingConditionsCommand.class.getSimpleName() + ".computePricesForBasePricingSystem caught ProductNotOnPriceListException");
throw e.appendParametersToMessage() // augment and rethrow
.setParameter("Sub-Calculation", "true")
.setParameter("basePricingSystemPricingCtx", basePricingSystemPricingCtx);
}
}
private static IPricingContext createBasePricingSystemPricingCtx(@NonNull final IPricingContext pricingCtx, @NonNull final PricingSystemId basePricingSystemId)
{
Check.assumeNotNull(pricingCtx.getCountryId(), "Given pricingCtx needs to have a country-ID, so we can later dedic the priceListId! pricingCtx={}", pricingCtx);
final IEditablePricingContext newPricingCtx = pricingCtx.copy();
newPricingCtx.setPricingSystemId(basePricingSystemId);
newPricingCtx.setPriceListId(null); // will be recomputed
newPricingCtx.setPriceListVersionId(null); // will be recomputed
newPricingCtx.setSkipCheckingPriceListSOTrxFlag(false);
newPricingCtx.setDisallowDiscount(true);
newPricingCtx.setFailIfNotCalculated();
return newPricingCtx;
}
private void computeDiscountForPricingConditionsBreak(final PricingConditionsResultBuilder result, final PricingConditionsBreak pricingConditionsBreak)
{
final Percent discount;
if (pricingConditionsBreak.isBpartnerFlatDiscount())
|
{
discount = request.getBpartnerFlatDiscount();
}
else
{
discount = pricingConditionsBreak.getDiscount();
}
result.discount(discount);
}
private PricingConditionsBreak findMatchingPricingConditionBreak()
{
if (request.getForcePricingConditionsBreak() != null)
{
return request.getForcePricingConditionsBreak();
}
else
{
final PricingConditions pricingConditions = getPricingConditions();
return pricingConditions.pickApplyingBreak(request.getPricingConditionsBreakQuery());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\impl\CalculatePricingConditionsCommand.java
| 2
|
请完成以下Java代码
|
protected Map<String, CachedEntity> findClassCacheByCheckingSubclasses(Class<?> entityClass) {
for (Class<?> clazz : cachedObjects.keySet()) {
if (entityClass.isAssignableFrom(clazz)) {
return cachedObjects.get(clazz);
}
}
return null;
}
@Override
public void cacheRemove(Class<?> entityClass, String entityId) {
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache == null) {
return;
}
classCache.remove(entityId);
}
@Override
public <T> Collection<CachedEntity> findInCacheAsCachedObjects(Class<T> entityClass) {
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache != null) {
return classCache.values();
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> List<T> findInCache(Class<T> entityClass) {
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache == null) {
classCache = findClassCacheByCheckingSubclasses(entityClass);
}
|
if (classCache != null) {
List<T> entities = new ArrayList<T>(classCache.size());
for (CachedEntity cachedObject : classCache.values()) {
entities.add((T) cachedObject.getEntity());
}
return entities;
}
return emptyList();
}
public Map<Class<?>, Map<String, CachedEntity>> getAllCachedEntities() {
return cachedObjects;
}
@Override
public void close() {}
@Override
public void flush() {}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\cache\EntityCacheImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public <T> Optional<Codec<T>> getCodecFor(Class<T> type) {
return this.delegate.getCodecFor(type);
}
@Override
public PersistenceExceptionTranslator getExceptionTranslator() {
return this.delegate.getExceptionTranslator();
}
@Override
public CodecRegistry getCodecRegistry() {
return this.delegate.getCodecRegistry();
}
@Override
public Mono<ClientSession> getSession(ClientSessionOptions options) {
|
return this.delegate.getSession(options);
}
@Override
public ReactiveMongoDatabaseFactory withSession(ClientSession session) {
return this.delegate.withSession(session);
}
@Override
public boolean isTransactionActive() {
return this.delegate.isTransactionActive();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoReactiveAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ApiResponse<Region> getRegionWithHttpInfo(String albertaApiKey, String _id) throws ApiException {
com.squareup.okhttp.Call call = getRegionValidateBeforeCall(albertaApiKey, _id, null, null);
Type localVarReturnType = new TypeToken<Region>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Daten einer einzelnen Region abrufen (asynchronously)
* Szenario - das WaWi fragt bei Alberta nach, wie die Daten der Region mit der angegebenen Id sind
* @param albertaApiKey (required)
* @param _id eindeutige id der Region (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call getRegionAsync(String albertaApiKey, String _id, final ApiCallback<Region> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
|
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = getRegionValidateBeforeCall(albertaApiKey, _id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<Region>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\RegionApi.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public final class MassPrintingService implements IMassPrintingService
{
private final IArchiveBL archiveService = Services.get(IArchiveBL.class);
/**
* Exports the given data to PDF and creates an <code>AD_Archive</code> with <code>IsDirectPrint='Y'</code> (to trigger a <code>C_Printing_Queue</code> record being created) and
* <code>IsCreatePrintJob='Y'</code> to also trigger a direct <code>C_PrintJob</code> creation.
*/
@Override
public void print(
@NonNull final Resource reportData,
@NonNull final ArchiveInfo archiveInfo)
{
final ArchiveResult archiveResult = archiveService.archive(ArchiveRequest.builder()
.ctx(Env.getCtx())
.trxName(ITrx.TRXNAME_ThreadInherited)
.data(reportData)
.force(true) // archive it even if AutoArchive says no
.save(true)
.isReport(archiveInfo.isReport())
.recordRef(archiveInfo.getRecordRef())
.processId(archiveInfo.getProcessId())
.pinstanceId(archiveInfo.getPInstanceId())
.archiveName(archiveInfo.getName())
|
.bpartnerId(archiveInfo.getBpartnerId())
//
// Ask our printing service to printing it right now:
.isDirectEnqueue(true)
.isDirectProcessQueueItem(true)
.copies(archiveInfo.getCopies())
//
.build());
if (archiveResult.isNoArchive())
{
throw new AdempiereException("No archive created for " + reportData + " and " + archiveInfo);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\adapter\MassPrintingService.java
| 2
|
请完成以下Java代码
|
public class MBankStatement extends X_C_BankStatement
{
public MBankStatement(final Properties ctx, final int C_BankStatement_ID, final String trxName)
{
super(ctx, C_BankStatement_ID, trxName);
if (is_new())
{
// setC_BP_BankAccount_ID (0); // parent
setStatementDate(new Timestamp(System.currentTimeMillis())); // @Date@
setDocAction(DOCACTION_Complete); // CO
setDocStatus(DOCSTATUS_Drafted); // DR
setBeginningBalance(BigDecimal.ZERO);
setStatementDifference(BigDecimal.ZERO);
setEndingBalance(BigDecimal.ZERO);
setIsApproved(false); // N
setIsManual(true); // Y
setPosted(false); // N
super.setProcessed(false);
}
}
|
public MBankStatement(final Properties ctx, final ResultSet rs, final String trxName)
{
super(ctx, rs, trxName);
}
@Override
public void setProcessed(final boolean processed)
{
super.setProcessed(processed);
final BankStatementId bankStatementId = BankStatementId.ofRepoIdOrNull(getC_BankStatement_ID());
if (bankStatementId != null)
{
final IBankStatementDAO bankStatementDAO = Services.get(IBankStatementDAO.class);
bankStatementDAO.updateBankStatementLinesProcessedFlag(bankStatementId, processed);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\model\MBankStatement.java
| 1
|
请完成以下Spring Boot application配置
|
#
# %L
# de-metas-camel-grssignum
# %%
# Copyright (C) 2021 metas GmbH
# %%
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more
|
details.
#
# You should have received a copy of the GNU General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/gpl-2.0.html>.
# L%
#
export.bpartner.retry.count=10
export.bpartner.retry.delay.ms=60000
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class RpPayProduct extends BaseEntity implements Serializable {
private String productCode;
private String productName;
private String auditStatus;
private static final long serialVersionUID = 1L;
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode == null ? null : productCode.trim();
}
public String getProductName() {
return productName;
}
|
public void setProductName(String productName) {
this.productName = productName == null ? null : productName.trim();
}
public String getAuditStatus() {
return auditStatus;
}
public void setAuditStatus(String auditStatus) {
this.auditStatus = auditStatus == null ? null : auditStatus.trim();
}
public String getAuditStatusDesc() {
return PublicEnum.getEnum(this.getAuditStatus()).getDesc();
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpPayProduct.java
| 2
|
请完成以下Java代码
|
public void setExpressionHandler(MethodSecurityExpressionHandler expressionHandler) {
this.registry.setExpressionHandler(expressionHandler);
}
/**
* Configure pre/post-authorization template resolution
* <p>
* By default, this value is <code>null</code>, which indicates that templates should
* not be resolved.
* @param defaults - whether to resolve pre/post-authorization templates parameters
* @since 6.4
*/
public void setTemplateDefaults(AnnotationTemplateExpressionDefaults defaults) {
this.registry.setTemplateDefaults(defaults);
}
/**
* {@inheritDoc}
*/
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* {@inheritDoc}
*/
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
@Override
public Advice getAdvice() {
return this;
}
@Override
public boolean isPerInstance() {
return true;
}
/**
* 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 strategy) {
this.securityContextHolderStrategy = () -> strategy;
}
/**
* Filter a {@code returnedObject} using the {@link PostFilter} annotation that the
* {@link MethodInvocation} specifies.
* @param mi the {@link MethodInvocation} to check check
* @return filtered {@code returnedObject}
*/
@Override
public @Nullable Object invoke(MethodInvocation mi) throws Throwable {
Object returnedObject = mi.proceed();
ExpressionAttribute attribute = this.registry.getAttribute(mi);
if (attribute == null) {
return returnedObject;
}
MethodSecurityExpressionHandler expressionHandler = this.registry.getExpressionHandler();
EvaluationContext ctx = expressionHandler.createEvaluationContext(this::getAuthentication, mi);
return expressionHandler.filter(returnedObject, attribute.getExpression(), ctx);
}
private Authentication getAuthentication() {
Authentication authentication = this.securityContextHolderStrategy.get().getContext().getAuthentication();
if (authentication == null) {
throw new AuthenticationCredentialsNotFoundException(
"An Authentication object was not found in the SecurityContext");
}
return authentication;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PostFilterAuthorizationMethodInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final boolean isCustomLoginPage() {
return this.customLoginPage;
}
/**
* Gets the Authentication Filter
* @return the Authentication Filter
*/
protected final F getAuthenticationFilter() {
return this.authFilter;
}
/**
* Sets the Authentication Filter
* @param authFilter the Authentication Filter
*/
protected final void setAuthenticationFilter(F authFilter) {
this.authFilter = authFilter;
}
/**
* Gets the login page
* @return the login page
*/
protected final String getLoginPage() {
return this.loginPage;
}
/**
* Gets the Authentication Entry Point
* @return the Authentication Entry Point
*/
protected final AuthenticationEntryPoint getAuthenticationEntryPoint() {
return this.authenticationEntryPoint;
}
/**
* Gets the URL to submit an authentication request to (i.e. where username/password
* must be submitted)
* @return the URL to submit an authentication request to
*/
protected final String getLoginProcessingUrl() {
return this.loginProcessingUrl;
}
/**
* Gets the URL to send users to if authentication fails
* @return the URL to send users if authentication fails (e.g. "/login?error").
*/
protected final String getFailureUrl() {
|
return this.failureUrl;
}
/**
* Updates the default values for authentication.
*/
protected final void updateAuthenticationDefaults() {
if (this.loginProcessingUrl == null) {
loginProcessingUrl(this.loginPage);
}
if (this.failureHandler == null) {
failureUrl(this.loginPage + "?error");
}
LogoutConfigurer<B> logoutConfigurer = getBuilder().getConfigurer(LogoutConfigurer.class);
if (logoutConfigurer != null && !logoutConfigurer.isCustomLogoutSuccess()) {
logoutConfigurer.logoutSuccessUrl(this.loginPage + "?logout");
}
}
/**
* Updates the default values for access.
*/
protected final void updateAccessDefaults(B http) {
if (this.permitAll) {
PermitAllSupport.permitAll(http, this.loginPage, this.loginProcessingUrl, this.failureUrl);
}
}
/**
* Sets the loginPage and updates the {@link AuthenticationEntryPoint}.
* @param loginPage
*/
private void setLoginPage(String loginPage) {
this.loginPage = loginPage;
this.authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint(loginPage);
}
private <C> C getBeanOrNull(B http, Class<C> clazz) {
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
if (context == null) {
return null;
}
return context.getBeanProvider(clazz).getIfUnique();
}
@SuppressWarnings("unchecked")
private T getSelf() {
return (T) this;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AbstractAuthenticationFilterConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private Object createInstance(String configurationClassName) {
try {
Class<?> configurationClass = getClass().getClassLoader().loadClass(configurationClassName);
return configurationClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new ProcessEngineException("Could not load '"+configurationClassName+"': the class must be visible from the camunda-wildfly-subsystem module.", e);
}
}
public void initializeServiceBuilder(ManagedProcessEngineMetadata processEngineConfiguration,
ServiceBuilder<?> serviceBuilder, ServiceName name, String jobExecutorName) {
ContextNames.BindInfo datasourceBindInfo = ContextNames.bindInfoFor(processEngineConfiguration.getDatasourceJndiName());
transactionManagerSupplier = serviceBuilder.requires(ServiceName.JBOSS.append("txn").append("TransactionManager"));
datasourceBinderServiceSupplier = serviceBuilder.requires(datasourceBindInfo.getBinderServiceName());
runtimeContainerDelegateSupplier = serviceBuilder.requires(ServiceNames.forMscRuntimeContainerDelegate());
mscRuntimeContainerJobExecutorSupplier = serviceBuilder.requires(ServiceNames.forMscRuntimeContainerJobExecutorService(jobExecutorName));
serviceBuilder.setInitialMode(Mode.ACTIVE);
serviceBuilder.requires(ServiceNames.forMscExecutorService());
|
processEngineConsumers.add(serviceBuilder.provides(name));
this.executorSupplier = JBossCompatibilityExtension.addServerExecutorDependency(serviceBuilder);
JBossCompatibilityExtension.addServerExecutorDependency(serviceBuilder);
}
public ProcessEngine getProcessEngine() {
return processEngine;
}
public ManagedProcessEngineMetadata getProcessEngineMetadata() {
return processEngineMetadata;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscManagedProcessEngineController.java
| 2
|
请完成以下Java代码
|
public class ParseHandler extends DefaultHandler {
protected String defaultNamespace;
protected Parse parse;
protected Locator locator;
protected Deque<Element> elementStack = new ArrayDeque<>();
public ParseHandler(Parse parse) {
this.parse = parse;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
Element element = new Element(uri, localName, qName, attributes, locator);
if (elementStack.isEmpty()) {
parse.rootElement = element;
} else {
elementStack.peek().add(element);
}
elementStack.push(element);
}
public void characters(char[] ch, int start, int length) throws SAXException {
elementStack.peek().appendText(String.valueOf(ch, start, length));
}
public void endElement(String uri, String localName, String qName) throws SAXException {
elementStack.pop();
}
public void error(SAXParseException e) {
parse.addError(e);
}
public void fatalError(SAXParseException e) {
|
parse.addError(e);
}
public void warning(SAXParseException e) {
parse.addWarning(e);
}
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
public void setDefaultNamespace(String defaultNamespace) {
this.defaultNamespace = defaultNamespace;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\ParseHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static String getHavingValue(AnnotationAttributes annotationAttributes) {
Object havingValue = annotationAttributes.get("havingValue");
Assert.state(havingValue != null, "'havingValue' must not be null");
return havingValue.toString();
}
private String getPrefix(AnnotationAttributes annotationAttributes) {
String prefix = annotationAttributes.getString("prefix").trim();
if (StringUtils.hasText(prefix) && !prefix.endsWith(".")) {
prefix = prefix + ".";
}
return prefix;
}
private String[] getNames(AnnotationAttributes annotationAttributes) {
String[] value = (String[]) annotationAttributes.get("value");
String[] name = (String[]) annotationAttributes.get("name");
Assert.state(value != null, "'value' must not be null");
Assert.state(name != null, "'name' must not be null");
Assert.state(value.length > 0 || name.length > 0,
() -> "The name or value attribute of @%s must be specified"
.formatted(ClassUtils.getShortName(this.annotationType)));
Assert.state(value.length == 0 || name.length == 0,
() -> "The name and value attributes of @%s are exclusive"
.formatted(ClassUtils.getShortName(this.annotationType)));
return (value.length > 0) ? value : name;
}
private void collectProperties(PropertyResolver resolver, List<String> missing, List<String> nonMatching) {
for (String name : this.names) {
String key = this.prefix + name;
if (resolver.containsProperty(key)) {
if (!isMatch(resolver.getProperty(key), this.havingValue)) {
nonMatching.add(name);
}
}
else {
if (!this.matchIfMissing) {
missing.add(name);
}
}
|
}
}
private boolean isMatch(@Nullable String value, String requiredValue) {
if (StringUtils.hasLength(requiredValue)) {
return requiredValue.equalsIgnoreCase(value);
}
return !"false".equalsIgnoreCase(value);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("(");
result.append(this.prefix);
if (this.names.length == 1) {
result.append(this.names[0]);
}
else {
result.append("[");
result.append(StringUtils.arrayToCommaDelimitedString(this.names));
result.append("]");
}
if (StringUtils.hasLength(this.havingValue)) {
result.append("=").append(this.havingValue);
}
result.append(")");
return result.toString();
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\OnPropertyCondition.java
| 2
|
请完成以下Java代码
|
public class FlowableMultiInstanceActivityCompletedEventImpl extends FlowableMultiInstanceActivityEventImpl implements
FlowableMultiInstanceActivityCompletedEvent {
protected int numberOfInstances;
protected int numberOfActiveInstances;
protected int numberOfCompletedInstances;
public FlowableMultiInstanceActivityCompletedEventImpl(FlowableEngineEventType type) {
super(type);
}
@Override
public int getNumberOfInstances() {
return numberOfInstances;
}
public void setNumberOfInstances(int numberOfInstances) {
this.numberOfInstances = numberOfInstances;
}
|
@Override
public int getNumberOfActiveInstances() {
return numberOfActiveInstances;
}
public void setNumberOfActiveInstances(int numberOfActiveInstances) {
this.numberOfActiveInstances = numberOfActiveInstances;
}
@Override
public int getNumberOfCompletedInstances() {
return numberOfCompletedInstances;
}
public void setNumberOfCompletedInstances(int numberOfCompletedInstances) {
this.numberOfCompletedInstances = numberOfCompletedInstances;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\delegate\event\impl\FlowableMultiInstanceActivityCompletedEventImpl.java
| 1
|
请完成以下Java代码
|
public int getM_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Locator_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
|
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Stock_Detail_V.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Integer add(UserAddDTO addDTO) {
// 插入用户记录,返回编号
Integer returnId = UUID.randomUUID().hashCode();
// 返回用户编号
return returnId;
}
/**
* 更新指定用户编号的用户
*
* @param updateDTO 更新用户信息 DTO
* @return 是否修改成功
*/
@PostMapping("/update") // URL 修改成 /update ,RequestMethod 改成 POST
public Boolean update(UserUpdateDTO updateDTO) {
// 更新用户记录
Boolean success = true;
// 返回更新是否成功
|
return success;
}
/**
* 删除指定用户编号的用户
*
* @param id 用户编号
* @return 是否删除成功
*/
@DeleteMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE
public Boolean delete(@RequestParam("id") Integer id) {
// 删除用户记录
Boolean success = false;
// 返回是否更新成功
return success;
}
}
|
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-01\src\main\java\cn\iocoder\springboot\lab23\springmvc\controller\UserController2.java
| 2
|
请完成以下Java代码
|
private ProcessClassInfo getProcessClassInfo()
{
if (_processClassInfo == null)
{
_processClassInfo = ProcessClassInfo.of(_processClass);
}
return _processClassInfo;
}
public ProcessPreconditionChecker setPreconditionsContext(final IProcessPreconditionsContext preconditionsContext)
{
setPreconditionsContext(() -> preconditionsContext);
return this;
}
public ProcessPreconditionChecker setPreconditionsContext(final Supplier<IProcessPreconditionsContext> preconditionsContextSupplier)
{
|
_preconditionsContextSupplier = preconditionsContextSupplier;
return this;
}
private IProcessPreconditionsContext getPreconditionsContext()
{
Check.assumeNotNull(_preconditionsContextSupplier, "Parameter preconditionsContextSupplier is not null");
final IProcessPreconditionsContext preconditionsContext = _preconditionsContextSupplier.get();
Check.assumeNotNull(preconditionsContext, "Parameter preconditionsContext is not null");
return preconditionsContext;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessPreconditionChecker.java
| 1
|
请完成以下Java代码
|
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", categoryId=").append(categoryId);
sb.append(", title=").append(title);
sb.append(", pic=").append(pic);
sb.append(", productCount=").append(productCount);
|
sb.append(", recommendStatus=").append(recommendStatus);
sb.append(", createTime=").append(createTime);
sb.append(", collectCount=").append(collectCount);
sb.append(", readCount=").append(readCount);
sb.append(", commentCount=").append(commentCount);
sb.append(", albumPics=").append(albumPics);
sb.append(", description=").append(description);
sb.append(", showStatus=").append(showStatus);
sb.append(", forwardCount=").append(forwardCount);
sb.append(", categoryName=").append(categoryName);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubject.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OrderEmailPropagationSysConfigRepository
{
private final ISysConfigBL sysConfigBL;
public static final String SYS_CONFIG_C_Order_Email_Propagation = "de.metas.order.C_Order_Email_Propagation";
private static final String SYS_CONFIG_C_Order_Email_Propagation_Default = "N";
public OrderEmailPropagationSysConfigRepository(@NonNull final ISysConfigBL sysConfigBL)
{
this.sysConfigBL = sysConfigBL;
}
final String getValue(final ClientAndOrgId clientAndOrgId)
{
return sysConfigBL.getValue(SYS_CONFIG_C_Order_Email_Propagation,
SYS_CONFIG_C_Order_Email_Propagation_Default,
clientAndOrgId);
}
public boolean isPropagateToDocOutboundLog(@NonNull final ClientAndOrgId clientAndOrgId)
{
final String value = getValue(clientAndOrgId);
|
return value.contains("C_Doc_Outbound_Log"); // #12448 It should be de.metas.document.archive.model.I_C_Doc_Outbound_Log.Table_Name but that's not available in de.metas.business
}
public boolean isPropagateToMInOut(@NonNull final ClientAndOrgId clientAndOrgId)
{
final String value = getValue(clientAndOrgId);
return value.contains(I_M_InOut.Table_Name);
}
public boolean isPropagateToCInvoice(@NonNull final ClientAndOrgId clientAndOrgId)
{
final String value = getValue(clientAndOrgId);
return value.contains(I_C_Invoice.Table_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderEmailPropagationSysConfigRepository.java
| 2
|
请完成以下Java代码
|
public final class DefaultServerGenerateOneTimeTokenRequestResolver
implements ServerGenerateOneTimeTokenRequestResolver {
private static final String USERNAME = "username";
private static final Duration DEFAULT_EXPIRES_IN = Duration.ofMinutes(5);
private Duration expiresIn = DEFAULT_EXPIRES_IN;
@Override
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
public Mono<GenerateOneTimeTokenRequest> resolve(ServerWebExchange exchange) {
// @formatter:off
return exchange.getFormData()
.mapNotNull((data) -> data.getFirst(USERNAME))
|
.switchIfEmpty(Mono.empty())
.map((username) -> new GenerateOneTimeTokenRequest(username, this.expiresIn));
// @formatter:on
}
/**
* Sets one-time token expiration time
* @param expiresIn one-time token expiration time
*/
public void setExpiresIn(Duration expiresIn) {
Assert.notNull(expiresIn, "expiresIn cannot be null");
this.expiresIn = expiresIn;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\ott\DefaultServerGenerateOneTimeTokenRequestResolver.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.