instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public java.sql.Timestamp getTimeSlotEnd ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_TimeSlotEnd);
}
/** Set Startzeitpunkt.
@param TimeSlotStart
Time when timeslot starts
*/
@Override
public void setTimeSlotStart (java.sql.Timestamp TimeSlotStart)
{
set_Value (COLUMNNAME_TimeSlotStart, TimeSlotStart);
}
/** Get Startzeitpunkt.
@return Time when timeslot starts
*/
@Override
public java.sql.Timestamp getTimeSlotStart ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_TimeSlotStart);
}
|
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ResourceType.java
| 1
|
请完成以下Java代码
|
public void windowStateChanged(WindowEvent e)
{
// The Customize Window was closed
if (e.getID() == WindowEvent.WINDOW_CLOSED && e.getSource() == m_requestFrame
&& m_model != null // sometimes we get NPE
)
{
final I_RV_R_Group_Prospect contact = m_model.getRV_R_Group_Prospect(false);
m_model.unlockContact(contact);
m_frame.setEnabled(true);
AEnv.showWindow(m_frame);
m_requestFrame = null;
refreshAll(true);
m_updater.start();
}
}
// @Override
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getSource() == m_model.getContactsGridTab() && evt.getPropertyName().equals(GridTab.PROPERTY))
{
updateFieldsStatus();
m_model.queryDetails();
vtableAutoSizeAll();
}
|
}
public static Image getImage(String fileNameInImageDir)
{
URL url = CallCenterForm.class.getResource("images/" + fileNameInImageDir);
if (url == null)
{
log.error("Not found: " + fileNameInImageDir);
return null;
}
Toolkit tk = Toolkit.getDefaultToolkit();
return tk.getImage(url);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\CallCenterForm.java
| 1
|
请完成以下Java代码
|
public static RegexRequestMatcher regexMatcher(HttpMethod method, String pattern) {
Assert.notNull(method, "method cannot be null");
Assert.hasText(pattern, "pattern cannot be empty");
return new RegexRequestMatcher(pattern, method.name());
}
/**
* Creates a case-sensitive {@code Pattern} instance to match against the request.
* @param pattern the regular expression to compile into a pattern.
* @param httpMethod the HTTP method to match. May be null to match all methods.
*/
public RegexRequestMatcher(String pattern, @Nullable String httpMethod) {
this(pattern, httpMethod, false);
}
/**
* As above, but allows setting of whether case-insensitive matching should be used.
* @param pattern the regular expression to compile into a pattern.
* @param httpMethod the HTTP method to match. May be null to match all methods.
* @param caseInsensitive if true, the pattern will be compiled with the
* {@link Pattern#CASE_INSENSITIVE} flag set.
*/
public RegexRequestMatcher(String pattern, @Nullable String httpMethod, boolean caseInsensitive) {
this.pattern = Pattern.compile(pattern, caseInsensitive ? CASE_INSENSITIVE : DEFAULT);
this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
}
/**
* Performs the match of the request URL ({@code servletPath + pathInfo + queryString}
* ) against the compiled pattern. If the query string is present, a question mark
* will be prepended.
* @param request the request to match
* @return true if the pattern matches the URL, false otherwise.
*/
@Override
public boolean matches(HttpServletRequest request) {
if (this.httpMethod != null && request.getMethod() != null
&& this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
return false;
}
String url = request.getServletPath();
|
String pathInfo = request.getPathInfo();
String query = request.getQueryString();
if (pathInfo != null || query != null) {
StringBuilder sb = new StringBuilder(url);
if (pathInfo != null) {
sb.append(pathInfo);
}
if (query != null) {
sb.append('?').append(query);
}
url = sb.toString();
}
logger.debug(LogMessage.format("Checking match of request : '%s'; against '%s'", url, this.pattern));
return this.pattern.matcher(url).matches();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Regex [pattern='").append(this.pattern).append("'");
if (this.httpMethod != null) {
sb.append(", ").append(this.httpMethod);
}
sb.append("]");
return sb.toString();
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\RegexRequestMatcher.java
| 1
|
请完成以下Java代码
|
public Integer next() {
exist(cursor);
return NUMBER_LIST.get(cursor++);
}
private void exist(int current) {
if (current >= NUMBER_LIST.size()) {
throw new NoSuchElementException();
}
}
@Override
public boolean hasNext() {
if (cursor > NUMBER_LIST.size()) {
return false;
}
for (int i = cursor; i < NUMBER_LIST.size(); i++) {
if (isPrime(NUMBER_LIST.get(i))) {
cursor = i;
return true;
|
}
}
return false;
}
private boolean isPrime(int number) {
for (int i = 2; i <= number / 2; ++i) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-2\src\main\java\com\baeldung\collections\iterator\Numbers.java
| 1
|
请完成以下Java代码
|
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_User_ID()));
}
/** Set Opt-out Date.
@param OptOutDate
Date the contact opted out
*/
public void setOptOutDate (Timestamp OptOutDate)
{
set_ValueNoCheck (COLUMNNAME_OptOutDate, OptOutDate);
}
/** Get Opt-out Date.
@return Date the contact opted out
*/
public Timestamp getOptOutDate ()
{
return (Timestamp)get_Value(COLUMNNAME_OptOutDate);
}
public I_R_InterestArea getR_InterestArea() throws RuntimeException
{
return (I_R_InterestArea)MTable.get(getCtx(), I_R_InterestArea.Table_Name)
.getPO(getR_InterestArea_ID(), get_TrxName()); }
/** Set Interest Area.
@param R_InterestArea_ID
Interest Area or Topic
*/
public void setR_InterestArea_ID (int R_InterestArea_ID)
{
if (R_InterestArea_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID));
}
/** Get Interest Area.
@return Interest Area or Topic
*/
public int getR_InterestArea_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Subscribe Date.
@param SubscribeDate
Date the contact actively subscribed
*/
public void setSubscribeDate (Timestamp SubscribeDate)
{
set_ValueNoCheck (COLUMNNAME_SubscribeDate, SubscribeDate);
}
/** Get Subscribe Date.
@return Date the contact actively subscribed
*/
public Timestamp getSubscribeDate ()
{
return (Timestamp)get_Value(COLUMNNAME_SubscribeDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_ContactInterest.java
| 1
|
请完成以下Java代码
|
public String toString ()
{
return toString(false);
} // toString
/**
* String Representation
* @param withData with data
* @return info
*/
public String toString (boolean withData)
{
StringBuffer sb = new StringBuffer("PrintDataGroup[");
sb.append("Groups=");
for (int i = 0; i < m_groups.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_groups.get(i));
}
if (withData)
{
Iterator it = m_groupMap.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupMap.get(key);
sb.append(":").append(key).append("=").append(value);
|
}
}
sb.append(";Functions=");
for (int i = 0; i < m_functions.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_functions.get(i));
}
if (withData)
{
Iterator it = m_groupFunction.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupFunction.get(key);
sb.append(":").append(key).append("=").append(value);
}
}
sb.append("]");
return sb.toString();
} // toString
} // PrintDataGroup
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataGroup.java
| 1
|
请完成以下Java代码
|
public <X> JsonSerde<X> copyWithType(Class<? super X> newTargetType) {
return new JsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
/**
* Copies this serde with same configuration, except new target type reference is used.
* @param newTargetType type reference forced for serialization, and used as default for deserialization, not null
* @param <X> new deserialization result type and serialization source type
* @return new instance of serde with type changes
* @since 2.6
*/
public <X> JsonSerde<X> copyWithType(TypeReference<? super X> newTargetType) {
return new JsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
/**
* Copies this serde with same configuration, except new target java type is used.
* @param newTargetType java type forced for serialization, and used as default for deserialization, not null
* @param <X> new deserialization result type and serialization source type
* @return new instance of serde with type changes
* @since 2.6
*/
public <X> JsonSerde<X> copyWithType(JavaType newTargetType) {
return new JsonSerde<>(this.jsonSerializer.copyWithType(newTargetType),
this.jsonDeserializer.copyWithType(newTargetType));
}
// Fluent API
/**
* Designate this Serde for serializing/deserializing keys (default is values).
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> forKeys() {
this.jsonSerializer.forKeys();
this.jsonDeserializer.forKeys();
return this;
}
/**
|
* Configure the serializer to not add type information.
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> noTypeInfo() {
this.jsonSerializer.noTypeInfo();
return this;
}
/**
* Don't remove type information headers after deserialization.
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> dontRemoveTypeHeaders() {
this.jsonDeserializer.dontRemoveTypeHeaders();
return this;
}
/**
* Ignore type information headers and use the configured target class.
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> ignoreTypeHeaders() {
this.jsonDeserializer.ignoreTypeHeaders();
return this;
}
/**
* Use the supplied {@link org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper}.
* @param mapper the mapper.
* @return the serde.
* @since 2.3
*/
public JsonSerde<T> typeMapper(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper mapper) {
this.jsonSerializer.setTypeMapper(mapper);
this.jsonDeserializer.setTypeMapper(mapper);
return this;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JsonSerde.java
| 1
|
请完成以下Java代码
|
private String determineSuffix(Qualifier qualifier) {
String id = qualifier.getId();
if (id.equals("RELEASE")) {
return "";
}
StringBuilder sb = new StringBuilder(" (");
if (id.contains("SNAPSHOT")) {
sb.append("SNAPSHOT");
}
else {
sb.append(id);
if (qualifier.getVersion() != null) {
sb.append(qualifier.getVersion());
}
}
sb.append(")");
return sb.toString();
}
|
private static final class VersionMetadataElementComparator implements Comparator<DefaultMetadataElement> {
private static final VersionParser versionParser = VersionParser.DEFAULT;
@Override
public int compare(DefaultMetadataElement o1, DefaultMetadataElement o2) {
Version o1Version = versionParser.parse(o1.getId());
Version o2Version = versionParser.parse(o2.getId());
return o1Version.compareTo(o2Version);
}
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\SpringBootMetadataReader.java
| 1
|
请完成以下Java代码
|
private void entityEncrypt(Object obj) throws Exception {
log.info("obj.getClass().getName(): {}", obj.getClass().getName());
String objFqn = obj.getClass().getName();
List<String> objFieldList = ENTITY_FILED_ANN_MAP.getOrDefault(objFqn, new ArrayList<>());
MetaObject metaObject = SystemMetaObject.forObject(obj);
if (!CollectionUtils.isEmpty(objFieldList)) {
// 不为空,已缓存
objFieldList.forEach(s -> cryptField(s, metaObject));
} else {
// 为空,需要遍历 再缓存
CryptEntity declaredAnnotation = obj.getClass().getDeclaredAnnotation(CryptEntity.class);
if (Objects.isNull(declaredAnnotation)) {
return;
}
Arrays.stream(obj.getClass().getDeclaredFields())
.filter(item -> Objects.nonNull(item.getAnnotation(CryptField.class)))
.forEach(item -> {
String fieldName = item.getName();
System.out.println(fieldName);
objFieldList.add(fieldName);
cryptField(fieldName, metaObject);
});
ENTITY_FILED_ANN_MAP.put(objFqn, objFieldList);
}
}
private void cryptField(String fieldName, MetaObject metaObject) {
Object fieldVal = metaObject.getValue(fieldName);
if (Objects.isNull(fieldVal)) {
return;
}
|
if (fieldVal instanceof CharSequence) {
metaObject.setValue(fieldName, encrypt.encrypt(fieldVal.toString()));
}
}
@Override
public Object plugin(Object target) {
if (target instanceof ParameterHandler) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties properties) {
}
}
|
repos\spring-boot-quick-master\mybatis-crypt-plugin\src\main\java\com\quick\db\crypt\intercept\CryptParamInterceptor.java
| 1
|
请完成以下Java代码
|
public String getName() {
return this.name;
}
public Class<?> getReturnType() {
return this.returnType;
}
public Class<?>[] getParamTypes() {
return this.paramTypes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Arrays.hashCode(paramTypes);
result = prime * result + ((returnType == null) ? 0 : returnType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MethodInfo other = (MethodInfo) obj;
|
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (!Arrays.equals(paramTypes, other.paramTypes)) {
return false;
}
if (returnType == null) {
return other.returnType == null;
} else {
return returnType.equals(other.returnType);
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\MethodInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isSaveAttributes() {
return getSettings().isSaveAttributes();
}
public boolean isSaveCredentials() {
return getSettings().isSaveCredentials();
}
public boolean isSaveCalculatedFields() {
return getSettings().isSaveCalculatedFields();
}
public EntityId getInternalId(EntityId externalId) {
var result = externalToInternalIdMap.get(externalId);
log.debug("[{}][{}] Local cache {} for id", externalId.getEntityType(), externalId.getId(), result != null ? "hit" : "miss");
return result;
}
public void putInternalId(EntityId externalId, EntityId internalId) {
log.debug("[{}][{}] Local cache put: {}", externalId.getEntityType(), externalId.getId(), internalId);
externalToInternalIdMap.put(externalId, internalId);
}
public void registerResult(EntityType entityType, boolean created) {
EntityTypeLoadResult result = results.computeIfAbsent(entityType, EntityTypeLoadResult::new);
if (created) {
result.setCreated(result.getCreated() + 1);
} else {
result.setUpdated(result.getUpdated() + 1);
}
}
public void registerDeleted(EntityType entityType) {
EntityTypeLoadResult result = results.computeIfAbsent(entityType, EntityTypeLoadResult::new);
result.setDeleted(result.getDeleted() + 1);
}
public void addRelations(Collection<EntityRelation> values) {
relations.addAll(values);
}
public void addReferenceCallback(EntityId externalId, ThrowingRunnable tr) {
if (tr != null) {
|
referenceCallbacks.put(externalId, tr);
}
}
public void addEventCallback(ThrowingRunnable tr) {
if (tr != null) {
eventCallbacks.add(tr);
}
}
public void registerNotFound(EntityId externalId) {
notFoundIds.add(externalId);
}
public boolean isNotFound(EntityId externalId) {
return notFoundIds.contains(externalId);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\data\EntitiesImportCtx.java
| 2
|
请完成以下Java代码
|
public void addDeployedArtifact(Object deployedArtifact) {
if (deployedArtifacts == null) {
deployedArtifacts = new HashMap<>();
}
Class<?> clazz = deployedArtifact.getClass();
List<Object> artifacts = deployedArtifacts.get(clazz);
if (artifacts == null) {
artifacts = new ArrayList<>();
deployedArtifacts.put(clazz, artifacts);
}
artifacts.add(deployedArtifact);
}
@SuppressWarnings("unchecked")
public <T> List<T> getDeployedArtifacts(Class<T> clazz) {
return (List<T>) deployedArtifacts.get(clazz);
}
// getters and setters //////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setResources(Map<String, ResourceEntity> resources) {
this.resources = resources;
|
}
@Override
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean isNew) {
this.isNew = isNew;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DeploymentEntity[id=" + id + ", name=" + name + "]";
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeploymentEntity.java
| 1
|
请完成以下Java代码
|
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setIsAcknowledged (final boolean IsAcknowledged)
{
set_Value (COLUMNNAME_IsAcknowledged, IsAcknowledged);
}
@Override
public boolean isAcknowledged()
{
return get_ValueAsBoolean(COLUMNNAME_IsAcknowledged);
}
@Override
public void setMsgText (final java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
|
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setRoot_AD_Table_ID (final int Root_AD_Table_ID)
{
if (Root_AD_Table_ID < 1)
set_Value (COLUMNNAME_Root_AD_Table_ID, null);
else
set_Value (COLUMNNAME_Root_AD_Table_ID, Root_AD_Table_ID);
}
@Override
public int getRoot_AD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Root_AD_Table_ID);
}
@Override
public void setRoot_Record_ID (final int Root_Record_ID)
{
if (Root_Record_ID < 1)
set_Value (COLUMNNAME_Root_Record_ID, null);
else
set_Value (COLUMNNAME_Root_Record_ID, Root_Record_ID);
}
@Override
public int getRoot_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Root_Record_ID);
}
/**
* Severity AD_Reference_ID=541949
* Reference name: Severity
*/
public static final int SEVERITY_AD_Reference_ID=541949;
/** Notice = N */
public static final String SEVERITY_Notice = "N";
/** Error = E */
public static final String SEVERITY_Error = "E";
@Override
public void setSeverity (final java.lang.String Severity)
{
set_Value (COLUMNNAME_Severity, Severity);
}
@Override
public java.lang.String getSeverity()
{
return get_ValueAsString(COLUMNNAME_Severity);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Record_Warning.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
final Iterator<I_C_Dunning_Candidate> it = retrieveSelectionIterator();
setDunningGrace(it, p_DunningGrace);
return "@Updated@";
}
private void setDunningGrace(final Iterator<I_C_Dunning_Candidate> it, final Timestamp dunningGrace)
{
while (it.hasNext())
{
final I_C_Dunning_Candidate candidate = it.next();
setDunningGrace(candidate, dunningGrace);
}
}
private void setDunningGrace(final I_C_Dunning_Candidate candidate, final Timestamp dunningGrace)
{
candidate.setDunningGrace(dunningGrace);
// We want to make sure that model validators are triggered EVEN if the old DunningGrace value equals with new DunningGrace value
markColumnChanged(candidate, I_C_Dunning_Candidate.COLUMNNAME_DunningGrace);
save(candidate);
}
private Iterator<I_C_Dunning_Candidate> retrieveSelectionIterator()
{
final StringBuilder sqlWhere = new StringBuilder();
final List<Object> params = new ArrayList<>();
if (!Check.isEmpty(getProcessInfo().getWhereClause(), true))
{
sqlWhere.append(getProcessInfo().getWhereClause())
|
.append(" AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + " = 'N'"); // 03663 : Must make sure to take only unprocessed candidates.
}
else
{
// We have no where clause. Assume all unprocessed candidates.
sqlWhere.append(I_C_Dunning_Candidate.COLUMNNAME_IsActive + " = 'Y'")
.append(" AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + " = 'N'");
}
return new Query(getCtx(), I_C_Dunning_Candidate.Table_Name, sqlWhere.toString(), get_TrxName())
.setParameters(params)
.setClient_ID()
.setOnlyActiveRecords(true)
.setRequiredAccess(Access.WRITE)
.iterate(I_C_Dunning_Candidate.class, false); // guaranteed=false
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_Dunning_Candidate_SetDunningGrace.java
| 1
|
请完成以下Java代码
|
public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper) {
return bind(fnMapper, varMapper, null);
}
/**
* Create a bindings.
* @param fnMapper the function mapper to use
* @param varMapper the variable mapper to use
* @param converter custom type converter
* @return tree bindings
*/
public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper, TypeConverter converter) {
Method[] methods = null;
if (!functions.isEmpty()) {
if (fnMapper == null) {
throw new ELException(LocalMessages.get("error.function.nomapper"));
}
methods = new Method[functions.size()];
for (int i = 0; i < functions.size(); i++) {
FunctionNode node = functions.get(i);
String image = node.getName();
Method method = null;
int colon = image.indexOf(':');
if (colon < 0) {
method = fnMapper.resolveFunction("", image);
} else {
method = fnMapper.resolveFunction(image.substring(0, colon), image.substring(colon + 1));
}
if (method == null) {
throw new ELException(LocalMessages.get("error.function.notfound", image));
}
|
if (node.isVarArgs() && method.isVarArgs()) {
if (method.getParameterTypes().length > node.getParamCount() + 1) {
throw new ELException(LocalMessages.get("error.function.params", image));
}
} else {
if (method.getParameterTypes().length != node.getParamCount()) {
throw new ELException(LocalMessages.get("error.function.params", image));
}
}
methods[node.getIndex()] = method;
}
}
ValueExpression[] expressions = null;
if (identifiers.size() > 0) {
expressions = new ValueExpression[identifiers.size()];
for (int i = 0; i < identifiers.size(); i++) {
IdentifierNode node = identifiers.get(i);
ValueExpression expression = null;
if (varMapper != null) {
expression = varMapper.resolveVariable(node.getName());
}
expressions[node.getIndex()] = expression;
}
}
return new Bindings(methods, expressions, converter);
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\Tree.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "oneChannel")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@ApiModelProperty(example = "1")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@ApiModelProperty(example = "The One Channel")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "inbound", allowableValues = "inbound,outbound")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@ApiModelProperty(example = "kafka")
public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
@ApiModelProperty(example = "2010-10-13T14:54:26.750+02:00")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "2")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
|
this.deploymentId = deploymentId;
}
@ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2")
public String getDeploymentUrl() {
return deploymentUrl;
}
public void setDeploymentUrl(String deploymentUrl) {
this.deploymentUrl = deploymentUrl;
}
@ApiModelProperty(example = "Examples")
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setResource(String resource) {
this.resource = resource;
}
@ApiModelProperty(example = "oneChannel.channel")
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2/resources/oneChannel.channel", value = "Contains the actual deployed channel definition JSON.")
public String getResource() {
return resource;
}
@ApiModelProperty(example = "This is a channel definition for testing purposes")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\ChannelDefinitionResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isNameSet() {
return nameSet;
}
public boolean isDescriptionSet() {
return descriptionSet;
}
public boolean isDuedateSet() {
return duedateSet;
}
public boolean isPrioritySet() {
return prioritySet;
}
|
public boolean isParentTaskIdSet() {
return parentTaskIdSet;
}
public boolean isCategorySet() {
return categorySet;
}
public boolean isTenantIdSet() {
return tenantIdSet;
}
public boolean isFormKeySet() {
return formKeySet;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class FileSystemStorageService implements StorageService {
private final Path rootLocation;
@Autowired
public FileSystemStorageService(StorageProperties properties) {
this.rootLocation = Paths.get(properties.getLocation());
}
@Override
public void store(MultipartFile file) {
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (IOException e) {
throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
}
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
@Override
public Path load(String filename) {
return rootLocation.resolve(filename);
|
}
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if(resource.exists() || resource.isReadable()) {
return resource;
}
else {
throw new StorageFileNotFoundException("Could not read file: " + filename);
}
} catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
@Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
@Override
public void init() {
try {
Files.createDirectory(rootLocation);
} catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}
|
repos\SpringBootLearning-master\springboot-upload-file\src\main\java\com\forezp\storage\FileSystemStorageService.java
| 2
|
请完成以下Java代码
|
public class BoundConfigurationProperties {
private final Map<ConfigurationPropertyName, ConfigurationProperty> properties = new LinkedHashMap<>();
/**
* The bean name that this class is registered with.
*/
private static final String BEAN_NAME = BoundConfigurationProperties.class.getName();
void add(ConfigurationProperty configurationProperty) {
this.properties.put(configurationProperty.getName(), configurationProperty);
}
/**
* Get the configuration property bound to the given name.
* @param name the property name
* @return the bound property or {@code null}
*/
public @Nullable ConfigurationProperty get(ConfigurationPropertyName name) {
return this.properties.get(name);
}
/**
* Get all bound properties.
* @return a map of all bound properties
*/
public Map<ConfigurationPropertyName, ConfigurationProperty> getAll() {
return Collections.unmodifiableMap(this.properties);
}
/**
* Return the {@link BoundConfigurationProperties} from the given
* {@link ApplicationContext} if it is available.
* @param context the context to search
* @return a {@link BoundConfigurationProperties} or {@code null}
*/
|
public static @Nullable BoundConfigurationProperties get(ApplicationContext context) {
return (!context.containsBeanDefinition(BEAN_NAME)) ? null
: context.getBean(BEAN_NAME, BoundConfigurationProperties.class);
}
static void register(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "'registry' must not be null");
if (!registry.containsBeanDefinition(BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder.rootBeanDefinition(BoundConfigurationProperties.class)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
.getBeanDefinition();
registry.registerBeanDefinition(BEAN_NAME, definition);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\BoundConfigurationProperties.java
| 1
|
请完成以下Java代码
|
protected DiagramNode transformBoundsForImage(DiagramNode diagramBoundsImage, DiagramNode diagramBoundsXml, DiagramNode elementBounds) {
double scalingFactorX = diagramBoundsImage.getWidth() / diagramBoundsXml.getWidth();
double scalingFactorY = diagramBoundsImage.getWidth() / diagramBoundsXml.getWidth();
DiagramNode elementBoundsForImage = new DiagramNode(elementBounds.getId());
elementBoundsForImage.setX((double) Math.round((elementBounds.getX() - diagramBoundsXml.getX()) * scalingFactorX + diagramBoundsImage.getX()));
elementBoundsForImage.setY((double) Math.round((elementBounds.getY() - diagramBoundsXml.getY()) * scalingFactorY + diagramBoundsImage.getY()));
elementBoundsForImage.setWidth((double) Math.round(elementBounds.getWidth() * scalingFactorX));
elementBoundsForImage.setHeight((double) Math.round(elementBounds.getHeight() * scalingFactorY));
return elementBoundsForImage;
}
protected Map<String, DiagramNode> fixFlowNodePositionsIfModelFromAdonis(Document bpmnModel, Map<String, DiagramNode> elementBoundsFromBpmnDi) {
if (isExportedFromAdonis50(bpmnModel)) {
Map<String, DiagramNode> mapOfFixedBounds = new HashMap<>();
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
xPath.setNamespaceContext(new Bpmn20NamespaceContext());
for (Entry<String, DiagramNode> entry : elementBoundsFromBpmnDi.entrySet()) {
String elementId = entry.getKey();
DiagramNode elementBounds = entry.getValue();
String expression = "local-name(//bpmn:*[@id = '" + elementId + "'])";
try {
XPathExpression xPathExpression = xPath.compile(expression);
String elementLocalName = xPathExpression.evaluate(bpmnModel);
if (!"participant".equals(elementLocalName) && !"lane".equals(elementLocalName) && !"textAnnotation".equals(elementLocalName) && !"group".equals(elementLocalName)) {
|
elementBounds.setX(elementBounds.getX() - elementBounds.getWidth() / 2);
elementBounds.setY(elementBounds.getY() - elementBounds.getHeight() / 2);
}
} catch (XPathExpressionException e) {
throw new FlowableException("Error while evaluating the following XPath expression on a BPMN XML document: '" + expression + "'.", e);
}
mapOfFixedBounds.put(elementId, elementBounds);
}
return mapOfFixedBounds;
} else {
return elementBoundsFromBpmnDi;
}
}
protected boolean isExportedFromAdonis50(Document bpmnModel) {
return "ADONIS".equals(bpmnModel.getDocumentElement().getAttribute("exporter")) && "5.0".equals(bpmnModel.getDocumentElement().getAttribute("exporterVersion"));
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\diagram\ProcessDiagramLayoutFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static Map<String, List<RelyingPartyRegistration>> createMappingByAssertingPartyEntityId(
Collection<RelyingPartyRegistration> rps) {
MultiValueMap<String, RelyingPartyRegistration> result = new LinkedMultiValueMap<>();
for (RelyingPartyRegistration rp : rps) {
result.add(rp.getAssertingPartyMetadata().getEntityId(), rp);
}
return Collections.unmodifiableMap(result);
}
@Override
public RelyingPartyRegistration findByRegistrationId(String id) {
return this.byRegistrationId.get(id);
}
@Override
public RelyingPartyRegistration findUniqueByAssertingPartyEntityId(String entityId) {
Collection<RelyingPartyRegistration> registrations = this.byAssertingPartyEntityId.get(entityId);
|
if (registrations == null) {
return null;
}
if (registrations.size() > 1) {
return null;
}
return registrations.iterator().next();
}
@Override
public Iterator<RelyingPartyRegistration> iterator() {
return this.byRegistrationId.values().iterator();
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\InMemoryRelyingPartyRegistrationRepository.java
| 2
|
请完成以下Java代码
|
public class StandardResponse {
private StatusResponse status;
private String message;
private JsonElement data;
public StandardResponse(StatusResponse status) {
this.status = status;
}
public StandardResponse(StatusResponse status, String message) {
this.status = status;
this.message = message;
}
public StandardResponse(StatusResponse status, JsonElement data) {
this.status = status;
this.data = data;
}
public StatusResponse getStatus() {
return status;
|
}
public void setStatus(StatusResponse status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public JsonElement getData() {
return data;
}
public void setData(JsonElement data) {
this.data = data;
}
}
|
repos\tutorials-master\web-modules\spark-java\src\main\java\com\baeldung\sparkjava\StandardResponse.java
| 1
|
请完成以下Java代码
|
private static void processEvents(Collection<MonitoringEvent> events) {
logger.info("Processing {} events", events.size());
events.forEach(evt -> {
logger.info("Event ID: {}, Name: {}, Type: {}, Status: {}, Device ID: {}, Creation Date: {}",
evt.getEventId(),
evt.getEventName().getValue(),
evt.getEventType().getValue(),
evt.getStatus().getValue(),
evt.getDeviceId().getValue(),
evt.getCreationDate().getValue());
});
}
private static void initialize(final Path snapshotPath) {
announcementWatcher = new HollowFilesystemAnnouncementWatcher(snapshotPath);
blobRetriever = new HollowFilesystemBlobRetriever(snapshotPath);
logger.info("snapshot data file location: {}", snapshotPath.toString());
consumer = new HollowConsumer.Builder<>()
.withAnnouncementWatcher(announcementWatcher)
.withBlobRetriever(blobRetriever)
.withGeneratedAPIClass(MonitoringEventAPI.class)
|
.build();
consumer.triggerRefresh();
monitoringEventAPI = consumer.getAPI(MonitoringEventAPI.class);
}
private static void sleep(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private static Path getSnapshotFilePath() {
String moduleDir = System.getProperty("user.dir");
String snapshotPath = moduleDir + "/.hollow/snapshots";
logger.info("snapshot data directory: {}", snapshotPath);
Path path = Paths.get(snapshotPath);
return path;
}
}
|
repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\consumer\MonitoringEventConsumer.java
| 1
|
请完成以下Java代码
|
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
|
return processDefinitionId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DeadLetterJobQueryImpl.java
| 1
|
请完成以下Java代码
|
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
public String getExecutorParam() {
return executorParam;
}
public void setExecutorParam(String executorParam) {
this.executorParam = executorParam;
}
public String getExecutorShardingParam() {
return executorShardingParam;
}
public void setExecutorShardingParam(String executorShardingParam) {
this.executorShardingParam = executorShardingParam;
}
public int getExecutorFailRetryCount() {
return executorFailRetryCount;
}
public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount;
}
public Date getTriggerTime() {
return triggerTime;
}
public void setTriggerTime(Date triggerTime) {
this.triggerTime = triggerTime;
}
public int getTriggerCode() {
return triggerCode;
}
public void setTriggerCode(int triggerCode) {
this.triggerCode = triggerCode;
}
public String getTriggerMsg() {
|
return triggerMsg;
}
public void setTriggerMsg(String triggerMsg) {
this.triggerMsg = triggerMsg;
}
public Date getHandleTime() {
return handleTime;
}
public void setHandleTime(Date handleTime) {
this.handleTime = handleTime;
}
public int getHandleCode() {
return handleCode;
}
public void setHandleCode(int handleCode) {
this.handleCode = handleCode;
}
public String getHandleMsg() {
return handleMsg;
}
public void setHandleMsg(String handleMsg) {
this.handleMsg = handleMsg;
}
public int getAlarmStatus() {
return alarmStatus;
}
public void setAlarmStatus(int alarmStatus) {
this.alarmStatus = alarmStatus;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLog.java
| 1
|
请完成以下Java代码
|
public int getM_ProductScalePrice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductScalePrice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mindestpreis.
@param PriceLimit
Unterster Preis f�r Kostendeckung
*/
@Override
public void setPriceLimit (java.math.BigDecimal PriceLimit)
{
set_Value (COLUMNNAME_PriceLimit, PriceLimit);
}
/** Get Mindestpreis.
@return Unterster Preis f�r Kostendeckung
*/
@Override
public java.math.BigDecimal getPriceLimit ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLimit);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Auszeichnungspreis.
@param PriceList
Auszeichnungspreis
*/
@Override
public void setPriceList (java.math.BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
/** Get Auszeichnungspreis.
@return Auszeichnungspreis
*/
@Override
public java.math.BigDecimal getPriceList ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Standardpreis.
@param PriceStd
Standardpreis
*/
@Override
public void setPriceStd (java.math.BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
|
/** Get Standardpreis.
@return Standardpreis
*/
@Override
public java.math.BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_ProductScalePrice.java
| 1
|
请完成以下Java代码
|
public String getCalledCaseInstanceId() {
return calledCaseInstanceId;
}
public void setCalledCaseInstanceId(String calledCaseInstanceId) {
this.calledCaseInstanceId = calledCaseInstanceId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskAssignee() {
return taskAssignee;
}
public void setTaskAssignee(String taskAssignee) {
this.taskAssignee = taskAssignee;
}
public void setActivityInstanceState(int activityInstanceState) {
this.activityInstanceState = activityInstanceState;
}
public int getActivityInstanceState() {
return activityInstanceState;
}
public boolean isCompleteScope() {
return ActivityInstanceState.SCOPE_COMPLETE.getStateCode() == activityInstanceState;
}
public boolean isCanceled() {
return ActivityInstanceState.CANCELED.getStateCode() == activityInstanceState;
}
public String getTenantId() {
return tenantId;
}
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[activityId=" + activityId
+ ", activityName=" + activityName
+ ", activityType=" + activityType
+ ", activityInstanceId=" + activityInstanceId
+ ", activityInstanceState=" + activityInstanceState
+ ", parentActivityInstanceId=" + parentActivityInstanceId
+ ", calledProcessInstanceId=" + calledProcessInstanceId
+ ", calledCaseInstanceId=" + calledCaseInstanceId
+ ", taskId=" + taskId
+ ", taskAssignee=" + taskAssignee
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime
+ ", endTime=" + endTime
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricActivityInstanceEventEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart, isHtml, to, subject, content);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.warn("Email could not be sent to user '{}'", to, e);
} else {
log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
}
}
}
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
Locale locale = Locale.forLanguageTag(user.getLangKey());
Context context = new Context(locale);
context.setVariable(USER, user);
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
String content = templateEngine.process(templateName, context);
String subject = messageSource.getMessage(titleKey, null, locale);
sendEmail(user.getEmail(), subject, content, false, true);
|
}
@Async
public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title");
}
@Async
public void sendCreationEmail(User user) {
log.debug("Sending creation email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title");
}
@Async
public void sendPasswordResetMail(User user) {
log.debug("Sending password reset email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title");
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\MailService.java
| 2
|
请完成以下Java代码
|
public final class VectorsReader
{
public final Charset ENCODING = Charset.forName("UTF-8");
int words, size;
String[] vocab;
float[][] matrix;
final String file;
public VectorsReader(String file)
{
this.file = file;
}
public void readVectorFile() throws IOException
{
Predefine.logger.info(String.format("reading %s file. please wait...\n", file));
InputStream is = null;
Reader r = null;
BufferedReader br = null;
try
{
is = IOUtil.newInputStream(file);
r = new InputStreamReader(is, ENCODING);
br = new BufferedReader(r);
String line = br.readLine();
words = Integer.parseInt(line.split("\\s+")[0].trim());
size = Integer.parseInt(line.split("\\s+")[1].trim());
vocab = new String[words];
matrix = new float[words][];
for (int i = 0; i < words; i++)
{
line = br.readLine().trim();
String[] params = line.split("\\s+");
if (params.length != size + 1)
{
Predefine.logger.info("词向量有一行格式不规范(可能是单词含有空格):" + line);
--words;
--i;
continue;
}
vocab[i] = params[0];
matrix[i] = new float[size];
double len = 0;
for (int j = 0; j < size; j++)
{
matrix[i][j] = Float.parseFloat(params[j + 1]);
len += matrix[i][j] * matrix[i][j];
}
len = Math.sqrt(len);
for (int j = 0; j < size; j++)
{
matrix[i][j] /= len;
}
}
|
if (words != vocab.length)
{
vocab = Utility.shrink(vocab, new String[words]);
matrix = Utility.shrink(matrix, new float[words][]);
}
}
finally
{
Utility.closeQuietly(br);
Utility.closeQuietly(r);
Utility.closeQuietly(is);
}
}
public int getSize()
{
return size;
}
public int getNumWords()
{
return words;
}
public String getWord(int idx)
{
return vocab[idx];
}
public float getMatrixElement(int row, int column)
{
return matrix[row][column];
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\VectorsReader.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void saveBPartnerBankAccounts(@NonNull final BPartnerComposite bpartnerComposite, final boolean validatePermissions)
{
final ArrayList<BPartnerBankAccountId> savedBPBankAccountIds = new ArrayList<>();
final List<BPartnerBankAccount> bankAccounts = bpartnerComposite.getBankAccounts();
final BPartnerId bpartnerId = bpartnerComposite.getBpartner().getId();
final OrgId orgId = bpartnerComposite.getOrgId();
for (final BPartnerBankAccount bankAccount : bankAccounts)
{
final BPartnerBankAccountsSaveRequest request = BPartnerBankAccountsSaveRequest.builder()
.bpartnerId(bpartnerId)
.orgId(orgId)
.bankAccount(bankAccount)
.validatePermissions(validatePermissions)
.build();
saveBPartnerBankAccount(request);
savedBPBankAccountIds.add(bankAccount.getId());
}
bpBankAccountsDAO.deactivateIBANAccountsByBPartnerExcept(bpartnerId, savedBPBankAccountIds);
}
private void saveBPartnerBankAccount(@NonNull final BPartnerBankAccountsSaveRequest request)
{
final BPartnerBankAccount bankAccount = request.getBankAccount();
final OrgId orgId = request.getOrgId();
final BPartnerId bpartnerId = request.getBpartnerId();
final boolean validatePermissions = request.isValidatePermissions();
try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(I_C_BP_BankAccount.Table_Name, bankAccount.getId()))
{
final I_C_BP_BankAccount record = loadOrNew(bankAccount.getId(), I_C_BP_BankAccount.class);
if (orgId != null)
{
record.setAD_Org_ID(orgId.getRepoId());
}
record.setC_BPartner_ID(bpartnerId.getRepoId());
|
record.setIBAN(bankAccount.getIban());
record.setC_Currency_ID(bankAccount.getCurrencyId().getRepoId());
record.setIsActive(bankAccount.isActive());
record.setAD_Org_Mapping_ID(OrgMappingId.toRepoId(bankAccount.getOrgMappingId()));
record.setA_Name(bankAccount.getAccountName());
record.setA_Street(bankAccount.getAccountStreet());
record.setA_Zip(bankAccount.getAccountZip());
record.setA_City(bankAccount.getAccountCity());
record.setA_Country(bankAccount.getAccountCountry());
if (validatePermissions)
{
assertCanCreateOrUpdate(record);
}
saveRecord(record);
final BPartnerBankAccountId id = BPartnerBankAccountId.ofRepoId(bpartnerId, record.getC_BP_BankAccount_ID());
bankAccount.setId(id);
}
}
private void assertCanCreateOrUpdate(@NonNull final Object record)
{
if (Adempiere.isUnitTestMode())
{
return;
}
PermissionServiceFactories
.currentContext()
.createPermissionService()
.assertCanCreateOrUpdate(record);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\repository\BPartnerCompositeSaver.java
| 2
|
请完成以下Java代码
|
public static final class Container<K, V> {
private final ProcessorContext<K, V> context;
private final K key;
private final V value;
private final Record<K, V> record;
Container(ProcessorContext<K, V> context, K key, V value, Record<K, V> record) {
this.context = context;
this.key = key;
this.value = value;
this.record = record;
}
public ProcessorContext<K, V> getContext() {
return this.context;
}
|
public K getKey() {
return this.key;
}
public V getValue() {
return this.value;
}
public Record<K, V> getRecord() {
return this.record;
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\streams\HeaderEnricherProcessor.java
| 1
|
请完成以下Java代码
|
public TransactionIdentifier1 getTxId() {
return txId;
}
/**
* Sets the value of the txId property.
*
* @param value
* allowed object is
* {@link TransactionIdentifier1 }
*
*/
public void setTxId(TransactionIdentifier1 value) {
this.txId = value;
}
/**
* Gets the value of the pdct property.
*
* @return
* possible object is
* {@link Product2 }
*
*/
public Product2 getPdct() {
return pdct;
}
/**
* Sets the value of the pdct property.
*
* @param value
* allowed object is
* {@link Product2 }
*
*/
public void setPdct(Product2 value) {
this.pdct = value;
}
/**
* Gets the value of the vldtnDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
|
*/
public XMLGregorianCalendar getVldtnDt() {
return vldtnDt;
}
/**
* Sets the value of the vldtnDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setVldtnDt(XMLGregorianCalendar value) {
this.vldtnDt = value;
}
/**
* Gets the value of the vldtnSeqNb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVldtnSeqNb() {
return vldtnSeqNb;
}
/**
* Sets the value of the vldtnSeqNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVldtnSeqNb(String value) {
this.vldtnSeqNb = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardIndividualTransaction1.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
// The methods below are not relevant, as getValue() is used directly to return the value set during the transaction
@Override
public String getTextValue() {
return null;
}
@Override
public void setTextValue(String textValue) {
}
@Override
public String getTextValue2() {
return null;
}
@Override
public void setTextValue2(String textValue2) {
}
@Override
public Long getLongValue() {
return null;
}
@Override
public void setLongValue(Long longValue) {
}
@Override
public Double getDoubleValue() {
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
|
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public void setBytes(byte[] bytes) {
}
@Override
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java
| 2
|
请完成以下Java代码
|
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return completed;
}
|
public void setCompleted(boolean completed) {
this.completed = completed;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Todo todo = (Todo) o;
return userId == todo.userId && id == todo.id && completed == todo.completed && Objects.equals(title, todo.title);
}
@Override
public int hashCode() {
return Objects.hash(userId, id, title, completed);
}
@Override
public String toString() {
return "{" + "userId=" + userId + ", id=" + id + ", title='" + title + '\'' + ", completed=" + completed + '}';
}
}
|
repos\tutorials-master\core-java-modules\core-java-11-3\src\main\java\com\baeldung\httppojo\Todo.java
| 1
|
请完成以下Java代码
|
public boolean isIncludeInput() {
return includeInput;
}
public boolean isIncludeOutputs() {
return includeOutputs;
}
@Override
public HistoricDecisionInstanceQuery disableBinaryFetching() {
isByteArrayFetchingEnabled = false;
return this;
}
@Override
public HistoricDecisionInstanceQuery disableCustomObjectDeserialization() {
isCustomObjectDeserializationEnabled = false;
return this;
}
public boolean isByteArrayFetchingEnabled() {
return isByteArrayFetchingEnabled;
}
public boolean isCustomObjectDeserializationEnabled() {
return isCustomObjectDeserializationEnabled;
}
public String getRootDecisionInstanceId() {
return rootDecisionInstanceId;
}
public HistoricDecisionInstanceQuery rootDecisionInstanceId(String rootDecisionInstanceId) {
ensureNotNull(NotValidException.class, "rootDecisionInstanceId", rootDecisionInstanceId);
this.rootDecisionInstanceId = rootDecisionInstanceId;
return this;
}
public boolean isRootDecisionInstancesOnly() {
return rootDecisionInstancesOnly;
}
public HistoricDecisionInstanceQuery rootDecisionInstancesOnly() {
this.rootDecisionInstancesOnly = true;
return this;
}
@Override
public HistoricDecisionInstanceQuery decisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) {
ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionId", decisionRequirementsDefinitionId);
this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId;
|
return this;
}
@Override
public HistoricDecisionInstanceQuery decisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) {
ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionKey", decisionRequirementsDefinitionKey);
this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey;
return this;
}
public String getDecisionRequirementsDefinitionId() {
return decisionRequirementsDefinitionId;
}
public String getDecisionRequirementsDefinitionKey() {
return decisionRequirementsDefinitionKey;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDecisionInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public Action getCopyPasteAction(final CopyPasteActionType actionType)
{
final String swingActionMapName = actionType.getSwingActionMapName();
return getTextComponent().getActionMap().get(swingActionMapName);
}
@Override
public void putCopyPasteAction(final CopyPasteActionType actionType, final Action action, final KeyStroke keyStroke)
{
final JTextComponent textComponent = getTextComponent();
final String swingActionMapName = actionType.getSwingActionMapName();
textComponent.getActionMap().put(swingActionMapName, action);
if (keyStroke != null)
{
textComponent.getInputMap().put(keyStroke, action.getValue(Action.NAME));
}
}
@Override
public boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType)
{
if (actionType == CopyPasteActionType.Copy)
{
return hasTextToCopy();
}
else if (actionType == CopyPasteActionType.Cut)
{
return isEditable() && hasTextToCopy();
}
else if (actionType == CopyPasteActionType.Paste)
{
return isEditable();
}
else if (actionType == CopyPasteActionType.SelectAll)
{
return !isEmpty();
}
else
{
return false;
}
}
|
private final boolean isEditable()
{
final JTextComponent textComponent = getTextComponent();
return textComponent.isEditable() && textComponent.isEnabled();
}
private final boolean hasTextToCopy()
{
final JTextComponent textComponent = getTextComponent();
final String selectedText = textComponent.getSelectedText();
return selectedText != null && !selectedText.isEmpty();
}
private final boolean isEmpty()
{
final JTextComponent textComponent = getTextComponent();
final String text = textComponent.getText();
return Check.isEmpty(text, false);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\JTextComponentCopyPasteSupportEditor.java
| 1
|
请完成以下Java代码
|
public String getFieldValue(String field) {
return getFieldValue(field, false);
}
public String getFieldValue(String field, boolean ignoreNullStrings) {
String[] fieldsTree = field.split("\\.");
JsonNode current = fieldsData;
for (String key : fieldsTree) {
if (current.has(key)) {
current = current.get(key);
} else {
current = null;
break;
}
}
if (current == null) {
return null;
}
if (current.isNull() && ignoreNullStrings) {
return null;
}
if (current.isValueNode()) {
String textValue = current.asText();
if (StringUtils.isEmpty(textValue) && ignoreNullStrings) {
return null;
}
return textValue;
|
}
try {
return mapper.writeValueAsString(current);
} catch (JsonProcessingException e) {
return null;
}
}
private static class EntityIdFieldSerializer extends JsonSerializer<EntityId> {
@Override
public void serialize(EntityId value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeObject(value.getId());
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\EntityFieldsData.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TokenService {
@Autowired
Cache<String, SessionUserInfo> cacheMap;
@Autowired
LoginDao loginDao;
/**
* 用户登录验证通过后(sso/帐密),生成token,记录用户已登录的状态
*/
public String generateToken(String username) {
MDC.put("username", username);
String token = UUID.randomUUID().toString().replace("-", "").substring(0, 20);
//设置用户信息缓存
setCache(token, username);
return token;
}
public SessionUserInfo getUserInfo() {
String token = MDC.get("token");
return getUserInfoFromCache(token);
}
/**
* 根据token查询用户信息
* 如果token无效,会抛未登录的异常
*/
private SessionUserInfo getUserInfoFromCache(String token) {
if (StringTools.isNullOrEmpty(token)) {
throw new CommonJsonException(ErrorEnum.E_20011);
}
log.debug("根据token从缓存中查询用户信息,{}", token);
SessionUserInfo info = cacheMap.getIfPresent(token);
if (info == null) {
log.info("没拿到缓存 token={}", token);
throw new CommonJsonException(ErrorEnum.E_20011);
}
return info;
}
private void setCache(String token, String username) {
SessionUserInfo info = getUserInfoByUsername(username);
log.info("设置用户信息缓存:token={} , username={}, info={}", token, username, info);
cacheMap.put(token, info);
|
}
/**
* 退出登录时,将token置为无效
*/
public void invalidateToken() {
String token = MDC.get("token");
if (!StringTools.isNullOrEmpty(token)) {
cacheMap.invalidate(token);
}
log.debug("退出登录,清除缓存:token={}", token);
}
private SessionUserInfo getUserInfoByUsername(String username) {
SessionUserInfo userInfo = loginDao.getUserInfo(username);
if (userInfo.getRoleIds().contains(1)) {
//管理员,查出全部按钮和权限码
userInfo.setMenuList(loginDao.getAllMenu());
userInfo.setPermissionList(loginDao.getAllPermissionCode());
}
return userInfo;
}
}
|
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\TokenService.java
| 2
|
请完成以下Java代码
|
private ProductId lookupProductIdOrNull(
@NonNull final JsonProductInfo json,
@NonNull final OrgId orgId)
{
final String productValue = json.getCode();
final String productExternalId = json.getExternalId();
final SyncAdvise syncAdvise = json.getSyncAdvise();
final ProductId existingProductId;
if (Check.isEmpty(productValue, true) && productExternalId == null)
{
existingProductId = null;
}
else
{
final ProductQuery query = ProductQuery.builder()
.value(productValue)
.externalId(ExternalId.ofOrNull(productExternalId))
.orgId(orgId)
.includeAnyOrg(true)
.outOfTrx(syncAdvise.isLoadReadOnly())
.build();
existingProductId = productDAO.retrieveProductIdBy(query);
}
if (existingProductId == null && syncAdvise.getIfNotExists().isFail())
{
final String msg = StringUtils.formatMessage("Found no existing product with orgId in ({}, 0); Search parameters - used if not null or empty: value={}; externalId={}",
OrgId.toRepoIdOrAny(orgId), productValue, productExternalId);
|
throw new ProductNotFoundException(msg);
}
return existingProductId;
}
private UomId getProductUOMId(
@Nullable final ProductId productId,
@Nullable final X12DE355 uomCode)
{
if (uomCode != null)
{
return uomDAO.getUomIdByX12DE355(uomCode);
}
else
{
return productsBL.getStockUOMId(productId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\ProductMasterDataProvider.java
| 1
|
请完成以下Java代码
|
public GatewayFilter apply(Config config) {
// AbstractChangeRequestUriGatewayFilterFactory.apply() returns
// OrderedGatewayFilter
OrderedGatewayFilter gatewayFilter = (OrderedGatewayFilter) super.apply(config);
return new OrderedGatewayFilter(gatewayFilter, gatewayFilter.getOrder()) {
@Override
public String toString() {
String template = Objects.requireNonNull(config.getTemplate(), "template must not be null");
return filterToStringCreator(SetRequestUriGatewayFilterFactory.this).append("template", template)
.toString();
}
};
}
String getUri(ServerWebExchange exchange, Config config) {
String template = Objects.requireNonNull(config.getTemplate(), "template must not be null");
if (template.indexOf('{') == -1) {
return template;
}
Map<String, String> variables = getUriTemplateVariables(exchange);
return UriComponentsBuilder.fromUriString(template).build().expand(variables).toUriString();
}
@Override
protected Optional<URI> determineRequestUri(ServerWebExchange exchange, Config config) {
try {
String url = getUri(exchange, config);
URI uri = URI.create(url);
if (!uri.isAbsolute()) {
log.info("Request url is invalid: url={}, error=URI is not absolute", url);
return Optional.ofNullable(null);
}
|
return Optional.of(uri);
}
catch (IllegalArgumentException e) {
log.info("Request url is invalid : url={}, error={}", config.getTemplate(), e.getMessage());
return Optional.ofNullable(null);
}
}
public static class Config {
private @Nullable String template;
public @Nullable String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetRequestUriGatewayFilterFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static Map<String, String> buildRequestPara(Map<String, String> sParaTemp) {
// 除去数组中的空值和签名参数
Map<String, String> sPara = AlipayCore.paraFilter(sParaTemp);
// 生成签名结果
String mysign = buildRequestMysign(sPara);
// 签名结果与签名方式加入请求提交参数组中
sPara.put("sign", mysign);
sPara.put("sign_type", SIGN_TYPE);
return sPara;
}
/**
* 建立请求,以表单HTML形式构造(默认)
*
* @param sParaTemp
* 请求参数数组
* @param strMethod
* 提交方式。两个值可选:post、get
* @param strButtonName
* 确认按钮显示文字
* @return 提交表单HTML文本
*/
public static String buildRequest(Map<String, String> sParaTemp, String strMethod, String strButtonName) {
// 待请求参数数组
Map<String, String> sPara = buildRequestPara(sParaTemp);
List<String> keys = new ArrayList<String>(sPara.keySet());
StringBuffer sbHtml = new StringBuffer();
sbHtml.append("<form id=\"alipaysubmit\" name=\"alipaysubmit\" action=\"" + ALIPAY_GATEWAY_NEW + "_input_charset=" + INPUT_CHARSET + "\" method=\"" + strMethod + "\">");
for (int i = 0; i < keys.size(); i++) {
String name = (String) keys.get(i);
String value = (String) sPara.get(name);
sbHtml.append("<input type=\"hidden\" name=\"" + name + "\" value=\"" + value + "\"/>");
}
// submit按钮控件请不要含有name属性
sbHtml.append("<input type=\"submit\" value=\"" + strButtonName + "\" style=\"display:none;\"></form>");
sbHtml.append("<script>document.forms['alipaysubmit'].submit();</script>");
return sbHtml.toString();
}
/**
* MAP类型数组转换成NameValuePair类型
|
*
* @param properties
* MAP类型数组
* @return NameValuePair类型数组
*/
public static NameValuePair[] generatNameValuePair(Map<String, String> properties) {
NameValuePair[] nameValuePair = new NameValuePair[properties.size()];
int i = 0;
for (Map.Entry<String, String> entry : properties.entrySet()) {
nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue());
}
return nameValuePair;
}
/**
* 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 注意:远程解析XML出错,与服务器是否支持SSL等配置有关
*
* @return 时间戳字符串
* @throws IOException
* @throws DocumentException
* @throws MalformedURLException
*/
public static String query_timestamp() throws MalformedURLException, DocumentException, IOException {
// 构造访问query_timestamp接口的URL串
String strUrl = ALIPAY_GATEWAY_NEW + "service=query_timestamp&partner=" + PARTNER + "&_input_charset" + INPUT_CHARSET;
StringBuffer result = new StringBuffer();
SAXReader reader = new SAXReader();
Document doc = reader.read(new URL(strUrl).openStream());
List<Node> nodeList = doc.selectNodes("//alipay/*");
for (Node node : nodeList) {
// 截取部分不需要解析的信息
if (node.getName().equals("is_success") && node.getText().equals("T")) {
// 判断是否有成功标示
List<Node> nodeList1 = doc.selectNodes("//response/timestamp/*");
for (Node node1 : nodeList1) {
result.append(node1.getText());
}
}
}
return result.toString();
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\AlipaySubmit.java
| 2
|
请完成以下Java代码
|
public class HUOrderFastInputHandler implements IOrderFastInputHandler
{
@Override
public void clearFields(final GridTab gridTab)
{
final I_C_Order order = InterfaceWrapperHelper.create(gridTab, I_C_Order.class);
order.setM_HU_PI_Item_Product_ID(-1);
order.setQty_FastInput_TU(null);
// these changes will be propagated to the GUI component
gridTab.setValue(I_C_Order.COLUMNNAME_M_HU_PI_Item_Product_ID, null);
gridTab.setValue(I_C_Order.COLUMNNAME_Qty_FastInput_TU, null);
}
@Override
public boolean requestFocus(final GridTab gridTab)
{
final I_C_Order order = InterfaceWrapperHelper.create(gridTab, I_C_Order.class);
final Integer productId = order.getM_Product_ID();
if (productId <= 0
&& gridTab.getField(de.metas.adempiere.model.I_C_Order.COLUMNNAME_M_Product_ID).isDisplayed())
{
gridTab.getField(de.metas.adempiere.model.I_C_Order.COLUMNNAME_M_Product_ID).requestFocus();
return true;
}
// task 06300: focus shall go from product to TU-qty (not CU-qty)
final BigDecimal qtyTU = order.getQty_FastInput_TU();
final BigDecimal qtyCU = order.getQty_FastInput();
final boolean hasTUs = Services.get(IHUOrderBL.class).hasTUs(order);
if (!hasTUs || null != qtyCU && qtyCU.signum() > 0)
{
// the product is not assigned to a TU, so we return false and leave it to the default handler which will probably request the focus for the "CU Qty" field
// 06730: Also, we leave it for the default handler if we have a TU quantity with no HU.
|
return false;
}
if ((qtyTU == null || qtyTU.signum() <= 0)
&& gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput_TU).isDisplayed())
{
// product has been set, but qty hasn't
gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput_TU).requestFocus();
return true;
}
final int huPIPId = order.getM_HU_PI_Item_Product_ID();
if (huPIPId <= 0
&& gridTab.getField(I_C_Order.COLUMNNAME_M_HU_PI_Item_Product_ID).isDisplayed())
{
gridTab.getField(I_C_Order.COLUMNNAME_M_HU_PI_Item_Product_ID).requestFocus();
return true;
}
// no focus was requested
return false;
}
@Override
public IGridTabRowBuilder createLineBuilderFromHeader(final Object model)
{
return new OrderLineHUPackingGridRowBuilder();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUOrderFastInputHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<FlowRule> convert(String value) {
try {
return Arrays.asList(objectMapper.readValue(value, FlowRule[].class));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
});
// 注册到 FlowRuleManager 中
FlowRuleManager.register2Property(refreshableDataSource.getProperty());
return refreshableDataSource;
}
@Bean
public FileWritableDataSource writableDataSource(ObjectMapper objectMapper) throws IOException {
// File 配置。这里先写死,推荐后面写到 application.yaml 配置文件中。
String directory = System.getProperty("user.home") + File.separator
+ "sentinel" + File.separator
+ System.getProperty("project.name");
mkdirs(directory);
String path = directory + File.separator + "flow-rule.json";
creteFile(path);
// 创建 FileRefreshableDataSource 对象
FileRefreshableDataSource<List<FlowRule>> refreshableDataSource = new FileRefreshableDataSource<>(path,
new Converter<String, List<FlowRule>>() { // 转换器,将读取的文本配置,转换成 FlowRule 数组
@Override
public List<FlowRule> convert(String value) {
try {
return Arrays.asList(objectMapper.readValue(value, FlowRule[].class));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
});
// 注册到 FlowRuleManager 中
FlowRuleManager.register2Property(refreshableDataSource.getProperty());
|
// 创建 FileWritableDataSource 对象
FileWritableDataSource<List<FlowRule>> fileWritableDataSource = new FileWritableDataSource<>(path,
new Converter<List<FlowRule>, String>() {
@Override
public String convert(List<FlowRule> source) {
try {
return objectMapper.writeValueAsString(source);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
});
// 注册到 WritableDataSourceRegistry 中
WritableDataSourceRegistry.registerFlowDataSource(fileWritableDataSource);
return fileWritableDataSource;
}
private void mkdirs(String path) {
File file = new File(path);
if (file.exists()) {
return;
}
file.mkdirs();
}
private void creteFile(String path) throws IOException {
File file = new File(path);
if (file.exists()) {
return;
}
file.createNewFile();
}
}
|
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo-file\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\config\SentinelConfiguration.java
| 2
|
请完成以下Java代码
|
public int getC_BPartner_ID()
{
return BPartnerId.toRepoId(getBPartnerEffectiveId(delegate));
}
@Override
public void setC_BPartner_ID(final int C_BPartner_ID)
{
}
@Override
public int getC_BPartner_Location_ID()
{
return getC_BPartner_Location_Effective_ID(delegate);
}
@Override
@Deprecated
public void setC_BPartner_Location_ID(final int C_BPartner_Location_ID)
{
}
@Override
public int getC_BPartner_Location_Value_ID()
{
return -1;
}
@Override
public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID)
{
}
@Override
public int getAD_User_ID()
{
return BPartnerContactId.toRepoId(getBPartnerContactID(delegate));
}
@Override
public void setAD_User_ID(final int AD_User_ID)
{
}
@Override
public String getBPartnerAddress()
|
{
return delegate.getBPartnerAddress_Override();
}
@Override
public void setBPartnerAddress(final String address)
{
delegate.setBPartnerAddress_Override(address);
}
}
@Override
public int updateDatePromisedOverrideAndPOReference(@NonNull final PInstanceId pinstanceId, @Nullable final LocalDate datePromisedOverride, @Nullable final String poReference)
{
if (datePromisedOverride == null && Check.isBlank(poReference))
{
throw new AdempiereException(MSG_DATEPROMISEDOVERRIDE_POREFERENCE_VALIDATION_ERROR)
.markAsUserValidationError();
}
final ICompositeQueryUpdater<I_M_ReceiptSchedule> updater = queryBL
.createCompositeQueryUpdater(I_M_ReceiptSchedule.class);
if (datePromisedOverride != null)
{
updater.addSetColumnValue(I_M_ReceiptSchedule.COLUMNNAME_DatePromised_Override, datePromisedOverride);
}
if (!Check.isBlank(poReference))
{
updater.addSetColumnValue(I_M_ReceiptSchedule.COLUMNNAME_POReference, poReference);
}
return queryBL.createQueryBuilder(I_M_ReceiptSchedule.class)
.setOnlySelection(pinstanceId)
.create()
.update(updater);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleBL.java
| 1
|
请完成以下Java代码
|
public class AcceptedType
extends StatusType
{
protected String explanation;
protected ReimbursementType reimbursement;
/**
* Gets the value of the explanation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExplanation() {
return explanation;
}
/**
* Sets the value of the explanation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExplanation(String value) {
this.explanation = value;
}
/**
* Gets the value of the reimbursement property.
*
* @return
* possible object is
* {@link ReimbursementType }
|
*
*/
public ReimbursementType getReimbursement() {
return reimbursement;
}
/**
* Sets the value of the reimbursement property.
*
* @param value
* allowed object is
* {@link ReimbursementType }
*
*/
public void setReimbursement(ReimbursementType value) {
this.reimbursement = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\AcceptedType.java
| 1
|
请完成以下Java代码
|
public int getQtyShipped_CatchWeight_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_QtyShipped_CatchWeight_UOM_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
|
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setReplicationTrxErrorMsg (final @Nullable java.lang.String ReplicationTrxErrorMsg)
{
throw new IllegalArgumentException ("ReplicationTrxErrorMsg is virtual column"); }
@Override
public java.lang.String getReplicationTrxErrorMsg()
{
return get_ValueAsString(COLUMNNAME_ReplicationTrxErrorMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCand.java
| 1
|
请完成以下Java代码
|
public Money toMoney(@NonNull final Amount amount)
{
final CurrencyId currencyId = currencyRepository.getCurrencyIdByCurrencyCode(amount.getCurrencyCode());
return Money.of(amount.getAsBigDecimal(), currencyId);
}
public Money multiply(
@NonNull final Quantity qty,
@NonNull final ProductPrice price)
{
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final Quantity qtyInPriceUnit = uomConversionBL.convertQuantityTo(
qty,
UOMConversionContext.of(price.getProductId()), price.getUomId());
return multiply(qtyInPriceUnit, price.toMoney());
}
|
public Money multiply(@NonNull final Quantity qty, @NonNull final Money money)
{
final CurrencyPrecision currencyPrecision = currencyRepository
.getById(money.getCurrencyId())
.getPrecision();
final BigDecimal moneyAmount = money.toBigDecimal();
final BigDecimal netAmt = qty.toBigDecimal().multiply(moneyAmount);
return Money.of(
currencyPrecision.round(netAmt),
money.getCurrencyId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\money\MoneyService.java
| 1
|
请完成以下Java代码
|
public DueDateAndStatus computeDueDate(@NonNull final PaymentTermBreak termBreak)
{
final LocalDate referenceDate = getAvailableReferenceDate(termBreak.getReferenceDateType());
if (referenceDate != null)
{
final LocalDate dueDate = referenceDate.plusDays(termBreak.getOffsetDays());
return DueDateAndStatus.awaitingPayment(dueDate);
}
else
{
return DueDateAndStatus.pending();
}
}
@Nullable
private LocalDate getAvailableReferenceDate(@NonNull final ReferenceDateType referenceDateType)
{
switch (referenceDateType)
{
|
case OrderDate:
return getOrderDate();
case LetterOfCreditDate:
return getLetterOfCreditDate();
case BillOfLadingDate:
return getBillOfLadingDate();
case ETADate:
return getETADate();
case InvoiceDate:
return getInvoiceDate();
default:
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\OrderSchedulingContext.java
| 1
|
请完成以下Java代码
|
public void add(T element) {
if (element == null) {
throw new NullPointerException();
}
Node<T> node = new Node<>(element);
Node<T> currentTail;
do {
currentTail = tail.get();
node.setPrevious(currentTail);
} while(!tail.compareAndSet(currentTail, node));
if(node.previous != null) {
node.previous.next = node;
}
head.compareAndSet(null, node); //if we are inserting the first element
size.incrementAndGet();
}
public T get() {
if(head.get() == null) {
throw new NoSuchElementException();
}
Node<T> currentHead;
Node<T> nextNode;
do {
currentHead = head.get();
nextNode = currentHead.getNext();
} while(!head.compareAndSet(currentHead, nextNode));
|
size.decrementAndGet();
return currentHead.getValue();
}
public int size() {
return this.size.get();
}
private class Node<T> {
private final T value;
private volatile Node<T> next;
private volatile Node<T> previous;
public Node(T value) {
this.value = value;
this.next = null;
}
public T getValue() {
return value;
}
public Node<T> getNext() {
return next;
}
public void setPrevious(Node<T> previous) {
this.previous = previous;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\lockfree\NonBlockingQueue.java
| 1
|
请完成以下Java代码
|
public class RedisKeyConstant {
/**
* redis key : 每日一题
*/
public static final String DAILY_QUESTION_KEY = "question_daily:question";
/**
* redis key : 用户每日一题做题情况
*/
public static final String USER_DAILY_QUESTION_KEY = "question_daily:user:%s";
/**
* redis key : 点赞父评论
*/
public static final String ROOT_COMMENT_LIKE_KEY = "like:root_comment";
/**
* redis key : 点赞子评论
*/
public static final String SON_COMMENT_LIKE_KEY = "like:son_comment";
/**
* redis key : 点赞题解
*/
public static final String NOTE_LIKE_KEY = "like:note";
/**
* redis key : 点赞问题
*/
public static final String QUESTION_LIKE_KEY = "like:question";
|
/**
* redis key : 自测代码限流
*/
public static final String TEST_RUN_CODE_KEY = "runcode:test:%s";
/**
* redis key : 提交代码限流
*/
public static final String COMMIT_RUN_CODE_KEY = "runcode:commit:%s";
/**
* redis key : 消息模板
*/
public static final String MESSAGE_TEMPLATE_KEY = "template_key:message";
/**
* redis key : 短信模板
*/
public static final String SMS_TEMPLATE_KEY = "template_key:sms";
/**
* redis key : 邮件模板
*/
public static final String EMAIL_TEMPLATE_KEY = "template_key:email";
}
|
repos\spring-boot-quick-master\quick-sse\src\main\java\com\quick\constant\RedisKeyConstant.java
| 1
|
请完成以下Java代码
|
public Status getAggregateStatus(Set<Status> statuses) {
return statuses.stream().filter(this::contains).min(this.comparator).orElse(Status.UNKNOWN);
}
private boolean contains(Status status) {
return this.order.contains(getUniformCode(status.getCode()));
}
private static List<String> getUniformCodes(Stream<String> codes) {
return codes.map(SimpleStatusAggregator::getUniformCode).toList();
}
@Contract("!null -> !null")
private static @Nullable String getUniformCode(@Nullable String code) {
if (code == null) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) || Character.isDigit(ch)) {
builder.append(Character.toLowerCase(ch));
}
}
|
return builder.toString();
}
/**
* {@link Comparator} used to order {@link Status}.
*/
private final class StatusComparator implements Comparator<Status> {
@Override
public int compare(Status s1, Status s2) {
List<String> order = SimpleStatusAggregator.this.order;
int i1 = order.indexOf(getUniformCode(s1.getCode()));
int i2 = order.indexOf(getUniformCode(s2.getCode()));
return (i1 < i2) ? -1 : (i1 != i2) ? 1 : s1.getCode().compareTo(s2.getCode());
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\SimpleStatusAggregator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PmsRolePermission getDataById(Long id) {
return pmsRolePermissionDao.getById(id);
}
/**
* 分页查询pmsOperator
*
* @param pageParam
* @param ActivityVo
* PmsOperator
* @return
*/
public PageBean listPage(PageParam pageParam, PmsRolePermission pmsRolePermission) {
Map<String, Object> paramMap = new HashMap<String, Object>();
return pmsRolePermissionDao.listPage(pageParam, paramMap);
}
/**
* 保存角色和权限之间的关联关系
*/
@Transactional(rollbackFor = Exception.class)
public void saveRolePermission(Long roleId, String rolePermissionStr){
// 删除原来的角色与权限关联
|
pmsRolePermissionDao.deleteByRoleId(roleId);
if (!StringUtils.isEmpty(rolePermissionStr)) {
// 创建新的关联
String[] permissionIds = rolePermissionStr.split(",");
for (int i = 0; i < permissionIds.length; i++) {
Long permissionId = Long.valueOf(permissionIds[i]);
PmsRolePermission item = new PmsRolePermission();
item.setPermissionId(permissionId);
item.setRoleId(roleId);
pmsRolePermissionDao.insert(item);
}
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsRolePermissionServiceImpl.java
| 2
|
请完成以下Java代码
|
public void setMSV3_Menge (int MSV3_Menge)
{
set_Value (COLUMNNAME_MSV3_Menge, Integer.valueOf(MSV3_Menge));
}
/** Get MSV3_Menge.
@return MSV3_Menge */
@Override
public int getMSV3_Menge ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Menge);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set MSV3_Pzn.
@param MSV3_Pzn MSV3_Pzn */
@Override
public void setMSV3_Pzn (java.lang.String MSV3_Pzn)
{
set_Value (COLUMNNAME_MSV3_Pzn, MSV3_Pzn);
}
/** Get MSV3_Pzn.
@return MSV3_Pzn */
@Override
public java.lang.String getMSV3_Pzn ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_Pzn);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungPosition.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PointEntity {
@Id
@GeneratedValue
private Long id;
@Column(columnDefinition="BINARY(2048)")
private Point point;
public PointEntity() {
}
public Long getId() {
return id;
}
|
public void setId(Long id) {
this.id = id;
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
@Override
public String toString() {
return "PointEntity{" + "id=" + id + ", point=" + point + '}';
}
}
|
repos\tutorials-master\persistence-modules\hibernate-enterprise\src\main\java\com\baeldung\hibernate\pojo\PointEntity.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private static TbMsg unbindMsg(JsonNode msgData, TbMsg msg) {
String data = null;
Map<String, String> metadata = null;
String messageType = null;
if (msgData.has(RuleNodeScriptFactory.MSG)) {
JsonNode msgPayload = msgData.get(RuleNodeScriptFactory.MSG);
data = JacksonUtil.toString(msgPayload);
}
if (msgData.has(RuleNodeScriptFactory.METADATA)) {
JsonNode msgMetadata = msgData.get(RuleNodeScriptFactory.METADATA);
metadata = JacksonUtil.convertValue(msgMetadata, new TypeReference<>() {});
}
if (msgData.has(RuleNodeScriptFactory.MSG_TYPE)) {
messageType = msgData.get(RuleNodeScriptFactory.MSG_TYPE).asText();
}
|
String newData = data != null ? data : msg.getData();
TbMsgMetaData newMetadata = metadata != null ? new TbMsgMetaData(metadata) : msg.getMetaData().copy();
String newMessageType = StringUtils.isNotEmpty(messageType) ? messageType : msg.getType();
return msg.transform()
.type(newMessageType)
.metaData(newMetadata)
.data(newData)
.build();
}
private TbScriptException wrongResultType(JsonNode result) {
return new TbScriptException(scriptId, TbScriptException.ErrorCode.RUNTIME, null, new ClassCastException("Wrong result type: " + result.getNodeType()));
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\script\RuleNodeJsScriptEngine.java
| 2
|
请完成以下Java代码
|
public class LinkEventDefinition extends EventDefinition {
private String name;
private String target;
private List<String> sources;
public LinkEventDefinition clone() {
LinkEventDefinition clone = new LinkEventDefinition();
clone.setValues(this);
return clone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
|
public List<String> getSources() {
return sources;
}
public void setSources(List<String> sources) {
this.sources = sources;
}
public void addSource(String source) {
if (sources == null) {
sources = new ArrayList<>();
}
sources.add(source);
}
public void setValues(LinkEventDefinition otherDefinition) {
super.setValues(otherDefinition);
setName(otherDefinition.getName());
setTarget(otherDefinition.getTarget());
setSources(otherDefinition.getSources());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\LinkEventDefinition.java
| 1
|
请完成以下Java代码
|
public List<PropertyChange> getPropertyChanges() {
return propertyChanges;
}
public void setPropertyChanges(List<PropertyChange> propertyChanges) {
this.propertyChanges = propertyChanges;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
|
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MigratingUser {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@JdbcTypeCode(SqlTypes.VARBINARY)
private List<String> tags;
private List<String> newTags;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public List<String> getTags() {
|
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public List<String> getNewTags() {
return newTags;
}
public void setNewTags(List<String> newTags) {
this.newTags = newTags;
}
}
|
repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\arrayscollections\entity\MigratingUser.java
| 2
|
请完成以下Java代码
|
public final class App {
public static App createHardened(int port) {
final XStream xstream = new XStream();
xstream.addPermission(NoTypePermission.NONE);
xstream.addPermission(NullPermission.NULL);
xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
xstream.allowTypes(new Class<?>[] { Person.class });
return new App(port, xstream);
}
public static App createVulnerable(int port) {
return new App(port, new XStream());
}
private final int port;
private final Set<Person> persons;
private final XStream xstream;
private HttpServer server;
private App(int port, XStream xstream) {
this.port = port;
persons = new HashSet<>();
// this app is vulnerable because XStream security is not configured
this.xstream = xstream;
this.xstream.alias("person", Person.class);
}
void start() throws IOException {
server = HttpServer.create(new InetSocketAddress("localhost", port), 0);
server.createContext("/persons", exchange -> {
switch (exchange.getRequestMethod()) {
case "POST":
final Person person = (Person) xstream.fromXML(exchange.getRequestBody());
persons.add(person);
exchange.sendResponseHeaders(201, 0);
exchange.close();
|
break;
case "GET":
exchange.sendResponseHeaders(200, 0);
xstream.toXML(persons, exchange.getResponseBody());
exchange.close();
break;
default:
exchange.sendResponseHeaders(405, 0);
exchange.close();
}
});
server.start();
}
void stop() {
if (server != null) {
server.stop(0);
}
}
int port() {
if (server == null)
throw new IllegalStateException("Server not started");
return server.getAddress()
.getPort();
}
}
|
repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\rce\App.java
| 1
|
请完成以下Java代码
|
private List<JsonCloseInvoiceCandidatesResponseItem> closeInvoiceCandidateRecords(final List<I_C_Invoice_Candidate> invoiceCandidateRecords)
{
final List<JsonCloseInvoiceCandidatesResponseItem> responseItems = new ArrayList<>();
for (final I_C_Invoice_Candidate invoiceCandidateRecord : invoiceCandidateRecords)
{
trxManager.runInNewTrx(() -> responseItems.add(closeInvoiceCandidateRecord(invoiceCandidateRecord)));
}
return responseItems;
}
private JsonCloseInvoiceCandidatesResponseItem closeInvoiceCandidateRecord(final I_C_Invoice_Candidate invoiceCandidateRecord)
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
final JsonCloseInvoiceCandidatesResponseItemBuilder responseItemBuilder = JsonCloseInvoiceCandidatesResponseItem.builder();
responseItemBuilder.externalHeaderId(JsonExternalId.of(invoiceCandidateRecord.getExternalHeaderId()))
.externalLineId(JsonExternalId.of(invoiceCandidateRecord.getExternalLineId()))
.metasfreshId(MetasfreshId.of(invoiceCandidateRecord.getC_Invoice_Candidate_ID()));
|
try
{
invoiceCandBL.closeInvoiceCandidate(invoiceCandidateRecord);
responseItemBuilder.status(JsonCloseInvoiceCandidatesResponseItem.CloseInvoiceCandidateStatus.Closed);
}
catch (final Exception ex)
{
responseItemBuilder.status(JsonCloseInvoiceCandidatesResponseItem.CloseInvoiceCandidateStatus.Error)
.error(JsonErrors.ofThrowable(ex, adLanguage));
}
return responseItemBuilder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\invoicecandidates\impl\CloseInvoiceCandidatesService.java
| 1
|
请完成以下Java代码
|
public static ProductDescriptor forProductAndAttributes(
final int productId,
@NonNull final AttributesKey attributesKey,
final int attributeSetInstanceId)
{
return new ProductDescriptor(productId, attributesKey, attributeSetInstanceId);
}
public static ProductDescriptor forProductAndAttributes(
final int productId,
@NonNull final AttributesKey attributesKey)
{
return new ProductDescriptor(productId, attributesKey, AttributeSetInstanceId.NONE.getRepoId());
}
@Getter
int productId;
@Getter
AttributesKey storageAttributesKey;
/**
* This ID is only here so that the candidate row's attributes can be displayed properly in the UI.
* It may not cause otherwise equal ProductDescriptors to seem as unequal.
*/
@Getter
int attributeSetInstanceId;
@JsonCreator
public ProductDescriptor(
@JsonProperty("productId") final int productId,
@JsonProperty("storageAttributesKey") @NonNull final AttributesKey storageAttributesKey,
@JsonProperty("attributeSetInstanceId") final int attributeSetInstanceId)
{
Preconditions.checkArgument(productId > 0,
"Given parameter productId=%s needs to be >0", productId);
Preconditions.checkArgument(attributeSetInstanceId >= -1,
"Given parameter attributeSetInstanceId needs to >=-1");
|
this.productId = productId;
this.storageAttributesKey = storageAttributesKey;
if (AttributesKey.NONE.equals(storageAttributesKey)
|| AttributesKey.ALL.equals(storageAttributesKey)
|| AttributesKey.OTHER.equals(storageAttributesKey))
{
// discard the given attribueSetInstanceId if it is not about a "real" ASI.
this.attributeSetInstanceId = 0;
}
else
{
this.attributeSetInstanceId = attributeSetInstanceId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\ProductDescriptor.java
| 1
|
请完成以下Java代码
|
private static int skipForward(final boolean[] pagesCovered,
final int pageFrom,
final int limit)
{
final int limitToUse = Math.min(limit, pagesCovered.length);
int pageFromFinal = pageFrom;
for (int i = pageFrom; i <= limitToUse; i++)
{
if (!pagesCovered[i - 1])
{
break;
}
pageFromFinal = i + 1;
}
return pageFromFinal;
}
private static void markCovered(final boolean[] pagesCovered,
final int pageFrom,
final int pageTo)
{
for (int i = pageFrom; i <= pageTo; i++)
{
pagesCovered[i - 1] = true;
}
}
public boolean hasData()
{
return data != null;
}
public int getNumberOfPages()
{
Integer numberOfPages = this._numberOfPages;
if (numberOfPages == null)
{
numberOfPages = this._numberOfPages = computeNumberOfPages();
}
return numberOfPages;
}
private int computeNumberOfPages()
{
if (!hasData())
{
return 0;
}
PdfReader reader = null;
try
{
reader = new PdfReader(getData());
return reader.getNumberOfPages();
}
catch (final IOException e)
|
{
throw new AdempiereException("Cannot get number of pages for C_Printing_Queue_ID=" + printingQueueItemId.getRepoId(), e);
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (final Exception ignored)
{
}
}
}
}
public PrintingData onlyWithType(@NonNull final OutputType outputType)
{
final ImmutableList<PrintingSegment> filteredSegments = segments.stream()
.filter(segment -> segment.isMatchingOutputType(outputType))
.collect(ImmutableList.toImmutableList());
return toBuilder()
.clearSegments()
.segments(filteredSegments)
.adjustSegmentPageRanges(false)
.build();
}
public PrintingData onlyQueuedForExternalSystems()
{
final ImmutableList<PrintingSegment> filteredSegments = segments.stream()
.filter(PrintingSegment::isQueuedForExternalSystems)
.collect(ImmutableList.toImmutableList());
return toBuilder()
.clearSegments()
.segments(filteredSegments)
.adjustSegmentPageRanges(false)
.build();
}
public boolean hasSegments() {return !getSegments().isEmpty();}
public int getSegmentsCount() {return getSegments().size();}
public ImmutableSet<String> getPrinterNames()
{
return segments.stream()
.map(segment -> segment.getPrinter().getName())
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingData.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public InitializingBean registerProcessCandidateStarterUserRemovedListenerDelegate(
RuntimeService runtimeService,
@Autowired(required = false) List<
ProcessRuntimeEventListener<ProcessCandidateStarterUserRemovedEvent>
> listeners,
ToAPIProcessCandidateStarterUserRemovedEventConverter processCandidateStarterUserRemovedEventConverter
) {
return () ->
runtimeService.addEventListener(
new ProcessCandidateStarterUserRemovedListenerDelegate(
getInitializedListeners(listeners),
processCandidateStarterUserRemovedEventConverter
),
ActivitiEventType.ENTITY_DELETED
);
}
@Bean
@ConditionalOnMissingBean
public ToAPIProcessCandidateStarterUserRemovedEventConverter processCandidateStarterUserRemovedEventConverter(
APIProcessCandidateStarterUserConverter processCandidateStarterUserConverter
) {
return new ToAPIProcessCandidateStarterUserRemovedEventConverter(processCandidateStarterUserConverter);
}
@Bean
|
@ConditionalOnMissingBean(name = "registerProcessCandidateStarterGroupRemovedListenerDelegate")
public InitializingBean registerProcessCandidateStarterGroupRemovedListenerDelegate(
RuntimeService runtimeService,
@Autowired(required = false) List<
ProcessRuntimeEventListener<ProcessCandidateStarterGroupRemovedEvent>
> listeners,
ToAPIProcessCandidateStarterGroupRemovedEventConverter processCandidateStarterGroupRemovedEventConverter
) {
return () ->
runtimeService.addEventListener(
new ProcessCandidateStarterGroupRemovedListenerDelegate(
getInitializedListeners(listeners),
processCandidateStarterGroupRemovedEventConverter
),
ActivitiEventType.ENTITY_DELETED
);
}
@Bean
@ConditionalOnMissingBean
public ToAPIProcessCandidateStarterGroupRemovedEventConverter processCandidateStarterGroupRemovedEventConverter(
APIProcessCandidateStarterGroupConverter processCandidateStarterGroupConverter
) {
return new ToAPIProcessCandidateStarterGroupRemovedEventConverter(processCandidateStarterGroupConverter);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\conf\ProcessRuntimeAutoConfiguration.java
| 2
|
请完成以下Java代码
|
private static Instant extractInvoiceDate(final I_C_Invoice invoice, final @NonNull InvoiceOpenRequest.DateColumn dateColumn)
{
switch (dateColumn)
{
case DateAcct:
return invoice.getDateAcct().toInstant();
case DateTrx:
default:
return invoice.getDateInvoiced().toInstant();
}
}
@Override
public BigDecimal retrieveWriteoffAmt(final org.compiere.model.I_C_Invoice invoice)
{
return retrieveWriteoffAmt(invoice, o -> {
final I_C_AllocationLine line = (I_C_AllocationLine)o;
return line.getWriteOffAmt();
});
}
private BigDecimal retrieveWriteoffAmt(final org.compiere.model.I_C_Invoice invoice, final TypedAccessor<BigDecimal> amountAccessor)
{
BigDecimal sum = BigDecimal.ZERO;
for (final I_C_AllocationLine line : retrieveAllocationLines(invoice))
{
final I_C_AllocationHdr ah = line.getC_AllocationHdr();
final BigDecimal lineWriteOff = amountAccessor.getValue(line);
if (null != ah && ah.getC_Currency_ID() != invoice.getC_Currency_ID())
{
final BigDecimal lineWriteOffConv = Services.get(ICurrencyBL.class).convert(
lineWriteOff, // Amt
CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID
CurrencyId.ofRepoId(invoice.getC_Currency_ID()), // CurTo_ID
|
ah.getDateTrx().toInstant(), // ConvDate
CurrencyConversionTypeId.ofRepoIdOrNull(invoice.getC_ConversionType_ID()),
ClientId.ofRepoId(line.getAD_Client_ID()),
OrgId.ofRepoId(line.getAD_Org_ID()));
sum = sum.add(lineWriteOffConv);
}
else
{
sum = sum.add(lineWriteOff);
}
}
return sum;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\impl\PlainAllocationDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class AutoConfiguredWebClientSsl implements WebClientSsl {
private final ClientHttpConnectorBuilder<?> connectorBuilder;
private final HttpClientSettings settings;
private final SslBundles sslBundles;
AutoConfiguredWebClientSsl(ClientHttpConnectorBuilder<?> connectorBuilder, HttpClientSettings settings,
SslBundles sslBundles) {
this.connectorBuilder = connectorBuilder;
this.settings = settings;
this.sslBundles = sslBundles;
}
|
@Override
public Consumer<WebClient.Builder> fromBundle(String bundleName) {
return fromBundle(this.sslBundles.getBundle(bundleName));
}
@Override
public Consumer<WebClient.Builder> fromBundle(SslBundle bundle) {
return (builder) -> {
HttpClientSettings settings = this.settings.withSslBundle(bundle);
ClientHttpConnector connector = this.connectorBuilder.build(settings);
builder.clientConnector(connector);
};
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webclient\src\main\java\org\springframework\boot\webclient\autoconfigure\AutoConfiguredWebClientSsl.java
| 2
|
请完成以下Java代码
|
public void applyToSystemProperties() {
applyTo(System.getProperties());
}
/**
* Apply log file details to {@code LOG_PATH} and {@code LOG_FILE} map entries.
* @param properties the properties to apply to
*/
public void applyTo(Properties properties) {
put(properties, LoggingSystemProperty.LOG_PATH, this.path);
put(properties, LoggingSystemProperty.LOG_FILE, toString());
}
private void put(Properties properties, LoggingSystemProperty property, @Nullable String value) {
if (StringUtils.hasLength(value)) {
properties.put(property.getEnvironmentVariableName(), value);
}
}
@Override
public String toString() {
if (StringUtils.hasLength(this.file)) {
return this.file;
}
return new File(this.path, "spring.log").getPath();
}
/**
|
* Get a {@link LogFile} from the given Spring {@link Environment}.
* @param propertyResolver the {@link PropertyResolver} used to obtain the logging
* properties
* @return a {@link LogFile} or {@code null} if the environment didn't contain any
* suitable properties
*/
public static @Nullable LogFile get(PropertyResolver propertyResolver) {
String file = propertyResolver.getProperty(FILE_NAME_PROPERTY);
String path = propertyResolver.getProperty(FILE_PATH_PROPERTY);
if (StringUtils.hasLength(file) || StringUtils.hasLength(path)) {
return new LogFile(file, path);
}
return null;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LogFile.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return getClass().getSimpleName() + "["
+ resource
+ ", " + accesses
+ "]";
}
@Override
public boolean hasAccess(final Access access)
{
return accesses.contains(access);
}
@Override
public Permission mergeWith(final Permission permissionFrom)
{
final TableColumnPermission columnPermissionFrom = checkCompatibleAndCast(permissionFrom);
return asNewBuilder()
.addAccesses(columnPermissionFrom.accesses)
.build();
}
public int getAD_Table_ID()
{
return resource.getAD_Table_ID();
}
public int getAD_Column_ID()
{
return resource.getAD_Column_ID();
}
public static class Builder
{
private TableColumnResource resource;
private final Set<Access> accesses = new LinkedHashSet<>();
public TableColumnPermission build()
{
return new TableColumnPermission(this);
}
public Builder setFrom(final TableColumnPermission columnPermission)
{
setResource(columnPermission.getResource());
setAccesses(columnPermission.accesses);
return this;
}
public Builder setResource(final TableColumnResource resource)
{
this.resource = resource;
return this;
}
public final Builder addAccess(final Access access)
{
accesses.add(access);
return this;
}
|
public final Builder removeAccess(final Access access)
{
accesses.remove(access);
return this;
}
public final Builder setAccesses(final Set<Access> acceses)
{
accesses.clear();
accesses.addAll(acceses);
return this;
}
public final Builder addAccesses(final Set<Access> acceses)
{
accesses.addAll(acceses);
return this;
}
public final Builder removeAllAccesses()
{
accesses.clear();
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnPermission.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
|
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", age=" + age
+ ", name=" + name + ", genre=" + genre + ", email=" + email + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootReferenceNaturalId\src\main\java\com\bookstore\entity\Author.java
| 1
|
请完成以下Java代码
|
public void setQty(final BigDecimal qty)
{
shipmentSchedule.setQtyOrdered_Override(qty);
}
@Override
public BigDecimal getQty()
{
// task 09005: make sure the correct qtyOrdered is taken from the shipmentSchedule
final BigDecimal qtyOrdered = Services.get(IShipmentScheduleEffectiveBL.class).computeQtyOrdered(shipmentSchedule);
return qtyOrdered;
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
return shipmentSchedule.getM_HU_PI_Item_Product_ID();
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
values.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
{
return shipmentSchedule.getQtyOrdered_TU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
shipmentSchedule.setQtyOrdered_TU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
|
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ShipmentScheduleHUPackingAware.java
| 1
|
请完成以下Java代码
|
public static String[][] spiltArray(String[] src, double rate)
{
assert 0 <= rate && rate <= 1;
String[][] output = new String[2][];
output[0] = new String[(int) (src.length * rate)];
output[1] = new String[src.length - output[0].length];
System.arraycopy(src, 0, output[0], 0, output[0].length);
System.arraycopy(src, output[0].length, output[1], 0, output[1].length);
return output;
}
/**
* 分割Map,其中旧map直接被改变
* @param src
* @param rate
|
* @return
*/
public static Map<String, String[]> splitMap(Map<String, String[]> src, double rate)
{
assert 0 <= rate && rate <= 1;
Map<String, String[]> output = new TreeMap<String, String[]>();
for (Map.Entry<String, String[]> entry : src.entrySet())
{
String[][] array = spiltArray(entry.getValue(), rate);
output.put(entry.getKey(), array[0]);
entry.setValue(array[1]);
}
return output;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\utilities\CollectionUtility.java
| 1
|
请完成以下Java代码
|
public static Map<String, ProcessEngine> getProcessEngines() {
return processEngines;
}
/**
* closes all process engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, ProcessEngine> engines = new HashMap<String, ProcessEngine>(processEngines);
processEngines = new HashMap<String, ProcessEngine>();
for (String processEngineName : engines.keySet()) {
ProcessEngine processEngine = engines.get(processEngineName);
try {
processEngine.close();
} catch (Exception e) {
log.error(
"exception while closing {}",
(processEngineName == null
? "the default process engine"
|
: "process engine " + processEngineName),
e
);
}
}
processEngineInfosByName.clear();
processEngineInfosByResourceUrl.clear();
processEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
ProcessEngines.isInitialized = isInitialized;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngines.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public FreeTextType getFreeText() {
return freeText;
}
/**
* Sets the value of the freeText property.
*
* @param value
* allowed object is
* {@link FreeTextType }
*
*/
public void setFreeText(FreeTextType value) {
this.freeText = value;
}
/**
* Additional duration information for MaterialAuthorization (.../ForecastListLineItem/AdditionalForecastInformation/MaterialAuthorization) coded in ISO 8601/durations format.
*
* @return
* possible object is
* {@link Duration }
*
*/
public Duration getMaterialAuthorizationDuration() {
return materialAuthorizationDuration;
}
/**
* Sets the value of the materialAuthorizationDuration property.
*
* @param value
* allowed object is
|
* {@link Duration }
*
*/
public void setMaterialAuthorizationDuration(Duration value) {
this.materialAuthorizationDuration = value;
}
/**
* Additional duration information for ProductionAuthorization (.../ForecastListLineItem/AdditionalForecastInformation/ProductionAuthorization) coded in ISO 8601/durations format.
*
* @return
* possible object is
* {@link Duration }
*
*/
public Duration getProductionAuthorizationDuration() {
return productionAuthorizationDuration;
}
/**
* Sets the value of the productionAuthorizationDuration property.
*
* @param value
* allowed object is
* {@link Duration }
*
*/
public void setProductionAuthorizationDuration(Duration value) {
this.productionAuthorizationDuration = 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\ForecastListLineItemExtensionType.java
| 2
|
请完成以下Java代码
|
public class FreshInvoiceCandBL implements IFreshInvoiceCandBL
{
@Override
public void updateC_DocTypeInvoice(I_C_Invoice_Candidate candidate)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
if (candidate.isSOTrx())
{
// nothing to do, because the produzendenabrechnung doctype is only for purchase transactions
return;
}
final DocTypeId freshProduzentenabrechnung = Services.get(IDocTypeDAO.class).getDocTypeId(
DocTypeQuery.builder()
.docBaseType(DocBaseType.PurchaseInvoice)
.docSubType(DocSubType.VendorInvoice)
.adClientId(candidate.getAD_Client_ID())
.adOrgId(candidate.getAD_Org_ID())
.build());
if (freshProduzentenabrechnung == null)
{
// This means that no API - VI doc type was defined in db
// do nothing
return;
}
final int candidateDocTypeID = candidate.getC_DocTypeInvoice_ID();
final I_C_BPartner partner = bpartnerDAO.getById(BPartnerId.ofRepoId(candidate.getBill_BPartner_ID()), I_C_BPartner.class);
final boolean isFresh_Produzentenabrechnung = partner.isFresh_Produzentenabrechnung();
if (!isFresh_Produzentenabrechnung)
{
if (freshProduzentenabrechnung.getRepoId() == candidateDocTypeID)
{
// the candidate was already freshProduzentenabrechnung but the partner was changed
// and the new partner is not freshProduzentenabrechnung
// In this case, the doctype of the candidate will be set to null
|
candidate.setC_DocTypeInvoice_ID(-1);
}
// no other validations needed. Do nothing any more
return;
}
if (candidate.getC_DocTypeInvoice_ID() > 0)
{
// check if we already have another special docType from material tracking
final I_C_DocType docTypeInvoice = docTypeDAO.getById(DocTypeId.ofRepoId(candidate.getC_DocTypeInvoice_ID()));
if (X_C_DocType.DOCBASETYPE_APInvoice.equals(docTypeInvoice.getDocBaseType()) &&
(IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_DownPayment.equals(docTypeInvoice.getDocSubType()) ||
IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_FinalSettlement.equals(docTypeInvoice.getDocSubType())))
{
return; // task 07845: these two doctypes are even more specific; don't override them
}
}
candidate.setC_DocTypeInvoice_ID(freshProduzentenabrechnung.getRepoId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\api\invoicecandidate\impl\FreshInvoiceCandBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorDetails() {
return errorDetails;
}
public void setErrorDetails(String errorDetails) {
this.errorDetails = errorDetails;
}
public Integer getRetries() {
|
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public Duration getRetryTimeout() {
return retryTimeout;
}
public void setRetryTimeout(Duration retryTimeout) {
this.retryTimeout = retryTimeout;
}
}
|
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\acquire\ExternalWorkerJobFailureRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public GatewayLegacyControllerEndpoint gatewayLegacyControllerEndpoint(
RouteDefinitionLocator routeDefinitionLocator, List<GlobalFilter> globalFilters,
List<GatewayFilterFactory> gatewayFilters, List<RoutePredicateFactory> routePredicates,
RouteDefinitionWriter routeDefinitionWriter, RouteLocator routeLocator,
WebEndpointProperties webEndpointProperties) {
return new GatewayLegacyControllerEndpoint(routeDefinitionLocator, globalFilters, gatewayFilters,
routePredicates, routeDefinitionWriter, routeLocator, webEndpointProperties);
}
}
private static class OnVerboseDisabledCondition extends NoneNestedConditions {
OnVerboseDisabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = "spring.cloud.gateway.server.webflux.actuator.verbose.enabled",
matchIfMissing = true)
static class VerboseDisabled {
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.cloud.gateway.server.webflux.enabled", matchIfMissing = true)
@ConditionalOnClass({ OAuth2AuthorizedClient.class, SecurityWebFilterChain.class, SecurityProperties.class })
@ConditionalOnEnabledFilter(TokenRelayGatewayFilterFactory.class)
protected static class TokenRelayConfiguration {
@Bean
public TokenRelayGatewayFilterFactory tokenRelayGatewayFilterFactory(
ObjectProvider<ReactiveOAuth2AuthorizedClientManager> clientManager) {
return new TokenRelayGatewayFilterFactory(clientManager);
}
}
|
}
class GatewayHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
if (!ClassUtils.isPresent("org.springframework.cloud.gateway.route.RouteLocator", classLoader)) {
return;
}
hints.reflection()
.registerType(TypeReference.of(FilterDefinition.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference.of(PredicateDefinition.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference.of(AbstractNameValueGatewayFilterFactory.NameValueConfig.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference
.of("org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator$DelegatingServiceInstance"),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private static void addValue(JsonObjectBuilder builder, String key, Object value) {
if (value != null) {
builder.add(key, value.toString());
} else {
builder.addNull(key);
}
}
public static JsonArray map(List<Book> books) {
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
books.forEach(book -> {
JsonObject jsonObject = map(book);
arrayBuilder.add(jsonObject);
});
return arrayBuilder.build();
}
public static Book map(InputStream is) {
try(JsonReader jsonReader = Json.createReader(is)) {
JsonObject jsonObject = jsonReader.readObject();
Book book = new Book();
book.setId(getStringFromJson("id", jsonObject));
book.setIsbn(getStringFromJson("isbn", jsonObject));
book.setName(getStringFromJson("name", jsonObject));
book.setAuthor(getStringFromJson("author", jsonObject));
book.setPages(getIntFromJson("pages",jsonObject));
return book;
}
}
private static String getStringFromJson(String key, JsonObject json) {
String returnedString = null;
|
if (json.containsKey(key)) {
JsonString value = json.getJsonString(key);
if (value != null) {
returnedString = value.getString();
}
}
return returnedString;
}
private static Integer getIntFromJson(String key, JsonObject json) {
Integer returnedValue = null;
if (json.containsKey(key)) {
JsonNumber value = json.getJsonNumber(key);
if (value != null) {
returnedValue = value.intValue();
}
}
return returnedValue;
}
}
|
repos\tutorials-master\microservices-modules\helidon\helidon-mp\src\main\java\com\baeldung\microprofile\util\BookMapper.java
| 2
|
请完成以下Java代码
|
public class DictionaryParser {
private Map<String, String> dictionaryParsed = new HashMap<>();
public DictionaryParser(File sourceFile) throws IOException {
parseDictionaryDump(FileUtils.lineIterator(sourceFile));
}
public String getKeyByKeyId(String keyId) {
return dictionaryParsed.get(keyId);
}
private boolean isBlockFinished(String line) {
return StringUtils.isBlank(line) || line.equals("\\.");
}
private boolean isBlockStarted(String line) {
return line.startsWith("COPY public.key_dictionary (");
}
private void parseDictionaryDump(LineIterator iterator) throws IOException {
try {
String tempLine;
while (iterator.hasNext()) {
tempLine = iterator.nextLine();
if (isBlockStarted(tempLine)) {
processBlock(iterator);
}
}
} finally {
|
iterator.close();
}
}
private void processBlock(LineIterator lineIterator) {
String tempLine;
String[] lineSplited;
while(lineIterator.hasNext()) {
tempLine = lineIterator.nextLine();
if(isBlockFinished(tempLine)) {
return;
}
lineSplited = tempLine.split("\t");
dictionaryParsed.put(lineSplited[1], lineSplited[0]);
}
}
}
|
repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\DictionaryParser.java
| 1
|
请完成以下Java代码
|
public void setSeqNo (final int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
|
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ElementValue.java
| 1
|
请完成以下Java代码
|
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_Item getM_HU_Item()
{
return get_ValueAsPO(COLUMNNAME_M_HU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class);
}
@Override
public void setM_HU_Item(final de.metas.handlingunits.model.I_M_HU_Item M_HU_Item)
{
set_ValueFromPO(COLUMNNAME_M_HU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, M_HU_Item);
}
@Override
public void setM_HU_Item_ID (final int M_HU_Item_ID)
{
if (M_HU_Item_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, M_HU_Item_ID);
}
@Override
public int getM_HU_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Item_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_Item_Storage getM_HU_Item_Storage()
{
return get_ValueAsPO(COLUMNNAME_M_HU_Item_Storage_ID, de.metas.handlingunits.model.I_M_HU_Item_Storage.class);
}
@Override
public void setM_HU_Item_Storage(final de.metas.handlingunits.model.I_M_HU_Item_Storage M_HU_Item_Storage)
{
set_ValueFromPO(COLUMNNAME_M_HU_Item_Storage_ID, de.metas.handlingunits.model.I_M_HU_Item_Storage.class, M_HU_Item_Storage);
}
@Override
public void setM_HU_Item_Storage_ID (final int M_HU_Item_Storage_ID)
{
if (M_HU_Item_Storage_ID < 1)
set_Value (COLUMNNAME_M_HU_Item_Storage_ID, null);
else
set_Value (COLUMNNAME_M_HU_Item_Storage_ID, M_HU_Item_Storage_ID);
}
@Override
public int getM_HU_Item_Storage_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID);
}
@Override
public void setM_HU_Item_Storage_Snapshot_ID (final int M_HU_Item_Storage_Snapshot_ID)
{
if (M_HU_Item_Storage_Snapshot_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, M_HU_Item_Storage_Snapshot_ID);
}
@Override
public int getM_HU_Item_Storage_Snapshot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_Snapshot_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 BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSnapshot_UUID (final java.lang.String Snapshot_UUID)
{
set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID);
}
@Override
public java.lang.String getSnapshot_UUID()
{
return get_ValueAsString(COLUMNNAME_Snapshot_UUID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage_Snapshot.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JobServiceConfiguration addHistoryJobHandler(String type, HistoryJobHandler historyJobHandler) {
if (this.historyJobHandlers == null) {
this.historyJobHandlers = new HashMap<>();
}
this.historyJobHandlers.put(type, historyJobHandler);
return this;
}
public int getAsyncExecutorNumberOfRetries() {
return asyncExecutorNumberOfRetries;
}
public JobServiceConfiguration setAsyncExecutorNumberOfRetries(int asyncExecutorNumberOfRetries) {
this.asyncExecutorNumberOfRetries = asyncExecutorNumberOfRetries;
return this;
}
public int getAsyncExecutorResetExpiredJobsMaxTimeout() {
return asyncExecutorResetExpiredJobsMaxTimeout;
}
public JobServiceConfiguration setAsyncExecutorResetExpiredJobsMaxTimeout(int asyncExecutorResetExpiredJobsMaxTimeout) {
this.asyncExecutorResetExpiredJobsMaxTimeout = asyncExecutorResetExpiredJobsMaxTimeout;
return this;
}
@Override
public ObjectMapper getObjectMapper() {
return objectMapper;
}
@Override
public JobServiceConfiguration setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
public List<JobProcessor> getJobProcessors() {
return jobProcessors;
}
public JobServiceConfiguration setJobProcessors(List<JobProcessor> jobProcessors) {
|
this.jobProcessors = Collections.unmodifiableList(jobProcessors);
return this;
}
public List<HistoryJobProcessor> getHistoryJobProcessors() {
return historyJobProcessors;
}
public JobServiceConfiguration setHistoryJobProcessors(List<HistoryJobProcessor> historyJobProcessors) {
this.historyJobProcessors = Collections.unmodifiableList(historyJobProcessors);
return this;
}
public void setJobParentStateResolver(InternalJobParentStateResolver jobParentStateResolver) {
this.jobParentStateResolver = jobParentStateResolver;
}
public InternalJobParentStateResolver getJobParentStateResolver() {
return jobParentStateResolver;
}
public List<String> getEnabledJobCategories() {
return enabledJobCategories;
}
public void setEnabledJobCategories(List<String> enabledJobCategories) {
this.enabledJobCategories = enabledJobCategories;
}
public void addEnabledJobCategory(String jobCategory) {
if (enabledJobCategories == null) {
enabledJobCategories = new ArrayList<>();
}
enabledJobCategories.add(jobCategory);
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\JobServiceConfiguration.java
| 2
|
请完成以下Java代码
|
public static ServletContextInitializers from(ServletWebServerSettings settings,
ServletContextInitializer... initializers) {
List<ServletContextInitializer> mergedInitializers = new ArrayList<>();
mergedInitializers
.add((servletContext) -> settings.getInitParameters().forEach(servletContext::setInitParameter));
mergedInitializers.add(new SessionConfiguringInitializer(settings.getSession()));
mergedInitializers.addAll(Arrays.asList(initializers));
mergedInitializers.addAll(settings.getInitializers());
return new ServletContextInitializers(mergedInitializers);
}
private static final class SessionConfiguringInitializer implements ServletContextInitializer {
private final Session session;
private SessionConfiguringInitializer(Session session) {
this.session = session;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (this.session.getTrackingModes() != null) {
servletContext.setSessionTrackingModes(unwrap(this.session.getTrackingModes()));
}
configureSessionCookie(servletContext.getSessionCookieConfig());
}
private void configureSessionCookie(SessionCookieConfig config) {
Cookie cookie = this.session.getCookie();
PropertyMapper map = PropertyMapper.get();
map.from(cookie::getName).to(config::setName);
map.from(cookie::getDomain).to(config::setDomain);
map.from(cookie::getPath).to(config::setPath);
map.from(cookie::getHttpOnly).to(config::setHttpOnly);
map.from(cookie::getSecure).to(config::setSecure);
map.from(cookie::getMaxAge).asInt(Duration::getSeconds).to(config::setMaxAge);
map.from(cookie::getPartitioned)
.as(Object::toString)
|
.to((partitioned) -> config.setAttribute("Partitioned", partitioned));
}
@Contract("!null -> !null")
private @Nullable Set<jakarta.servlet.SessionTrackingMode> unwrap(
@Nullable Set<Session.SessionTrackingMode> modes) {
if (modes == null) {
return null;
}
Set<jakarta.servlet.SessionTrackingMode> result = new LinkedHashSet<>();
for (Session.SessionTrackingMode mode : modes) {
result.add(jakarta.servlet.SessionTrackingMode.valueOf(mode.name()));
}
return result;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletContextInitializers.java
| 1
|
请完成以下Java代码
|
public int hashCode()
{
return Objects.hash(id);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final MethodNameCalloutInstance other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return id.equals(other.id);
}
@Override
public void execute(final ICalloutExecutor executor, final ICalloutField field)
{
try
{
legacyCallout.start(methodName, field);
}
catch (final CalloutException e)
{
throw e.setCalloutExecutor(executor)
.setCalloutInstance(this)
.setField(field);
}
catch (final Exception e)
{
|
throw CalloutExecutionException.wrapIfNeeded(e)
.setCalloutExecutor(executor)
.setCalloutInstance(this)
.setField(field);
}
}
@VisibleForTesting
public org.compiere.model.Callout getLegacyCallout()
{
return legacyCallout;
}
public String getMethodName()
{
return methodName;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\MethodNameCalloutInstance.java
| 1
|
请完成以下Java代码
|
public final class ObjectFactoryHelper
{
private ObjectFactoryHelper()
{
super();
}
public static <TT> JAXBElement<TT> createJAXBElement(final Object objectFactory, final TT obj) throws JAXBException
{
if (obj == null)
{
return null;
}
final Class<?> objClass = obj.getClass();
for (final Method method : objectFactory.getClass().getDeclaredMethods())
{
if (!method.getName().startsWith("create"))
{
continue;
}
if (method.getParameterTypes().length != 1)
{
continue;
}
|
if (!method.getParameterTypes()[0].equals(objClass))
{
continue;
}
if (!method.getReturnType().equals(JAXBElement.class))
{
continue;
}
try
{
@SuppressWarnings("unchecked")
JAXBElement<TT> jaxbElement = (JAXBElement<TT>)method.invoke(objectFactory, obj);
return jaxbElement;
}
catch (Exception e)
{
throw new JAXBException("Cannot convert object " + obj + " to JAXBElement by using method " + method, e);
}
}
throw new JAXBException("No converter method found in factory: " + objectFactory);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\jaxb\ObjectFactoryHelper.java
| 1
|
请完成以下Java代码
|
public class SynchronizationBadPracticeExample {
public void stringBadPractice1() {
String stringLock = "LOCK_STRING";
synchronized (stringLock) {
// ...
}
}
private final String stringLock = "LOCK_STRING";
public void stringBadPractice2() {
synchronized (stringLock) {
// ...
}
}
private final String internedStringLock = new String("LOCK_STRING").intern();
public void stringBadPractice3() {
synchronized (internedStringLock) {
// ...
}
}
private final Boolean booleanLock = Boolean.FALSE;
public void booleanBadPractice() {
synchronized (booleanLock) {
// ...
}
}
|
private int count = 0;
private final Integer intLock = count;
public void boxedPrimitiveBadPractice() {
synchronized (intLock) {
count++;
// ...
}
}
public void classBadPractice() throws InterruptedException {
AnimalBadPractice animalObj = new AnimalBadPractice("Tommy", "John");
synchronized(animalObj) {
while (true) {
Thread.sleep(Integer.MAX_VALUE);
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-4\src\main\java\com\baeldung\synchronizationbadpractices\SynchronizationBadPracticeExample.java
| 1
|
请完成以下Java代码
|
Map<String, Object> getChangedJson() {
return Collections.singletonMap("user", getJson());
}
/**
* Returns a simple XML payload.
*
* @return
*/
@GetMapping(path = "/", produces = MediaType.APPLICATION_XML_VALUE)
String getXml() {
return "<user>".concat(XML_PAYLOAD).concat("</user>");
}
/**
* Returns the payload of {@link #getXml()} wrapped into another XML element to simulate a change in the
* representation structure.
*
* @return
*/
@GetMapping(path = "/changed", produces = MediaType.APPLICATION_XML_VALUE)
String getChangedXml() {
return "<user><username>".concat(XML_PAYLOAD).concat("</username></user>");
|
}
/**
* The projection interface using XPath and JSON Path expression to selectively pick elements from the payload.
*
* @author Oliver Gierke
*/
@ProjectedPayload
public interface UserPayload {
@XBRead("//firstname")
@JsonPath("$..firstname")
String getFirstname();
@XBRead("//lastname")
@JsonPath("$..lastname")
String getLastname();
}
}
|
repos\spring-data-examples-main\web\projection\src\main\java\example\users\UserController.java
| 1
|
请完成以下Java代码
|
public final class MessageHeaderUtils {
/**
* Message Header name which contains HTTP request parameters.
*/
public static final String HTTP_REQUEST_PARAM = "http_request_param";
private static final HttpHeaders IGNORED = new HttpHeaders();
private static final HttpHeaders REQUEST_ONLY = new HttpHeaders();
static {
IGNORED.add(MessageHeaders.ID, "");
IGNORED.add(HttpHeaders.CONTENT_LENGTH, "0");
// Headers that would typically be added by a downstream client
REQUEST_ONLY.add(HttpHeaders.ACCEPT, "");
REQUEST_ONLY.add(HttpHeaders.CONTENT_LENGTH, "");
REQUEST_ONLY.add(HttpHeaders.CONTENT_TYPE, "");
REQUEST_ONLY.add(HttpHeaders.HOST, "");
}
private MessageHeaderUtils() {
throw new IllegalStateException("Can't instantiate a utility class");
}
public static HttpHeaders fromMessage(MessageHeaders headers, List<String> ignoredHeders) {
HttpHeaders result = new HttpHeaders();
for (String name : headers.keySet()) {
Object value = headers.get(name);
name = name.toLowerCase(Locale.ROOT);
if (!IGNORED.containsHeader(name) && !ignoredHeders.contains(name)) {
Collection<?> values = multi(value);
for (Object object : values) {
result.set(name, object.toString());
}
}
}
return result;
}
@SuppressWarnings("unchecked")
public static HttpHeaders fromMessage(MessageHeaders headers) {
return fromMessage(headers, Collections.EMPTY_LIST);
}
public static HttpHeaders sanitize(HttpHeaders request, List<String> ignoredHeders,
List<String> requestOnlyHeaders) {
HttpHeaders result = new HttpHeaders();
for (String name : request.headerNames()) {
List<String> value = request.get(name);
name = name.toLowerCase(Locale.ROOT);
if (!IGNORED.containsHeader(name) && !REQUEST_ONLY.containsHeader(name) && !ignoredHeders.contains(name)
|
&& !requestOnlyHeaders.contains(name)) {
result.put(name, value);
}
}
return result;
}
@SuppressWarnings("unchecked")
public static HttpHeaders sanitize(HttpHeaders request) {
return sanitize(request, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
}
public static MessageHeaders fromHttp(HttpHeaders headers) {
Map<String, Object> map = new LinkedHashMap<>();
for (String name : headers.headerNames()) {
Collection<?> values = multi(headers.get(name));
name = name.toLowerCase(Locale.ROOT);
Object value = values == null ? null : (values.size() == 1 ? values.iterator().next() : values);
if (name.toLowerCase(Locale.ROOT).equals(HttpHeaders.CONTENT_TYPE.toLowerCase(Locale.ROOT))) {
name = MessageHeaders.CONTENT_TYPE;
}
map.put(name, value);
}
return new MessageHeaders(map);
}
private static Collection<?> multi(Object value) {
return value instanceof Collection ? (Collection<?>) value : Arrays.asList(value);
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\MessageHeaderUtils.java
| 1
|
请完成以下Java代码
|
public Timestamp getLastDayOfYear(final I_C_Year year)
{
final I_C_Period period = Services.get(ICalendarDAO.class).retrieveLastPeriodOfTheYear(year);
final Timestamp lastDay = period.getEndDate();
return lastDay;
}
@Override
public Timestamp getFirstDayOfYear(final I_C_Year year)
{
final I_C_Period period = Services.get(ICalendarDAO.class).retrieveFirstPeriodOfTheYear(year);
final Timestamp firstDay = period.getStartDate();
return firstDay;
}
@Override
public void checkCorrectCalendar(final I_C_Calendar calendar)
{
Check.errorUnless(isCalendarNoOverlaps(calendar), "{} has overlaps", calendar);
Check.errorUnless(isCalendarNoGaps(calendar), "{} has gaps", calendar);
final List<I_C_Year> years = Services.get(ICalendarDAO.class).retrieveYearsOfCalendar(calendar);
for (final I_C_Year year : years)
{
Check.errorUnless(isLengthOneYear(year), "{} doesn't have the length 1 year", year);
}
}
private List<I_C_Period> getPeriodsOfCalendar(final I_C_Calendar calendar)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(calendar);
final String trxName = InterfaceWrapperHelper.getTrxName(calendar);
final List<I_C_Year> years = Services.get(ICalendarDAO.class).retrieveYearsOfCalendar(calendar);
final List<I_C_Period> periodsOfCalendar = new ArrayList<>();
for (final I_C_Year year : years)
{
final List<I_C_Period> periodsOfYear = Services.get(ICalendarDAO.class).retrievePeriods(ctx, year, trxName);
periodsOfCalendar.addAll(periodsOfYear);
}
Collections.sort(periodsOfCalendar, new AccessorComparator<I_C_Period, Timestamp>(
new ComparableComparator<Timestamp>(),
new TypedAccessor<Timestamp>()
|
{
@Override
public Timestamp getValue(final Object o)
{
return ((I_C_Period)o).getStartDate();
}
}));
return periodsOfCalendar;
}
@Override
public boolean isStandardPeriod(final I_C_Period period)
{
return X_C_Period.PERIODTYPE_StandardCalendarPeriod.equals(period.getPeriodType());
} // isStandardPeriod
@Override
public IBusinessDayMatcher createBusinessDayMatcherExcluding(final Set<DayOfWeek> excludeWeekendDays)
{
// TODO: consider I_C_NonBusinessDay and compose the matchers using CompositeBusinessDayMatcher
return ExcludeWeekendBusinessDayMatcher.builder()
.excludeWeekendDays(excludeWeekendDays)
.build();
}
@Override
@NonNull
public CalendarId getOrgCalendarOrDefault(final @NonNull OrgId orgId)
{
final OrgInfo orgInfo = orgDAO.getOrgInfoByIdInTrx(orgId);
if (orgInfo.getCalendarId() != null)
{
return orgInfo.getCalendarId();
}
final I_C_Calendar calendar = calendarDAO.getDefaultCalendar(orgId);
return CalendarId.ofRepoId(calendar.getC_Calendar_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\CalendarBL.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BPartner_Department_ID (final int C_BPartner_Department_ID)
{
if (C_BPartner_Department_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Department_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Department_ID, C_BPartner_Department_ID);
}
@Override
public int getC_BPartner_Department_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Department_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
|
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Department.java
| 1
|
请完成以下Java代码
|
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public void setPosted (boolean Posted)
{
set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted));
}
@Override
public boolean isPosted()
{
return get_ValueAsBoolean(COLUMNNAME_Posted);
}
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
|
}
@Override
public void setStatementDate (java.sql.Timestamp StatementDate)
{
set_Value (COLUMNNAME_StatementDate, StatementDate);
}
@Override
public java.sql.Timestamp getStatementDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StatementDate);
}
@Override
public void setStatementDifference (java.math.BigDecimal StatementDifference)
{
set_Value (COLUMNNAME_StatementDifference, StatementDifference);
}
@Override
public java.math.BigDecimal getStatementDifference()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StatementDifference);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BankStatement.java
| 1
|
请完成以下Java代码
|
public abstract class HandleExternalTaskCmd extends ExternalTaskCmd {
/**
* The reported worker id.
*/
protected String workerId;
public HandleExternalTaskCmd(String externalTaskId, String workerId) {
super(externalTaskId);
this.workerId = workerId;
}
@Override
public Void execute(CommandContext commandContext) {
validateInput();
ExternalTaskEntity externalTask = commandContext.getExternalTaskManager().findExternalTaskById(externalTaskId);
EnsureUtil.ensureNotNull(NotFoundException.class,
"Cannot find external task with id " + externalTaskId, "externalTask", externalTask);
if (validateWorkerViolation(externalTask)) {
throw new BadUserRequestException(getErrorMessageOnWrongWorkerAccess() + "'. It is locked by worker '" + externalTask.getWorkerId() + "'.");
}
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateProcessInstanceById(externalTask.getProcessInstanceId());
}
try {
execute(externalTask);
} catch (NotFoundException e) {
// wrap up NotFoundExceptions reported for entities different than external tasks
throw new ProcessEngineException(e.getMessage(), e);
}
return null;
}
/**
* Returns the error message. Which is used to create an specific message
|
* for the BadUserRequestException if an worker has no rights to execute commands of the external task.
*
* @return the specific error message
*/
public abstract String getErrorMessageOnWrongWorkerAccess();
/**
* Validates the current input of the command.
*/
@Override
protected void validateInput() {
EnsureUtil.ensureNotNull("workerId", workerId);
}
/**
* Validates the caller's workerId against the workerId of the external task.
*/
protected boolean validateWorkerViolation(ExternalTaskEntity externalTask) {
return !workerId.equals(externalTask.getWorkerId());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\HandleExternalTaskCmd.java
| 1
|
请完成以下Java代码
|
public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public String getUrl() {
return url;
}
@Override
public void setUrl(String url) {
this.url = url;
}
@Override
public String getContentId() {
return contentId;
}
@Override
public void setContentId(String contentId) {
this.contentId = contentId;
}
|
@Override
public ByteArrayEntity getContent() {
return content;
}
@Override
public void setContent(ByteArrayEntity content) {
this.content = content;
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String getUserId() {
return userId;
}
@Override
public Date getTime() {
return time;
}
@Override
public void setTime(Date time) {
this.time = time;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\AttachmentEntityImpl.java
| 1
|
请完成以下Java代码
|
public List<JobEntity> findJobsToExecute(Page page) {
return getDbSqlSession().selectList("selectJobsToExecute", null, page);
}
@Override
public List<JobEntity> findJobsByExecutionId(final String executionId) {
return getList("selectJobsByExecutionId", executionId, jobsByExecutionIdMatcher, true);
}
@Override
public List<JobEntity> findJobsByProcessDefinitionId(final String processDefinitionId) {
Map<String, String> params = new HashMap<String, String>(1);
params.put("processDefinitionId", processDefinitionId);
return getDbSqlSession().selectList("selectJobByProcessDefinitionId", params);
}
@Override
public List<JobEntity> findJobsByTypeAndProcessDefinitionId(
final String jobHandlerType,
final String processDefinitionId
) {
Map<String, String> params = new HashMap<String, String>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionId", processDefinitionId);
return getDbSqlSession().selectList("selectJobByTypeAndProcessDefinitionId", params);
}
@Override
@SuppressWarnings("unchecked")
public List<JobEntity> findJobsByProcessInstanceId(final String processInstanceId) {
return getDbSqlSession().selectList("selectJobsByProcessInstanceId", processInstanceId);
}
@Override
@SuppressWarnings("unchecked")
public List<JobEntity> findExpiredJobs(Page page) {
Date now = getClock().getCurrentTime();
return getDbSqlSession().selectList("selectExpiredJobs", now, page);
|
}
@Override
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) {
final String query = "selectJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
}
@Override
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectJobCountByQueryCriteria", jobQuery);
}
@Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateJobTenantIdForDeployment", params);
}
@Override
public void resetExpiredJob(String jobId) {
Map<String, Object> params = new HashMap<String, Object>(2);
params.put("id", jobId);
getDbSqlSession().update("resetExpiredJob", params);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisJobDataManager.java
| 1
|
请完成以下Java代码
|
public class ToFromStringSerde<T> implements Serde<T> {
private final ToStringSerializer<T> toStringSerializer;
private final ParseStringDeserializer<T> fromStringDeserializer;
/**
* Construct an instance with the provided properties.
* @param toStringSerializer the {@link ToStringSerializer}.
* @param fromStringDeserializer the {@link ParseStringDeserializer}.
*/
public ToFromStringSerde(ToStringSerializer<T> toStringSerializer,
ParseStringDeserializer<T> fromStringDeserializer) {
Assert.notNull(toStringSerializer, "'toStringSerializer' must not be null.");
Assert.notNull(fromStringDeserializer, "'fromStringDeserializer' must not be null.");
this.toStringSerializer = toStringSerializer;
this.fromStringDeserializer = fromStringDeserializer;
}
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
|
this.toStringSerializer.configure(configs, isKey);
this.fromStringDeserializer.configure(configs, isKey);
}
@Override
public Serializer<T> serializer() {
return this.toStringSerializer;
}
@Override
public Deserializer<T> deserializer() {
return this.fromStringDeserializer;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\ToFromStringSerde.java
| 1
|
请完成以下Java代码
|
public IQueryOrderByBuilder<T> addColumn(
@NonNull final String columnName,
@NonNull final Direction direction,
@NonNull final Nulls nulls)
{
final QueryOrderByItem orderByItem = new QueryOrderByItem(columnName, direction, nulls);
orderBys.add(orderByItem);
return this;
}
@Override
public IQueryOrderByBuilder<T> addColumn(@NonNull final ModelColumn<T, ?> column, final Direction direction, final Nulls nulls)
{
final String columnName = column.getColumnName();
return addColumn(columnName, direction, nulls);
}
private Nulls getNulls(final Direction direction)
{
// NOTE: keeping backward compatibility
// i.e. postgresql 9.1. specifications:
// "By default, null values sort as if larger than any non-null value;
// that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise."
|
//
// see https://www.postgresql.org/docs/9.5/queries-order.html
if (direction == Direction.Descending)
{
return Nulls.First;
}
else
{
return Nulls.Last;
}
}
@Override
public IQueryOrderBy createQueryOrderBy()
{
final QueryOrderBy orderBy = new QueryOrderBy(orderBys);
return orderBy;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryOrderByBuilder.java
| 1
|
请完成以下Java代码
|
protected void createCompensateEventSubscription(ActivityExecution execution) {
String compensationHandlerId = (String) execution.getActivity().getProperty(BpmnParse.PROPERTYNAME_COMPENSATION_HANDLER_ID);
ExecutionEntity executionEntity = (ExecutionEntity) execution;
ActivityImpl compensationHandler = executionEntity.getProcessDefinition().findActivity(compensationHandlerId);
PvmScope scopeActivity = compensationHandler.getParent();
ExecutionEntity scopeExecution = ScopeUtil.findScopeExecutionForScope(executionEntity, scopeActivity);
CompensateEventSubscriptionEntity compensateEventSubscriptionEntity = CompensateEventSubscriptionEntity.createAndInsert(scopeExecution);
compensateEventSubscriptionEntity.setActivity(compensationHandler);
}
protected boolean hasLoopCharacteristics() {
return hasMultiInstanceCharacteristics();
}
protected boolean hasMultiInstanceCharacteristics() {
return multiInstanceActivityBehavior != null;
}
public MultiInstanceActivityBehavior getMultiInstanceActivityBehavior() {
return multiInstanceActivityBehavior;
}
public void setMultiInstanceActivityBehavior(MultiInstanceActivityBehavior multiInstanceActivityBehavior) {
this.multiInstanceActivityBehavior = multiInstanceActivityBehavior;
}
@Override
public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception {
if ("compensationDone".equals(signalName)) {
signalCompensationDone(execution, signalData);
} else {
super.signal(execution, signalName, signalData);
|
}
}
protected void signalCompensationDone(ActivityExecution execution, Object signalData) {
// default behavior is to join compensating executions and propagate the signal if all executions
// have compensated
// join compensating executions
if (execution.getExecutions().isEmpty()) {
if (execution.getParent() != null) {
ActivityExecution parent = execution.getParent();
((InterpretableExecution) execution).remove();
((InterpretableExecution) parent).signal("compensationDone", signalData);
}
} else {
((ExecutionEntity) execution).forceUpdate();
}
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\AbstractBpmnActivityBehavior.java
| 1
|
请完成以下Java代码
|
public Timestamp getDateDoc ()
{
return (Timestamp)get_Value(COLUMNNAME_DateDoc);
}
/** Set Period No.
@param PeriodNo
Unique Period Number
*/
public void setPeriodNo (int PeriodNo)
{
set_Value (COLUMNNAME_PeriodNo, Integer.valueOf(PeriodNo));
}
/** Get Period No.
@return Unique Period Number
*/
public int getPeriodNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PeriodNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
|
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Build.java
| 1
|
请完成以下Java代码
|
public IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration() {
return identityLinkServiceConfiguration;
}
public AppEngineConfiguration setIdentityLinkServiceConfiguration(IdentityLinkServiceConfiguration identityLinkServiceConfiguration) {
this.identityLinkServiceConfiguration = identityLinkServiceConfiguration;
return this;
}
public VariableServiceConfiguration getVariableServiceConfiguration() {
return variableServiceConfiguration;
}
public AppEngineConfiguration setVariableServiceConfiguration(VariableServiceConfiguration variableServiceConfiguration) {
this.variableServiceConfiguration = variableServiceConfiguration;
return this;
}
public boolean isSerializableVariableTypeTrackDeserializedObjects() {
return serializableVariableTypeTrackDeserializedObjects;
}
public AppEngineConfiguration setSerializableVariableTypeTrackDeserializedObjects(boolean serializableVariableTypeTrackDeserializedObjects) {
this.serializableVariableTypeTrackDeserializedObjects = serializableVariableTypeTrackDeserializedObjects;
return this;
}
public boolean isJsonVariableTypeTrackObjects() {
return jsonVariableTypeTrackObjects;
}
public AppEngineConfiguration setJsonVariableTypeTrackObjects(boolean jsonVariableTypeTrackObjects) {
this.jsonVariableTypeTrackObjects = jsonVariableTypeTrackObjects;
return this;
}
@Override
public VariableJsonMapper getVariableJsonMapper() {
return variableJsonMapper;
}
@Override
public AppEngineConfiguration setVariableJsonMapper(VariableJsonMapper variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
return this;
}
public boolean isDisableIdmEngine() {
|
return disableIdmEngine;
}
public AppEngineConfiguration setDisableIdmEngine(boolean disableIdmEngine) {
this.disableIdmEngine = disableIdmEngine;
return this;
}
public boolean isDisableEventRegistry() {
return disableEventRegistry;
}
public AppEngineConfiguration setDisableEventRegistry(boolean disableEventRegistry) {
this.disableEventRegistry = disableEventRegistry;
return this;
}
public BusinessCalendarManager getBusinessCalendarManager() {
return businessCalendarManager;
}
public AppEngineConfiguration setBusinessCalendarManager(BusinessCalendarManager businessCalendarManager) {
this.businessCalendarManager = businessCalendarManager;
return this;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\AppEngineConfiguration.java
| 1
|
请完成以下Spring Boot application配置
|
## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
## Mybatis
|
配置
mybatis.typeAliasesPackage=org.spring.springboot.domain
mybatis.mapperLocations=classpath:mapper/*.xml
|
repos\springboot-learning-example-master\springboot-mybatis\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
default Stream<T> stream() throws DBException
{
return list().stream();
}
default Stream<T> iterateAndStream() throws DBException
{
final Iterator<T> iterator = iterate(getModelClass());
final boolean parallel = false;
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), parallel);
}
default <ID extends RepoIdAware> Stream<ID> iterateAndStreamIds(@NonNull final IntFunction<ID> idMapper) throws DBException
{
final Iterator<ID> iterator = iterateIds(idMapper);
|
final boolean parallel = false;
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), parallel);
}
/**
* Return a stream of all records that match the query criteria.
*
* @param clazz all resulting models will be converted to this interface
* @return Stream
*/
default <ET extends T> Stream<ET> stream(final Class<ET> clazz) throws DBException
{
return list(clazz).stream();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\IQuery.java
| 1
|
请完成以下Java代码
|
protected DecisionRequirementsDefinitionEntity findDeployedDrdForResource(DeploymentEntity deployment, String resourceName) {
List<DecisionRequirementsDefinitionEntity> deployedDrds = deployment.getDeployedArtifacts(DecisionRequirementsDefinitionEntity.class);
if (deployedDrds != null) {
for (DecisionRequirementsDefinitionEntity deployedDrd : deployedDrds) {
if (deployedDrd.getResourceName().equals(resourceName)) {
return deployedDrd;
}
}
}
return null;
}
@Override
protected DecisionDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return getDecisionDefinitionManager().findDecisionDefinitionByDeploymentAndKey(deploymentId, definitionKey);
}
@Override
protected DecisionDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return getDecisionDefinitionManager().findLatestDecisionDefinitionByKeyAndTenantId(definitionKey, tenantId);
}
@Override
protected void persistDefinition(DecisionDefinitionEntity definition) {
getDecisionDefinitionManager().insertDecisionDefinition(definition);
}
@Override
protected void addDefinitionToDeploymentCache(DeploymentCache deploymentCache, DecisionDefinitionEntity definition) {
|
deploymentCache.addDecisionDefinition(definition);
}
// context ///////////////////////////////////////////////////////////////////////////////////////////
protected DecisionDefinitionManager getDecisionDefinitionManager() {
return getCommandContext().getDecisionDefinitionManager();
}
// getters/setters ///////////////////////////////////////////////////////////////////////////////////
public DmnTransformer getTransformer() {
return transformer;
}
public void setTransformer(DmnTransformer transformer) {
this.transformer = transformer;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\deployer\DecisionDefinitionDeployer.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.