instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public String getStartUserId() {
return startUserId;
}
public void setStartUserId(String startUserId) {
this.startUserId = startUserId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public void setSuperProcessInstanceId(String superProcessInstanceId) {
this.superProcessInstanceId = superProcessInstanceId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public void setSuperCaseInstanceId(String superCaseInstanceId) {
this.superCaseInstanceId = superCaseInstanceId;
}
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getState() {
return state; | }
public void setState(String state) {
this.state = state;
}
public String getRestartedProcessInstanceId() {
return restartedProcessInstanceId;
}
public void setRestartedProcessInstanceId(String restartedProcessInstanceId) {
this.restartedProcessInstanceId = restartedProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[businessKey=" + businessKey
+ ", startUserId=" + startUserId
+ ", superProcessInstanceId=" + superProcessInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", superCaseInstanceId=" + superCaseInstanceId
+ ", deleteReason=" + deleteReason
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime
+ ", endTime=" + endTime
+ ", removalTime=" + removalTime
+ ", endActivityId=" + endActivityId
+ ", startActivityId=" + startActivityId
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", tenantId=" + tenantId
+ ", restartedProcessInstanceId=" + restartedProcessInstanceId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricProcessInstanceEventEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PPOrderLineCandidateId implements RepoIdAware
{
int repoId;
@JsonCreator
public static PPOrderLineCandidateId ofRepoId(final int repoId)
{
return new PPOrderLineCandidateId(repoId);
}
@Nullable
public static PPOrderLineCandidateId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new PPOrderLineCandidateId(repoId) : null;
} | private PPOrderLineCandidateId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_OrderLine_Candidate_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final PPOrderLineCandidateId id1, @Nullable final PPOrderLineCandidateId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\model\PPOrderLineCandidateId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private String getAPIPath(final @NonNull ReportContext reportContext)
{
final String path = StringUtils.trimBlankToNull(reportContext.getJSONPath());
if (path == null || "-".equals(path))
{
throw new AdempiereException(MSG_URLNotValid)
.appendParametersToMessage()
.setParameter("reason", "JSONPath is not set");
}
final IStringExpression pathExpression = expressionFactory.compile(path, IStringExpression.class);
final Evaluatee evalCtx = createEvalCtx(reportContext);
return pathExpression.evaluate(evalCtx, OnVariableNotFound.Fail);
}
@Nullable
private String retrieveJsonSqlValue(@NonNull final ReportContext reportContext)
{
//
// Get SQL
final String sql = StringUtils.trimBlankToNull(reportContext.getSQLStatement());
if (sql == null)
{
return null;
}
// Parse the SQL Statement
final IStringExpression sqlExpression = expressionFactory.compile(sql, IStringExpression.class);
final Evaluatee evalCtx = createEvalCtx(reportContext);
final String sqlFinal = sqlExpression.evaluate(evalCtx, OnVariableNotFound.Fail);
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited, sqlFinal);
}
private static Evaluatee createEvalCtx(@NonNull final ReportContext reportContext) | {
final ArrayList<Evaluatee> contexts = new ArrayList<>();
//
// 1: Add process parameters
contexts.add(Evaluatees.ofRangeAwareParams(new ProcessParams(reportContext.getProcessInfoParameters())));
//
// 2: underlying record
final String recordTableName = reportContext.getTableNameOrNull();
final int recordId = reportContext.getRecord_ID();
if (recordTableName != null && recordId > 0)
{
final TableRecordReference recordRef = TableRecordReference.of(recordTableName, recordId);
final Evaluatee evalCtx = Evaluatees.ofTableRecordReference(recordRef);
if (evalCtx != null)
{
contexts.add(evalCtx);
}
}
//
// 3: global context
contexts.add(Evaluatees.ofCtx(Env.getCtx()));
return Evaluatees.compose(contexts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\RemoteRestAPIDataSource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SendGridProperties {
/**
* SendGrid API key.
*/
private @Nullable String apiKey;
/**
* Proxy configuration.
*/
private @Nullable Proxy proxy;
public @Nullable String getApiKey() {
return this.apiKey;
}
public void setApiKey(@Nullable String apiKey) {
this.apiKey = apiKey;
}
public @Nullable Proxy getProxy() {
return this.proxy;
}
public void setProxy(@Nullable Proxy proxy) {
this.proxy = proxy;
}
public static class Proxy {
/**
* SendGrid proxy host. | */
private @Nullable String host;
/**
* SendGrid proxy port.
*/
private @Nullable Integer port;
public @Nullable String getHost() {
return this.host;
}
public void setHost(@Nullable String host) {
this.host = host;
}
public @Nullable Integer getPort() {
return this.port;
}
public void setPort(@Nullable Integer port) {
this.port = port;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-sendgrid\src\main\java\org\springframework\boot\sendgrid\autoconfigure\SendGridProperties.java | 2 |
请完成以下Java代码 | public Set<String> getRegisteredRedirectUri() {
return stringToSet(redirectUrl);
}
/**
* 这里需要提一下
* 个人觉得这里应该是客户端所有的权限
* 但是已经有 scope 的存在可以很好的对客户端的权限进行认证了
* 那么在 oauth2 的四个角色中,这里就有可能是资源服务器的权限
* 但是一般资源服务器都有自己的权限管理机制,比如拿到用户信息后做 RBAC
* 所以在 spring security 的默认实现中直接给的是空的一个集合
* 这里我们也给他一个空的把
*
* @return GrantedAuthority
*/
@Override
public Collection<GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
/**
* 判断是否自动授权
*
* @param scope scope
* @return 结果
*/
@Override
public boolean isAutoApprove(String scope) {
if (autoApproveScopes == null || autoApproveScopes.isEmpty()) {
return false; | }
Set<String> authorizationSet = stringToSet(authorizations);
for (String auto : authorizationSet) {
if ("true".equalsIgnoreCase(auto) || scope.matches(auto)) {
return true;
}
}
return false;
}
/**
* additional information 是 spring security 的保留字段
* 暂时用不到,直接给个空的即可
*
* @return map
*/
@Override
public Map<String, Object> getAdditionalInformation() {
return Collections.emptyMap();
}
private Set<String> stringToSet(String s) {
return Arrays.stream(s.split(",")).collect(Collectors.toSet());
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\entity\SysClientDetails.java | 1 |
请完成以下Java代码 | public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public Book(Long id, String name, String writer, String introduction) {
this.id = id;
this.name = name;
this.writer = writer; | this.introduction = introduction;
}
public Book(Long id, String name) {
this.id = id;
this.name = name;
}
public Book(String name) {
this.name = name;
}
public Book() {
}
} | repos\springboot-learning-example-master\chapter-3-spring-boot-web\src\main\java\demo\springboot\domain\Book.java | 1 |
请完成以下Java代码 | public AttributeListValue changeAttributeValue(@NonNull final AttributeListValueChangeRequest request)
{
final I_M_AttributeValue record = loadOutOfTrx(request.getId(), I_M_AttributeValue.class);
if (request.getActive() != null)
{
record.setIsActive(request.getActive());
}
if (request.getValue() != null)
{
record.setValue(request.getValue().orElse(null));
}
if (request.getName() != null)
{
record.setName(request.getName());
}
if (request.getDescription() != null)
{
record.setDescription(request.getDescription().orElse(null));
}
if (request.getAvailableForTrx() != null)
{
record.setAvailableTrx(request.getAvailableForTrx().getCode());
}
saveRecord(record);
return toAttributeListValue(record);
}
@Override
public void deleteAttributeValueByCode(@NonNull final AttributeId attributeId, @Nullable final String value)
{
queryBL.createQueryBuilder(I_M_AttributeValue.class)
.addEqualsFilter(I_M_AttributeValue.COLUMN_M_Attribute_ID, attributeId)
.addEqualsFilter(I_M_AttributeValue.COLUMNNAME_Value, value)
.create()
.delete();
}
@Override
public List<Attribute> retrieveAttributes(final AttributeSetId attributeSetId, final boolean isInstanceAttribute)
{
return getAttributesByAttributeSetId(attributeSetId)
.stream()
.filter(attribute -> attribute.isInstanceAttribute() == isInstanceAttribute)
.collect(ImmutableList.toImmutableList());
}
@Override
public boolean containsAttribute(@NonNull final AttributeSetId attributeSetId, @NonNull final AttributeId attributeId)
{
return getAttributeSetDescriptorById(attributeSetId).contains(attributeId);
}
@Override
@Nullable
public I_M_Attribute retrieveAttribute(final AttributeSetId attributeSetId, final AttributeId attributeId)
{
if (!containsAttribute(attributeSetId, attributeId))
{
return null;
}
return getAttributeRecordById(attributeId); | }
private static final class AttributeListValueMap
{
public static AttributeListValueMap ofList(final List<AttributeListValue> list)
{
if (list.isEmpty())
{
return EMPTY;
}
return new AttributeListValueMap(list);
}
private static final AttributeListValueMap EMPTY = new AttributeListValueMap();
private final ImmutableMap<String, AttributeListValue> map;
private AttributeListValueMap()
{
map = ImmutableMap.of();
}
private AttributeListValueMap(@NonNull final List<AttributeListValue> list)
{
map = Maps.uniqueIndex(list, AttributeListValue::getValue);
}
public List<AttributeListValue> toList()
{
return ImmutableList.copyOf(map.values());
}
@Nullable
public AttributeListValue getByIdOrNull(@NonNull final AttributeValueId id)
{
return map.values()
.stream()
.filter(av -> AttributeValueId.equals(av.getId(), id))
.findFirst()
.orElse(null);
}
public AttributeListValue getByValueOrNull(final String value)
{
return map.get(value);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeDAO.java | 1 |
请完成以下Java代码 | public MRPQueryBuilder setM_Product_ID(final Integer productId)
{
this._productId = productId;
return this;
}
private int getM_Product_ID_ToUse()
{
if (_productId != null)
{
return _productId;
}
return -1;
}
@Override
public MRPQueryBuilder setTypeMRP(final String typeMRP)
{
this._typeMRP = typeMRP;
return this;
}
public String getTypeMRP()
{
return _typeMRP;
}
@Nullable
public Date getDatePromisedMax()
{
return this._datePromisedMax;
}
@Nullable
public MRPFirmType getMRPFirmType()
{
return this._mrpFirmType;
}
public boolean isQtyNotZero()
{
return false;
}
@Nullable
public Boolean getMRPAvailable()
{
return _mrpAvailable;
}
public boolean isOnlyActiveRecords()
{
return _onlyActiveRecords; | }
@Override
public MRPQueryBuilder setOnlyActiveRecords(final boolean onlyActiveRecords)
{
this._onlyActiveRecords = onlyActiveRecords;
return this;
}
@Override
public MRPQueryBuilder setOrderType(final String orderType)
{
this._orderTypes.clear();
if (orderType != null)
{
this._orderTypes.add(orderType);
}
return this;
}
private Set<String> getOrderTypes()
{
return this._orderTypes;
}
@Override
public MRPQueryBuilder setReferencedModel(final Object referencedModel)
{
this._referencedModel = referencedModel;
return this;
}
public Object getReferencedModel()
{
return this._referencedModel;
}
@Override
public void setPP_Order_BOMLine_Null()
{
this._ppOrderBOMLine_Null = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPQueryBuilder.java | 1 |
请完成以下Java代码 | public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setIsStdUserWorkflow (final boolean IsStdUserWorkflow)
{
set_Value (COLUMNNAME_IsStdUserWorkflow, IsStdUserWorkflow);
}
@Override
public boolean isStdUserWorkflow()
{
return get_ValueAsBoolean(COLUMNNAME_IsStdUserWorkflow);
}
@Override | public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTransitionCode (final java.lang.String TransitionCode)
{
set_Value (COLUMNNAME_TransitionCode, TransitionCode);
}
@Override
public java.lang.String getTransitionCode()
{
return get_ValueAsString(COLUMNNAME_TransitionCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_NodeNext.java | 1 |
请完成以下Java代码 | public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} | public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\projection\model\Address.java | 1 |
请完成以下Java代码 | public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() { | return role;
}
public void setRole(String role) {
this.role = role;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\customlogouthandler\user\User.java | 1 |
请完成以下Java代码 | public String getColumnName()
{
return columnName;
}
@Override
public Class<?> getColumnClass()
{
return columnClass;
}
void setColumnClass(final Class<?> columnClass)
{
Check.assumeNotNull(columnClass, "columnClass not null");
this.columnClass = columnClass;
}
@Override
public String getDisplayName()
{
return displayName;
}
public void setDisplayName(final String displayName)
{
this.displayName = displayName;
}
@Override
public boolean isEditable()
{
return editable;
}
public void setEditable(final boolean editable)
{
if (this.editable == editable)
{
return;
}
final boolean editableOld = this.editable;
this.editable = editable;
pcs.firePropertyChange(PROPERTY_Editable, editableOld, editable);
}
public boolean isVisible()
{
return visible;
}
public void setVisible(boolean visible)
{
if (this.visible == visible)
{
return;
}
final boolean visibleOld = this.visible;
this.visible = visible;
pcs.firePropertyChange(PROPERTY_Visible, visibleOld, visible);
}
@Override
public Method getReadMethod()
{
return readMethod;
}
@Override
public Method getWriteMethod()
{
return writeMethod;
}
void setWriteMethod(final Method writeMethod)
{
this.writeMethod = writeMethod;
}
void setSeqNo(final int seqNo)
{
this.seqNo = seqNo;
}
@Override | public int getSeqNo()
{
return seqNo;
}
@Override
public String getLookupTableName()
{
return lookupTableName;
}
void setLookupTableName(final String lookupTableName)
{
this.lookupTableName = lookupTableName;
}
@Override
public String getLookupColumnName()
{
return lookupColumnName;
}
void setLookupColumnName(final String lookupColumnName)
{
this.lookupColumnName = lookupColumnName;
}
@Override
public String getPrototypeValue()
{
return prototypeValue;
}
void setPrototypeValue(final String prototypeValue)
{
this.prototypeValue = prototypeValue;
}
public int getDisplayType(final int defaultDisplayType)
{
return displayType > 0 ? displayType : defaultDisplayType;
}
public int getDisplayType()
{
return displayType;
}
void setDisplayType(int displayType)
{
this.displayType = displayType;
}
public boolean isSelectionColumn()
{
return selectionColumn;
}
public void setSelectionColumn(boolean selectionColumn)
{
this.selectionColumn = selectionColumn;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableColumnInfo.java | 1 |
请完成以下Java代码 | class GImage extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 4991225210651641722L;
/**
* Graphic Image
*/
public GImage()
{
super();
} // GImage
/** The Image */
private Image m_image = null;
/**
* Set Image
*
* @param image image
*/
public void setImage(final Image image)
{
m_image = image;
if (m_image == null)
{
return;
}
MediaTracker mt = new MediaTracker(this);
mt.addImage(m_image, 0);
try
{
mt.waitForID(0);
}
catch (Exception e)
{
}
Dimension dim = new Dimension(m_image.getWidth(this), m_image.getHeight(this));
this.setPreferredSize(dim);
} // setImage | /**
* Paint
*
* @param g graphics
*/
@Override
public void paint(final Graphics g)
{
Insets in = getInsets();
if (m_image != null)
{
g.drawImage(m_image, in.left, in.top, this);
}
} // paint
/**
* Update
*
* @param g graphics
*/
@Override
public void update(final Graphics g)
{
paint(g);
} // update
} // GImage
} // Attachment | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\Attachment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class S_ResourceType
{
static final S_ResourceType INSTANCE = new S_ResourceType();
private S_ResourceType()
{
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_S_ResourceType.COLUMNNAME_IsTimeSlot,
I_S_ResourceType.COLUMNNAME_TimeSlotStart,
I_S_ResourceType.COLUMNNAME_TimeSlotEnd
})
public void validateStartEndDate(final I_S_ResourceType resourceType)
{
if (!resourceType.isTimeSlot())
{
return; // nothing to do
}
final Timestamp start = resourceType.getTimeSlotStart();
if (start == null)
{
throw new FillMandatoryException(I_S_ResourceType.COLUMNNAME_TimeSlotStart);
} | final Timestamp end = resourceType.getTimeSlotEnd();
if (end == null)
{
throw new FillMandatoryException(I_S_ResourceType.COLUMNNAME_TimeSlotEnd);
}
if (start.compareTo(end) >= 0)
{
throw new AdempiereException("@TimeSlotStart@ > @TimeSlotEnd@");
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE })
public void updateProducts(final I_S_ResourceType resourceType)
{
Services.get(IResourceDAO.class).onResourceTypeChanged(resourceType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\interceptor\S_ResourceType.java | 2 |
请完成以下Java代码 | public static String validateRoutingNo (String routingNo)
{
int length = checkNumeric(routingNo).length();
// US - length 9
// Germany - length 8
// Japan - 7
// CH - 5
// Issue: Bank account country
if (length > 0)
return "";
return "PaymentBankRoutingNotValid";
} // validateBankRoutingNo
/**
* Validate Account No
* @param AccountNo AccountNo
* @return "" or Error AD_Message
*/
public static String validateAccountNo (String AccountNo)
{
int length = checkNumeric(AccountNo).length();
if (length > 0)
return "";
return "PaymentBankAccountNotValid";
} // validateBankAccountNo
/**
* Validate Check No
* @param CheckNo CheckNo
* @return "" or Error AD_Message
*/
public static String validateCheckNo (String CheckNo)
{
int length = checkNumeric(CheckNo).length(); | if (length > 0)
return "";
return "PaymentBankCheckNotValid";
} // validateBankCheckNo
/**
* Check Numeric
* @param data input
* @return the digits of the data - ignore the rest
*/
public static String checkNumeric (String data)
{
if (data == null || data.length() == 0)
return "";
// Remove all non Digits
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length(); i++)
{
if (Character.isDigit(data.charAt(i)))
sb.append(data.charAt(i));
}
return sb.toString();
} // checkNumeric
} // MPaymentValidate | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MPaymentValidate.java | 1 |
请完成以下Java代码 | public class PostDeployInvocationStep extends DeploymentOperationStep {
private final static ContainerIntegrationLogger LOG = ProcessEngineLogger.CONTAINER_INTEGRATION_LOGGER;
private static final String CALLBACK_NAME = "@PostDeploy";
public String getName() {
return "Invoking @PostDeploy";
}
public void performOperationStep(DeploymentOperation operationContext) {
final AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION);
final String paName = processApplication.getName();
Class<? extends AbstractProcessApplication> paClass = processApplication.getClass();
Method postDeployMethod = InjectionUtil.detectAnnotatedMethod(paClass, PostDeploy.class);
if(postDeployMethod == null) {
LOG.debugPaLifecycleMethodNotFound(CALLBACK_NAME, paName);
return;
}
LOG.debugFoundPaLifecycleCallbackMethod(CALLBACK_NAME, paName);
// resolve injections
Object[] injections = InjectionUtil.resolveInjections(operationContext, postDeployMethod); | try {
// perform the actual invocation
postDeployMethod.invoke(processApplication, injections);
}
catch (IllegalArgumentException e) {
throw LOG.exceptionWhileInvokingPaLifecycleCallback(CALLBACK_NAME, paName, e);
}
catch (IllegalAccessException e) {
throw LOG.exceptionWhileInvokingPaLifecycleCallback(CALLBACK_NAME, paName, e);
}
catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if(cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
else {
throw LOG.exceptionWhileInvokingPaLifecycleCallback(CALLBACK_NAME, paName, e);
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\PostDeployInvocationStep.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class ConvertTask implements Runnable {
private final Logger logger = LoggerFactory.getLogger(ConvertTask.class);
private final FilePreviewFactory previewFactory;
private final CacheService cacheService;
private final FileHandlerService fileHandlerService;
public ConvertTask(FilePreviewFactory previewFactory,
CacheService cacheService,
FileHandlerService fileHandlerService) {
this.previewFactory = previewFactory;
this.cacheService = cacheService;
this.fileHandlerService = fileHandlerService;
}
@Override
public void run() {
while (true) {
String url = null;
try {
url = cacheService.takeQueueTask();
if (url != null) {
FileAttribute fileAttribute = fileHandlerService.getFileAttribute(url, null);
FileType fileType = fileAttribute.getType();
logger.info("正在处理预览转换任务,url:{},预览类型:{}", url, fileType); | if (isNeedConvert(fileType)) {
FilePreview filePreview = previewFactory.get(fileAttribute);
filePreview.filePreviewHandle(url, new ExtendedModelMap(), fileAttribute);
} else {
logger.info("预览类型无需处理,url:{},预览类型:{}", url, fileType);
}
}
} catch (Exception e) {
try {
TimeUnit.SECONDS.sleep(10);
} catch (Exception ex) {
Thread.currentThread().interrupt();
logger.error("Failed to sleep after exception", ex);
}
logger.info("处理预览转换任务异常,url:{}", url, e);
}
}
}
public boolean isNeedConvert(FileType fileType) {
return fileType.equals(FileType.COMPRESS) || fileType.equals(FileType.OFFICE) || fileType.equals(FileType.CAD);
}
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\FileConvertQueueTask.java | 2 |
请完成以下Java代码 | public void addActionListener(ActionListener l)
{
if (l != null)
listenerList.add(ActionListener.class, l);
} // addActionListener
/**
* Removes an <code>ActionListener</code> from the indicator.
* @param l the listener to be removed
*/
public void removeActionListener(ActionListener l)
{
if (l != null)
listenerList.remove(ActionListener.class, l);
} // removeActionListener
/**
* Returns an array of all the <code>ActionListener</code>s added
* to this indicator with addActionListener().
*
* @return all of the <code>ActionListener</code>s added or an empty
* array if no listeners have been added
*/
public ActionListener[] getActionListeners()
{
return (listenerList.getListeners(ActionListener.class));
} // getActionListeners
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>event</code>
* parameter.
*
* @param event the <code>ActionEvent</code> object
* @see EventListenerList
*/
protected void fireActionPerformed(MouseEvent event)
{
// Guaranteed to return a non-null array
ActionListener[] listeners = getActionListeners();
ActionEvent e = null;
// Process the listeners first to last
for (int i = 0; i < listeners.length; i++)
{
// Lazily create the event:
if (e == null)
e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
"pi", event.getWhen(), event.getModifiers());
listeners[i].actionPerformed(e);
}
} // fireActionPerformed
/**************************************************************************
* Mouse Clicked
* @param e mouse event
*/
@Override
public void mouseClicked (MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() > 1)
fireActionPerformed(e);
if (SwingUtilities.isRightMouseButton(e))
popupMenu.show((Component)e.getSource(), e.getX(), e.getY());
} // mouseClicked
@Override
public void mousePressed (MouseEvent e)
{
}
@Override | public void mouseReleased (MouseEvent e)
{
}
@Override
public void mouseEntered (MouseEvent e)
{
}
@Override
public void mouseExited (MouseEvent e)
{
}
/**
* Action Listener.
* Update Display
* @param e event
*/
@Override
public void actionPerformed (ActionEvent e)
{
if (e.getSource() == mRefresh)
{
m_goal.updateGoal(true);
updateDisplay();
//
Container parent = getParent();
if (parent != null)
parent.invalidate();
invalidate();
if (parent != null)
parent.repaint();
else
repaint();
}
} // actionPerformed
} // PerformanceIndicator | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\PerformanceIndicator.java | 1 |
请完成以下Java代码 | public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event)
{
final DocumentPostRequest request = eventConverter.extractDocumentPostRequest(event);
try (final IAutoCloseable ignored = switchCtx(request);
final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(request.getRecord());
final MDCCloseable ignored2 = MDC.putCloseable("eventHandler.className", handler.getClass().getName()))
{
eventLogUserService.invokeHandlerAndLog(InvokeHandlerAndLogRequest.builder()
.handlerClass(handler.getClass())
.invokaction(() -> handleRequest(request))
.build());
}
}
private void handleRequest(@NonNull final DocumentPostRequest request)
{
handler.handleRequest(request); | }
private IAutoCloseable switchCtx(@NonNull final DocumentPostRequest request)
{
final Properties ctx = createCtx(request);
return Env.switchContext(ctx);
}
private Properties createCtx(@NonNull final DocumentPostRequest request)
{
final Properties ctx = Env.newTemporaryCtx();
Env.setClientId(ctx, request.getClientId());
return ctx;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\DocumentPostingBusService.java | 1 |
请完成以下Java代码 | public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public boolean isSuspended() {
return suspended;
}
public String getFormKey() {
return formKey;
}
public CamundaFormRef getCamundaFormRef() {
return camundaFormRef;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTaskState() {
return taskState;
}
public void setTaskState(String taskState) {
this.taskState = taskState;
}
public static TaskDto fromEntity(Task task) {
TaskDto dto = new TaskDto();
dto.id = task.getId();
dto.name = task.getName();
dto.assignee = task.getAssignee();
dto.created = task.getCreateTime();
dto.lastUpdated = task.getLastUpdated();
dto.due = task.getDueDate();
dto.followUp = task.getFollowUpDate();
if (task.getDelegationState() != null) {
dto.delegationState = task.getDelegationState().toString();
}
dto.description = task.getDescription();
dto.executionId = task.getExecutionId();
dto.owner = task.getOwner();
dto.parentTaskId = task.getParentTaskId();
dto.priority = task.getPriority();
dto.processDefinitionId = task.getProcessDefinitionId();
dto.processInstanceId = task.getProcessInstanceId();
dto.taskDefinitionKey = task.getTaskDefinitionKey(); | dto.caseDefinitionId = task.getCaseDefinitionId();
dto.caseExecutionId = task.getCaseExecutionId();
dto.caseInstanceId = task.getCaseInstanceId();
dto.suspended = task.isSuspended();
dto.tenantId = task.getTenantId();
dto.taskState = task.getTaskState();
try {
dto.formKey = task.getFormKey();
dto.camundaFormRef = task.getCamundaFormRef();
}
catch (BadUserRequestException e) {
// ignore (initializeFormKeys was not called)
}
return dto;
}
public void updateTask(Task task) {
task.setName(getName());
task.setDescription(getDescription());
task.setPriority(getPriority());
task.setAssignee(getAssignee());
task.setOwner(getOwner());
DelegationState state = null;
if (getDelegationState() != null) {
DelegationStateConverter converter = new DelegationStateConverter();
state = converter.convertQueryParameterToType(getDelegationState());
}
task.setDelegationState(state);
task.setDueDate(getDue());
task.setFollowUpDate(getFollowUp());
task.setParentTaskId(getParentTaskId());
task.setCaseInstanceId(getCaseInstanceId());
task.setTenantId(getTenantId());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\TaskDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BPGroupService
{
private final BPGroupRepository bpGroupRepository;
/**
* If different threads try to create the same group concurrently, then return just the first created group to everyone.
*/
public BPGroupId getOrCreateBPGroup(
@NonNull final OrgId orgId,
@NonNull final String groupName)
{
Check.assumeNotEmpty(groupName, "groupName is not empty");
final Optional<BPGroup> optionalBPGroup = bpGroupRepository.getByNameAndOrgId(groupName, orgId);
final BPGroup bpGroup;
if (optionalBPGroup.isPresent())
{
bpGroup = optionalBPGroup.get();
bpGroup.setName(groupName);
}
else
{
bpGroup = BPGroup.builder()
.orgId(orgId) | .value(groupName)
.name(groupName)
.build();
}
try
{
return bpGroupRepository.save(bpGroup);
}
catch (final DBUniqueConstraintException e)
{
// meanwhile a group with that name was created, so we can return the existing one
return bpGroupRepository.getByNameAndOrgId(bpGroup.getName(), bpGroup.getOrgId())
.map(BPGroup::getId)
.orElseThrow(() -> e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPGroupService.java | 2 |
请完成以下Java代码 | public DmnDecision getDecisionTable() {
return getDecision();
}
public DmnDecision getDecision() {
return decision;
}
public void setDecisionTable(DmnDecision decision) {
this.decision = decision;
}
public List<DmnEvaluatedInput> getInputs() {
return inputs;
}
public void setInputs(List<DmnEvaluatedInput> inputs) {
this.inputs = inputs;
}
public List<DmnEvaluatedDecisionRule> getMatchingRules() {
return matchingRules;
}
public void setMatchingRules(List<DmnEvaluatedDecisionRule> matchingRules) {
this.matchingRules = matchingRules;
}
public String getCollectResultName() {
return collectResultName;
}
public void setCollectResultName(String collectResultName) {
this.collectResultName = collectResultName;
} | public TypedValue getCollectResultValue() {
return collectResultValue;
}
public void setCollectResultValue(TypedValue collectResultValue) {
this.collectResultValue = collectResultValue;
}
public long getExecutedDecisionElements() {
return executedDecisionElements;
}
public void setExecutedDecisionElements(long executedDecisionElements) {
this.executedDecisionElements = executedDecisionElements;
}
@Override
public String toString() {
return "DmnDecisionTableEvaluationEventImpl{" +
" key="+ decision.getKey() +
", name="+ decision.getName() +
", decisionLogic=" + decision.getDecisionLogic() +
", inputs=" + inputs +
", matchingRules=" + matchingRules +
", collectResultName='" + collectResultName + '\'' +
", collectResultValue=" + collectResultValue +
", executedDecisionElements=" + executedDecisionElements +
'}';
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnDecisionTableEvaluationEventImpl.java | 1 |
请完成以下Java代码 | public void setIsLandscape (boolean IsLandscape)
{
set_Value (COLUMNNAME_IsLandscape, Boolean.valueOf(IsLandscape));
}
/** Get Landscape.
@return Landscape orientation
*/
public boolean isLandscape ()
{
Object oo = get_Value(COLUMNNAME_IsLandscape);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Label Height.
@param LabelHeight
Height of the label
*/
public void setLabelHeight (int LabelHeight)
{
set_Value (COLUMNNAME_LabelHeight, Integer.valueOf(LabelHeight));
}
/** Get Label Height.
@return Height of the label
*/
public int getLabelHeight ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LabelHeight);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Label Width.
@param LabelWidth
Width of the Label
*/
public void setLabelWidth (int LabelWidth)
{
set_Value (COLUMNNAME_LabelWidth, Integer.valueOf(LabelWidth));
}
/** Get Label Width.
@return Width of the Label
*/
public int getLabelWidth ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LabelWidth);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{ | set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Printer Name.
@param PrinterName
Name of the Printer
*/
public void setPrinterName (String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
/** Get Printer Name.
@return Name of the Printer
*/
public String getPrinterName ()
{
return (String)get_Value(COLUMNNAME_PrinterName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OAuth2AuthenticationConfiguration extends ResourceServerConfigurerAdapter {
private final OAuth2Properties oAuth2Properties;
private final OAuth2TokenEndpointClient tokenEndpointClient;
private final TokenStore tokenStore;
public OAuth2AuthenticationConfiguration(OAuth2Properties oAuth2Properties, OAuth2TokenEndpointClient tokenEndpointClient, TokenStore tokenStore) {
this.oAuth2Properties = oAuth2Properties;
this.tokenEndpointClient = tokenEndpointClient;
this.tokenStore = tokenStore;
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/auth/login").permitAll()
.antMatchers("/auth/logout").authenticated()
.and()
.apply(refreshTokenSecurityConfigurerAdapter());
}
/**
* A SecurityConfigurerAdapter to install a servlet filter that refreshes OAuth2 tokens.
*/
private RefreshTokenFilterConfigurer refreshTokenSecurityConfigurerAdapter() {
return new RefreshTokenFilterConfigurer(uaaAuthenticationService(), tokenStore);
} | @Bean
public OAuth2CookieHelper cookieHelper() {
return new OAuth2CookieHelper(oAuth2Properties);
}
@Bean
public OAuth2AuthenticationService uaaAuthenticationService() {
return new OAuth2AuthenticationService(tokenEndpointClient, cookieHelper());
}
/**
* Configure the ResourceServer security by installing a new TokenExtractor.
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenExtractor(tokenExtractor());
}
/**
* The new TokenExtractor can extract tokens from Cookies and Authorization headers.
*
* @return the CookieTokenExtractor bean.
*/
@Bean
public TokenExtractor tokenExtractor() {
return new CookieTokenExtractor();
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\oauth2\OAuth2AuthenticationConfiguration.java | 2 |
请完成以下Java代码 | public List<ChangePlanItemIdMapping> getChangePlanItemIdMappings() {
return changePlanItemIdMappings;
}
@Override
public List<ChangePlanItemIdWithDefinitionIdMapping> getChangePlanItemIdWithDefinitionIdMappings() {
return changePlanItemIdWithDefinitionIdMappings;
}
@Override
public List<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIdsMappings() {
return changePlanItemDefinitionWithNewTargetIdsMappings;
}
@Override
public String getPreUpgradeExpression() {
return preUpgradeExpression;
}
@Override
public String getPostUpgradeExpression() {
return postUpgradeExpression;
} | @Override
public Map<String, Map<String, Object>> getPlanItemLocalVariables() {
return this.planItemLocalVariables;
}
@Override
public Map<String, Object> getCaseInstanceVariables() {
return this.caseInstanceVariables;
}
@Override
public String asJsonString() {
return CaseInstanceMigrationDocumentConverter.convertToJsonString(this);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationDocumentImpl.java | 1 |
请完成以下Java代码 | public final class OAuth2AuthorizationRequestCustomizers {
private static final StringKeyGenerator DEFAULT_SECURE_KEY_GENERATOR = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
private OAuth2AuthorizationRequestCustomizers() {
}
/**
* Returns a {@code Consumer} to be provided the
* {@link OAuth2AuthorizationRequest.Builder} that adds the
* {@link PkceParameterNames#CODE_CHALLENGE code_challenge} and, usually,
* {@link PkceParameterNames#CODE_CHALLENGE_METHOD code_challenge_method} parameters
* to the OAuth 2.0 Authorization Request. The {@code code_verifier} is stored in
* {@link OAuth2AuthorizationRequest#getAttribute(String)} under the key
* {@link PkceParameterNames#CODE_VERIFIER code_verifier} for subsequent use in the
* OAuth 2.0 Access Token Request.
* @return a {@code Consumer} to be provided the
* {@link OAuth2AuthorizationRequest.Builder} that adds the PKCE parameters
* @see <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/rfc7636#section-1.1">1.1. Protocol Flow</a>
* @see <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/rfc7636#section-4.1">4.1. Client Creates a
* Code Verifier</a>
* @see <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/rfc7636#section-4.2">4.2. Client Creates the
* Code Challenge</a>
*/
public static Consumer<OAuth2AuthorizationRequest.Builder> withPkce() {
return OAuth2AuthorizationRequestCustomizers::applyPkce;
}
private static void applyPkce(OAuth2AuthorizationRequest.Builder builder) {
if (isPkceAlreadyApplied(builder)) {
return;
}
String codeVerifier = DEFAULT_SECURE_KEY_GENERATOR.generateKey();
builder.attributes((attrs) -> attrs.put(PkceParameterNames.CODE_VERIFIER, codeVerifier));
builder.additionalParameters((params) -> {
try {
String codeChallenge = createHash(codeVerifier); | params.put(PkceParameterNames.CODE_CHALLENGE, codeChallenge);
params.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
}
catch (NoSuchAlgorithmException ex) {
params.put(PkceParameterNames.CODE_CHALLENGE, codeVerifier);
}
});
}
private static boolean isPkceAlreadyApplied(OAuth2AuthorizationRequest.Builder builder) {
AtomicBoolean pkceApplied = new AtomicBoolean(false);
builder.additionalParameters((params) -> {
if (params.containsKey(PkceParameterNames.CODE_CHALLENGE)) {
pkceApplied.set(true);
}
});
return pkceApplied.get();
}
private static String createHash(String value) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestCustomizers.java | 1 |
请完成以下Java代码 | public class SensitiveSerialize extends JsonSerializer<String> implements ContextualSerializer {
private SensitiveEnum type;
@Override
public void serialize(String data, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
switch (type){
case ENCODE:
try {
jsonGenerator.writeString(AesEncryptUtil.encrypt(data));
} catch (Exception exception) {
log.error("数据加密错误", exception.getMessage());
jsonGenerator.writeString(data);
}
break;
case CHINESE_NAME:
jsonGenerator.writeString(SensitiveInfoUtil.chineseName(data));
break;
case ID_CARD:
jsonGenerator.writeString(SensitiveInfoUtil.idCardNum(data));
break;
case FIXED_PHONE:
jsonGenerator.writeString(SensitiveInfoUtil.fixedPhone(data));
break;
case MOBILE_PHONE:
jsonGenerator.writeString(SensitiveInfoUtil.mobilePhone(data));
break;
case ADDRESS:
jsonGenerator.writeString(SensitiveInfoUtil.address(data, 3));
break;
case EMAIL:
jsonGenerator.writeString(SensitiveInfoUtil.email(data));
break;
case BANK_CARD:
jsonGenerator.writeString(SensitiveInfoUtil.bankCard(data));
break;
case CNAPS_CODE: | jsonGenerator.writeString(SensitiveInfoUtil.cnapsCode(data));
break;
default:
jsonGenerator.writeString(data);
}
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
if (beanProperty != null) {
if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
Sensitive sensitive = beanProperty.getAnnotation(Sensitive.class);
if (sensitive == null) {
sensitive = beanProperty.getContextAnnotation(Sensitive.class);
}
if (sensitive != null) {
return new SensitiveSerialize(sensitive.type());
}
}
return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
}
return serializerProvider.findNullValueSerializer(null);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\desensitization\SensitiveSerialize.java | 1 |
请完成以下Java代码 | public boolean hasAttribute(String attribute)
{
return(getElementHashEntry().containsKey(attribute));
}
/** Return a list of the attributes associated with this element. */
public Enumeration<String> attributes()
{
return getElementHashEntry().keys();
}
/**
* Return the specified attribute.
* @param attribute The name of the attribute to fetch
*/
public String getAttribute(String attribute)
{
return (String)getElementHashEntry().get(attribute);
}
/**
This method overrides createStartTag() in Generic Element.
It provides a way to print out the attributes of an element.
*/
protected String createStartTag()
{
StringBuffer out = new StringBuffer();
out.append(getStartTagChar());
if(getBeginStartModifierDefined())
{
out.append(getBeginStartModifier());
}
out.append(getElementType());
Enumeration<String> en = getElementHashEntry().keys();
String value = null; // avoid creating a new string object on each pass through the loop
while (en.hasMoreElements())
{ | String attr = en.nextElement();
if(getAttributeFilterState())
{
value = getAttributeFilter().process(getElementHashEntry().get(attr).toString());
}
else
{
value = (String) getElementHashEntry().get(attr);
}
out.append(' ');
out.append(alterCase(attr));
if(!value.equalsIgnoreCase(NO_ATTRIBUTE_VALUE) && getAttributeQuote())
{
out.append(getAttributeEqualitySign());
out.append(getAttributeQuoteChar());
out.append(value);
out.append(getAttributeQuoteChar());
}
else if( !getAttributeQuote() )
{
out.append(getAttributeEqualitySign());
out.append(value);
}
}
if(getBeginEndModifierDefined())
{
out.append(getBeginEndModifier());
}
out.append(getEndTagChar());
return(out.toString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ElementAttributes.java | 1 |
请完成以下Java代码 | public static class Searcher extends BaseSearcher<Character>
{
/**
* 分词从何处开始,这是一个状态
*/
int begin;
DoubleArrayTrie<Character> trie;
protected Searcher(char[] c, DoubleArrayTrie<Character> trie)
{
super(c);
this.trie = trie;
}
protected Searcher(String text, DoubleArrayTrie<Character> trie)
{
super(text);
this.trie = trie;
}
@Override
public Map.Entry<String, Character> next()
{
// 保证首次调用找到一个词语
Map.Entry<String, Character> result = null;
while (begin < c.length)
{
LinkedList<Map.Entry<String, Character>> entryList = trie.commonPrefixSearchWithValue(c, begin);
if (entryList.size() == 0)
{
++begin;
} | else
{
result = entryList.getLast();
offset = begin;
begin += result.getKey().length();
break;
}
}
if (result == null)
{
return null;
}
return result;
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\nr\JapanesePersonDictionary.java | 1 |
请完成以下Java代码 | public void setDescription(String description) {
this.description = description;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public void setHasGraphicalNotation(boolean hasGraphicalNotation) {
this.isGraphicalNotationDefined = hasGraphicalNotation;
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
} | @Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<IdentityLinkEntity> getIdentityLinks() {
if (!isIdentityLinksInitialized) {
definitionIdentityLinkEntities = CommandContextUtil.getCmmnEngineConfiguration().getIdentityLinkServiceConfiguration()
.getIdentityLinkService().findIdentityLinksByScopeDefinitionIdAndType(id, ScopeTypes.CMMN);
isIdentityLinksInitialized = true;
}
return definitionIdentityLinkEntities;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_K_IndexLog[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Index Query.
@param IndexQuery
Text Search Query
*/
public void setIndexQuery (String IndexQuery)
{
set_ValueNoCheck (COLUMNNAME_IndexQuery, IndexQuery);
}
/** Get Index Query.
@return Text Search Query
*/
public String getIndexQuery ()
{
return (String)get_Value(COLUMNNAME_IndexQuery);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getIndexQuery());
}
/** Set Query Result.
@param IndexQueryResult
Result of the text query
*/
public void setIndexQueryResult (int IndexQueryResult)
{
set_ValueNoCheck (COLUMNNAME_IndexQueryResult, Integer.valueOf(IndexQueryResult));
}
/** Get Query Result.
@return Result of the text query
*/
public int getIndexQueryResult ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IndexQueryResult);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Index Log. | @param K_IndexLog_ID
Text search log
*/
public void setK_IndexLog_ID (int K_IndexLog_ID)
{
if (K_IndexLog_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_IndexLog_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_IndexLog_ID, Integer.valueOf(K_IndexLog_ID));
}
/** Get Index Log.
@return Text search log
*/
public int getK_IndexLog_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexLog_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** QuerySource AD_Reference_ID=391 */
public static final int QUERYSOURCE_AD_Reference_ID=391;
/** Collaboration Management = C */
public static final String QUERYSOURCE_CollaborationManagement = "C";
/** Java Client = J */
public static final String QUERYSOURCE_JavaClient = "J";
/** HTML Client = H */
public static final String QUERYSOURCE_HTMLClient = "H";
/** Self Service = W */
public static final String QUERYSOURCE_SelfService = "W";
/** Set Query Source.
@param QuerySource
Source of the Query
*/
public void setQuerySource (String QuerySource)
{
set_Value (COLUMNNAME_QuerySource, QuerySource);
}
/** Get Query Source.
@return Source of the Query
*/
public String getQuerySource ()
{
return (String)get_Value(COLUMNNAME_QuerySource);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_IndexLog.java | 1 |
请完成以下Java代码 | public class CustomOAuth2TokenRetriever
{
public static final String DHL_OAUTH2_PATH = "/parcel/de/account/auth/ropc/v1/token";
private final RestTemplate restTemplate;
public CustomOAuth2TokenRetriever(final RestTemplate restTemplate)
{
this.restTemplate = restTemplate;
}
public String retrieveAccessToken(final DhlClientConfig clientConfig)
{
// Build the form-encoded body for the request
final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("grant_type", "password"); // As described by DHL
formData.add("client_id", clientConfig.getApplicationID());
formData.add("client_secret", clientConfig.getApplicationToken());
formData.add("username", clientConfig.getUsername());
formData.add("password", clientConfig.getSignature()); // Assuming `signature` is the password field
// Prepare the headers
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// Create the request entity
final HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
// Call the token endpoint | final ResponseEntity<DhlOAuthTokenResponse> response = restTemplate.exchange(
clientConfig.getBaseUrl() + DHL_OAUTH2_PATH,
HttpMethod.POST,
requestEntity,
DhlOAuthTokenResponse.class
);
// Extract and return the access token
return Objects.requireNonNull(response.getBody()).getAccess_token();
}
// Response handling class for parsing the token response
@Getter
public static class DhlOAuthTokenResponse
{
private String access_token;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\oauth2\CustomOAuth2TokenRetriever.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final Set<EDIDesadvPackId> lineSSCCIdsToPrint = generateLabels();
if (!lineSSCCIdsToPrint.isEmpty())
{
final ReportResultData report = desadvBL.printSSCC18_Labels(getCtx(), lineSSCCIdsToPrint);
getResult().setReportData(report);
}
return MSG_OK;
}
private Set<EDIDesadvPackId> generateLabels()
{
return trxManager.callInThreadInheritedTrx(this::generateLabelsInTrx);
}
private Set<EDIDesadvPackId> generateLabelsInTrx()
{
if(!p_IsDefault && p_Counter <= 0)
{
throw new FillMandatoryException(PARAM_Counter);
}
final List<I_EDI_DesadvLine> desadvLines = getSelectedLines();
if (desadvLines.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final DesadvLineSSCC18Generator desadvLineLabelsGenerator = DesadvLineSSCC18Generator.builder()
.sscc18CodeService(sscc18CodeService)
.desadvBL(desadvBL)
.ediDesadvPackService(ediDesadvPackService)
.printExistingLabels(true)
.bpartnerId(extractBPartnerId(desadvLines))
.build();
final LinkedHashSet<EDIDesadvPackId> lineSSCCIdsToPrint = new LinkedHashSet<>();
for (final I_EDI_DesadvLine desadvLine : desadvLines)
{
final PrintableDesadvLineSSCC18Labels desadvLineLabels = PrintableDesadvLineSSCC18Labels.builder()
.setEDI_DesadvLine(desadvLine) | .setRequiredSSCC18Count(!p_IsDefault ? p_Counter : null)
.build();
desadvLineLabelsGenerator.generateAndEnqueuePrinting(desadvLineLabels);
lineSSCCIdsToPrint.addAll(desadvLineLabelsGenerator.getLineSSCCIdsToPrint());
}
return lineSSCCIdsToPrint;
}
private static BPartnerId extractBPartnerId(@NonNull final List<I_EDI_DesadvLine> desadvLines)
{
final I_EDI_Desadv ediDesadvRecord = desadvLines.get(0).getEDI_Desadv();
final int bpartnerRepoId = CoalesceUtil.firstGreaterThanZero(
ediDesadvRecord.getDropShip_BPartner_ID(),
ediDesadvRecord.getC_BPartner_ID());
return BPartnerId.ofRepoId(bpartnerRepoId);
}
private List<I_EDI_DesadvLine> getSelectedLines()
{
final Set<Integer> lineIds = getSelectedLineIds();
return desadvBL.retrieveLinesByIds(lineIds);
}
private I_EDI_DesadvLine getSingleSelectedLine()
{
return CollectionUtils.singleElement(getSelectedLines());
}
private Set<Integer> getSelectedLineIds()
{
return getSelectedIncludedRecordIds(I_EDI_DesadvLine.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_GenerateSSCCLabels.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static Map<String, String> createFormData(@NonNull final OAuthAccessTokenRequest request)
{
final Map<String, String> formData = new HashMap<>();
if (Check.isNotBlank(request.getIdentity().getClientId()))
{
formData.put("client_id", request.getIdentity().getClientId());
}
if (Check.isNotBlank(request.getClientSecret()))
{
formData.put("client_secret", request.getClientSecret());
}
if (Check.isNotBlank(request.getIdentity().getUsername()))
{
formData.put("email", request.getIdentity().getUsername());
}
if (Check.isNotBlank(request.getPassword())) | {
formData.put("password", request.getPassword());
}
return formData;
}
@Value
@Builder
private static class CacheKey
{
@NonNull String tokenUrl;
@Nullable String clientId;
@Nullable String username;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-scriptedadapter\src\main\java\de\metas\camel\externalsystems\scriptedadapter\oauth\OAuthTokenManager.java | 2 |
请完成以下Java代码 | public class UserFriendlyException extends RuntimeException {
public UserFriendlyException() {
}
public UserFriendlyException(String message) {
super(message);
}
public UserFriendlyException(String message, Throwable cause) {
super(message, cause);
}
public UserFriendlyException(String message, ErrorCode errorCode) {
super(message);
this.errorCode = errorCode.getCode();
}
public UserFriendlyException(Throwable cause) {
super(cause);
}
public UserFriendlyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
private int httpStatusCode = 200;
private int errorCode = ErrorCode.serverError.getCode(); | public int getHttpStatusCode() {
return httpStatusCode;
}
public UserFriendlyException setHttpStatusCode(int statusCode) {
this.httpStatusCode = statusCode;
return this;
}
public int getErrorCode() {
return errorCode;
}
public UserFriendlyException setErrorCode(int errorCode) {
this.errorCode = errorCode;
return this;
}
} | repos\springboot-demo-master\Aviator\src\main\java\com\et\exception\UserFriendlyException.java | 1 |
请完成以下Java代码 | public BigDecimal getStatementDifference ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_StatementDifference);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_ElementValue getUser1() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser1_ID(), get_TrxName()); }
/** Set User List 1.
@param User1_ID
User defined list element #1
*/
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1
*/
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ElementValue getUser2() throws RuntimeException | {
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser2_ID(), get_TrxName()); }
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cash.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PPOrderCandidateId implements RepoIdAware
{
int repoId;
@JsonCreator
public static PPOrderCandidateId ofRepoId(final int repoId)
{
return new PPOrderCandidateId(repoId);
}
@Nullable
public static PPOrderCandidateId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new PPOrderCandidateId(repoId) : null;
}
public static int toRepoId(@Nullable final PPOrderCandidateId ppOrderCandidateId)
{
return ppOrderCandidateId != null ? ppOrderCandidateId.getRepoId() : -1;
} | private PPOrderCandidateId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Candidate_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final PPOrderCandidateId id1, @Nullable final PPOrderCandidateId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\org\eevolution\productioncandidate\model\PPOrderCandidateId.java | 2 |
请完成以下Java代码 | abstract class AbstractAllocableDocRow implements IAllocableDocRow
{
@Override
public final BigDecimal getOpenAmtConv_APAdjusted()
{
return adjustAP(getOpenAmtConv());
}
/**
* @return not applied amount (i.e. {@link #getOpenAmtConv()} minus {@link #getAppliedAmt()})
*/
public final BigDecimal getNotAppliedAmt()
{
final BigDecimal openAmt = getOpenAmtConv();
final BigDecimal appliedAmt = getAppliedAmt();
final BigDecimal notAppliedAmt = openAmt.subtract(appliedAmt);
return notAppliedAmt;
}
@Override
public final BigDecimal getAppliedAmt_APAdjusted()
{
return adjustAP(getAppliedAmt());
}
protected static final BigDecimal notNullOrZero(final BigDecimal value)
{
return value == null ? BigDecimal.ZERO : value;
} | /**
* AP Adjust given amount (by using {@link #getMultiplierAP()}).
*
* @param amount
* @return AP adjusted amount
*/
protected final BigDecimal adjustAP(final BigDecimal amount)
{
final BigDecimal multiplierAP = getMultiplierAP();
final BigDecimal amount_APAdjusted = amount.multiply(multiplierAP);
return amount_APAdjusted;
}
public final PaymentDirection getPaymentDirection()
{
return PaymentDirection.ofInboundPaymentFlag(isCustomerDocument());
}
@Override
public final boolean isVendorDocument()
{
return getMultiplierAP().signum() < 0;
}
@Override
public final boolean isCustomerDocument()
{
return getMultiplierAP().signum() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\AbstractAllocableDocRow.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
addLog("Calling with params: externalSystemChildConfigId: {}", getExternalSystemChildConfigId());
final Iterator<I_C_BPartner> bPartnerIterator = getSelectedBPartnerRecords();
final IExternalSystemChildConfigId externalSystemChildConfigId = getExternalSystemChildConfigId();
while (bPartnerIterator.hasNext())
{
final TableRecordReference bPartnerRecordRef = TableRecordReference.of(bPartnerIterator.next());
getExportToBPartnerExternalSystem().exportToExternalSystem(externalSystemChildConfigId, bPartnerRecordRef, getPinstanceId());
}
return JavaProcess.MSG_OK;
}
@NonNull
private Iterator<I_C_BPartner> getSelectedBPartnerRecords() | {
final IQueryBuilder<I_C_BPartner> bPartnerQuery = retrieveSelectedRecordsQueryBuilder(I_C_BPartner.class);
return bPartnerQuery
.create()
.iterate(I_C_BPartner.class);
}
protected Optional<ProcessPreconditionsResolution> applyCustomPreconditionsIfAny(final @NonNull IProcessPreconditionsContext context)
{
return Optional.empty();
}
protected abstract ExternalSystemType getExternalSystemType();
protected abstract IExternalSystemChildConfigId getExternalSystemChildConfigId();
protected abstract String getExternalSystemParam();
protected abstract ExportToExternalSystemService getExportToBPartnerExternalSystem();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\bpartner\C_BPartner_SyncTo_ExternalSystem.java | 1 |
请完成以下Java代码 | private Quantity extractQtyCUToDeliver(@NonNull final I_M_ShipmentSchedule record)
{
return shipmentScheduleBL.getQtyToDeliver(record);
}
private BigDecimal extractQtyToDeliverCatchOverride(@NonNull final I_M_ShipmentSchedule record)
{
return shipmentScheduleBL
.getCatchQtyOverride(record)
.map(qty -> qty.toBigDecimal())
.orElse(null);
}
private int extractSalesOrderLineNo(final I_M_ShipmentSchedule record)
{ | final OrderAndLineId salesOrderAndLineId = extractSalesOrderAndLineId(record);
if (salesOrderAndLineId == null)
{
return 0;
}
final I_C_OrderLine salesOrderLine = salesOrderLines.get(salesOrderAndLineId);
if (salesOrderLine == null)
{
return 0;
}
return salesOrderLine.getLine();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidateRowsLoader.java | 1 |
请完成以下Java代码 | public OIRow withSelected(final boolean selected)
{
return this.selected != selected
? toBuilder().selected(selected).build()
: this;
}
public OIRow withUserInputCleared()
{
return this.selected
? toBuilder().selected(false).build()
: this;
}
@Nullable
public OIRowUserInputPart getUserInputPart()
{
if (selected)
{
return OIRowUserInputPart.builder()
.rowId(rowId) | .factAcctId(factAcctId)
.selected(selected)
.build();
}
else
{
return null;
}
}
public OIRow withUserInput(@Nullable final OIRowUserInputPart userInput)
{
final boolean selectedNew = userInput != null && userInput.isSelected();
return this.selected != selectedNew
? toBuilder().selected(selectedNew).build()
: this;
}
public Amount getOpenAmountEffective() {return openAmount;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIRow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setCaseDefinitionKey(String caseDefinitionKey) {
this.caseDefinitionKey = caseDefinitionKey;
}
@ApiModelProperty(example = "My case name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "myBusinessKey")
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "tenant1")
public String getTenantId() {
return tenantId;
}
@ApiModelProperty(example = "overrideTenant1")
public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId;
}
public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) {
this.overrideDefinitionTenantId = overrideDefinitionTenantId;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public List<RestVariable> getVariables() {
return variables;
} | public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public List<RestVariable> getTransientVariables() {
return transientVariables;
}
public void setTransientVariables(List<RestVariable> transientVariables) {
this.transientVariables = transientVariables;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public List<RestVariable> getStartFormVariables() {
return startFormVariables;
}
public void setStartFormVariables(List<RestVariable> startFormVariables) {
this.startFormVariables = startFormVariables;
}
public String getOutcome() {
return outcome;
}
public void setOutcome(String outcome) {
this.outcome = outcome;
}
@JsonIgnore
public boolean isTenantSet() {
return tenantId != null && !StringUtils.isEmpty(tenantId);
}
public boolean getReturnVariables() {
return returnVariables;
}
public void setReturnVariables(boolean returnVariables) {
this.returnVariables = returnVariables;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceCreateRequest.java | 2 |
请完成以下Java代码 | public void setQualityIssuePercentage (java.math.BigDecimal QualityIssuePercentage)
{
set_Value (COLUMNNAME_QualityIssuePercentage, QualityIssuePercentage);
}
/** Get QualityIssuePercentage.
@return QualityIssuePercentage */
@Override
public java.math.BigDecimal getQualityIssuePercentage ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QualityIssuePercentage);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo) | {
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaBreak.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LocalStorageController {
private final LocalStorageService localStorageService;
@GetMapping
@ApiOperation("查询文件")
@PreAuthorize("@el.check('storage:list')")
public ResponseEntity<PageResult<LocalStorageDto>> queryFile(LocalStorageQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(localStorageService.queryAll(criteria,pageable),HttpStatus.OK);
}
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('storage:list')")
public void exportFile(HttpServletResponse response, LocalStorageQueryCriteria criteria) throws IOException {
localStorageService.download(localStorageService.queryAll(criteria), response);
}
@PostMapping
@ApiOperation("上传文件")
@PreAuthorize("@el.check('storage:add')")
public ResponseEntity<Object> createFile(@RequestParam String name, @RequestParam("file") MultipartFile file){
localStorageService.create(name, file);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@ApiOperation("上传图片")
@PostMapping("/pictures")
public ResponseEntity<LocalStorage> uploadPicture(@RequestParam MultipartFile file){
// 判断文件是否为图片
String suffix = FileUtil.getExtensionName(file.getOriginalFilename()); | if(!FileUtil.IMAGE.equals(FileUtil.getFileType(suffix))){
throw new BadRequestException("只能上传图片");
}
LocalStorage localStorage = localStorageService.create(null, file);
return new ResponseEntity<>(localStorage, HttpStatus.OK);
}
@PutMapping
@Log("修改文件")
@ApiOperation("修改文件")
@PreAuthorize("@el.check('storage:edit')")
public ResponseEntity<Object> updateFile(@Validated @RequestBody LocalStorage resources){
localStorageService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除文件")
@DeleteMapping
@ApiOperation("多选删除")
public ResponseEntity<Object> deleteFile(@RequestBody Long[] ids) {
localStorageService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\rest\LocalStorageController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ZebraConfigId implements RepoIdAware
{
@JsonCreator
public static ZebraConfigId ofRepoId(final int repoId)
{
return new ZebraConfigId(repoId);
}
public static ZebraConfigId ofRepoIdOrNull(int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<ZebraConfigId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
int repoId;
private ZebraConfigId(final int zebraConfigId)
{ | this.repoId = Check.assumeGreaterThanZero(zebraConfigId, "zebraConfigId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(final ZebraConfigId zebraConfigId)
{
return zebraConfigId != null ? zebraConfigId.getRepoId() : -1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\ZebraConfigId.java | 2 |
请完成以下Java代码 | protected void moveExternalWorkerJobToExecutableJob(ExternalWorkerJobEntity externalWorkerJob, CommandContext commandContext) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
cmmnEngineConfiguration.getJobServiceConfiguration().getJobManager().moveExternalWorkerJobToExecutableJob(externalWorkerJob);
cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService()
.deleteIdentityLinksByScopeIdAndType(externalWorkerJob.getCorrelationId(), ScopeTypes.EXTERNAL_WORKER);
}
protected ExternalWorkerJobEntity resolveJob(CommandContext commandContext) {
if (StringUtils.isEmpty(externalJobId)) {
throw new FlowableIllegalArgumentException("externalJobId must not be empty");
}
if (StringUtils.isEmpty(workerId)) {
throw new FlowableIllegalArgumentException("workerId must not be empty");
} | CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
ExternalWorkerJobEntityManager externalWorkerJobEntityManager = cmmnEngineConfiguration.getJobServiceConfiguration().getExternalWorkerJobEntityManager();
ExternalWorkerJobEntity job = externalWorkerJobEntityManager.findById(externalJobId);
if (job == null) {
throw new FlowableObjectNotFoundException("No External Worker job found for id: " + externalJobId, ExternalWorkerJobEntity.class);
}
if (!Objects.equals(workerId, job.getLockOwner())) {
throw new FlowableIllegalArgumentException(workerId + " does not hold a lock on the requested job");
}
return job;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\AbstractExternalWorkerJobCmd.java | 1 |
请完成以下Java代码 | public class MetadataElement {
/**
* A visual representation of this element.
*/
private String name;
/**
* The unique id of this element for a given capability.
*/
private String id;
public MetadataElement() {
}
public MetadataElement(MetadataElement other) {
this(other.id, other.name);
}
public MetadataElement(String id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return (this.name != null) ? this.name : this.id; | }
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\MetadataElement.java | 1 |
请完成以下Java代码 | boolean matchesPassword(String rawPassword, PasswordEncoder passwordEncoder) {
return password.matchesPassword(rawPassword, passwordEncoder);
}
void changeEmail(Email email) {
this.email = email;
}
void changePassword(Password password) {
this.password = password;
}
void changeName(UserName userName) {
profile.changeUserName(userName);
}
void changeBio(String bio) {
profile.changeBio(bio);
}
void changeImage(Image image) {
profile.changeImage(image);
}
public Long getId() {
return id;
}
public Email getEmail() {
return email;
} | public UserName getName() {
return profile.getUserName();
}
String getBio() {
return profile.getBio();
}
Image getImage() {
return profile.getImage();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final var user = (User) o;
return email.equals(user.email);
}
@Override
public int hashCode() {
return Objects.hash(email);
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void submitAttempt(BiConsumer<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgConsumer) {
this.msgConsumer = msgConsumer;
msgIdx.set(0);
submitNext();
}
@Override
public void update(ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> reprocessMap) {
super.update(reprocessMap);
}
@Override
protected void doOnSuccess(UUID id) {
if (expectedMsgId.equals(id)) {
msgIdx.incrementAndGet();
submitNext();
}
} | private void submitNext() {
int listSize = orderedMsgList.size();
int idx = msgIdx.get();
if (idx < listSize) {
IdMsgPair<TransportProtos.ToRuleEngineMsg> pair = orderedMsgList.get(idx);
expectedMsgId = pair.uuid;
if (log.isDebugEnabled()) {
log.debug("[{}] submitting [{}] message to rule engine", queueName, pair.msg);
}
msgConsumer.accept(pair.uuid, pair.msg);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\SequentialTbRuleEngineSubmitStrategy.java | 2 |
请完成以下Java代码 | public static void dumpAllLevelsUpToRoot(final Logger logger)
{
final Consumer<Logger> dumpLevel = (currentLogger) -> {
final String currentLoggerInfo;
if (currentLogger instanceof ch.qos.logback.classic.Logger)
{
final ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger)currentLogger;
currentLoggerInfo = "effectiveLevel=" + logbackLogger.getEffectiveLevel() + ", level=" + logbackLogger.getLevel();
}
else
{
currentLoggerInfo = "unknown level for logger object " + currentLogger + " (" + currentLogger.getClass() + ")";
}
System.out.println(" * " + currentLogger.getName() + "(" + System.identityHashCode(currentLogger) + "): " + currentLoggerInfo);
};
System.out.println("\nDumping all log levels starting from " + logger);
forAllLevelsUpToRoot(logger, dumpLevel);
}
public static void forAllLevelsUpToRoot(final Logger logger, final Consumer<Logger> consumer)
{
Logger currentLogger = logger; | String currentLoggerName = currentLogger.getName();
while (currentLogger != null)
{
consumer.accept(currentLogger);
final int idx = currentLoggerName.lastIndexOf(".");
if (idx < 0)
{
break;
}
currentLoggerName = currentLoggerName.substring(0, idx);
currentLogger = getLogger(currentLoggerName);
}
consumer.accept(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME));
}
private LogManager()
{
super();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\LogManager.java | 1 |
请完成以下Java代码 | public static Set<Long> gatherLongPropertyFromJsonNodes(Iterable<JsonNode> jsonNodes, String propertyName) {
Set<Long> result = new HashSet<Long>(); // Using a Set to filter out doubles
for (JsonNode node : jsonNodes) {
if (node.has(propertyName)) {
Long propertyValue = node.get(propertyName).asLong();
if (propertyValue > 0) {
// Just to be safe
result.add(propertyValue);
}
}
}
return result;
}
public static Set<String> gatherStringPropertyFromJsonNodes(Iterable<JsonNode> jsonNodes, String propertyName) {
Set<String> result = new HashSet<String>(); // Using a Set to filter out doubles
for (JsonNode node : jsonNodes) {
if (node.has(propertyName)) {
String propertyValue = node.get(propertyName).asText();
if (propertyValue != null) {
// Just to be safe
result.add(propertyValue);
}
}
}
return result;
}
public static List<JsonNode> filterOutJsonNodes(List<JsonLookupResult> lookupResults) {
List<JsonNode> jsonNodes = new ArrayList<JsonNode>(lookupResults.size());
for (JsonLookupResult lookupResult : lookupResults) {
jsonNodes.add(lookupResult.getJsonNode());
}
return jsonNodes;
}
// Helper classes
public static class JsonLookupResult {
private String id;
private String name;
private JsonNode jsonNode;
public JsonLookupResult(String id, String name, JsonNode jsonNode) {
this(name, jsonNode);
this.id = id; | }
public JsonLookupResult(String name, JsonNode jsonNode) {
this.name = name;
this.jsonNode = jsonNode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public JsonNode getJsonNode() {
return jsonNode;
}
public void setJsonNode(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\util\JsonConverterUtil.java | 1 |
请完成以下Java代码 | public Integer generateRandomWithSplittableRandom(int min, int max) {
SplittableRandom splittableRandom = new SplittableRandom();
int randomWithSplittableRandom = splittableRandom.nextInt(min, max);
return randomWithSplittableRandom;
}
public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) {
SplittableRandom splittableRandom = new SplittableRandom();
IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max);
return limitedIntStreamWithinARangeWithSplittableRandom;
}
public Integer generateRandomWithSecureRandom() {
SecureRandom secureRandom = new SecureRandom();
int randomWithSecureRandom = secureRandom.nextInt();
return randomWithSecureRandom;
} | public Integer generateRandomWithSecureRandomWithinARange(int min, int max) {
SecureRandom secureRandom = new SecureRandom();
int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min;
return randomWithSecureRandomWithinARange;
}
public Integer generateRandomWithRandomDataGenerator(int min, int max) {
RandomDataGenerator randomDataGenerator = new RandomDataGenerator();
int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max);
return randomWithRandomDataGenerator;
}
public Integer generateRandomWithXoRoShiRo128PlusRandom(int min, int max) {
XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom();
int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max - min) + min;
return randomWithXoRoShiRo128PlusRandom;
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-3\src\main\java\com\baeldung\randomnumbers\RandomNumbersGenerator.java | 1 |
请完成以下Java代码 | public void onMsg(TbContext ctx, TbMsg msg) {
if (msg.isTypeOf(TbMsgType.MSG_COUNT_SELF_MSG) && msg.getId().equals(nextTickId)) {
JsonObject telemetryJson = new JsonObject();
telemetryJson.addProperty(this.telemetryPrefix + "_" + ctx.getServiceId(), messagesProcessed.longValue());
messagesProcessed = new AtomicLong(0);
TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("delta", Long.toString(System.currentTimeMillis() - lastScheduledTs + delay));
TbMsg tbMsg = TbMsg.newMsg()
.queueName(msg.getQueueName())
.type(TbMsgType.POST_TELEMETRY_REQUEST)
.originator(ctx.getTenantId())
.customerId(msg.getCustomerId())
.copyMetaData(metaData)
.data(gson.toJson(telemetryJson))
.build();
ctx.enqueueForTellNext(tbMsg, TbNodeConnectionType.SUCCESS);
scheduleTickMsg(ctx, tbMsg); | } else {
messagesProcessed.incrementAndGet();
ctx.ack(msg);
}
}
private void scheduleTickMsg(TbContext ctx, TbMsg msg) {
long curTs = System.currentTimeMillis();
if (lastScheduledTs == 0L) {
lastScheduledTs = curTs;
}
lastScheduledTs = lastScheduledTs + delay;
long curDelay = Math.max(0L, (lastScheduledTs - curTs));
TbMsg tickMsg = ctx.newMsg(null, TbMsgType.MSG_COUNT_SELF_MSG, ctx.getSelfId(), msg != null ? msg.getCustomerId() : null, TbMsgMetaData.EMPTY, TbMsg.EMPTY_STRING);
nextTickId = tickMsg.getId();
ctx.tellSelf(tickMsg, curDelay);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbMsgCountNode.java | 1 |
请完成以下Java代码 | public void setP_WIP_Acct (int P_WIP_Acct)
{
set_Value (COLUMNNAME_P_WIP_Acct, Integer.valueOf(P_WIP_Acct));
}
/** Get Unfertige Leistungen.
@return Das Konto Unfertige Leistungen wird im Produktionaauftrag verwendet
*/
@Override
public int getP_WIP_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing) | {
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
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_M_Product_Category_Acct.java | 1 |
请完成以下Java代码 | public static boolean isNull(Object model, String columnName)
{
final GridTab gridTab = getGridTab(model);
if (gridTab == null)
{
return true;
}
final Object value = gridTab.getValue(columnName);
return value == null;
}
public static boolean hasColumnName(final Object model, final String columnName)
{
final GridTab gridTab = getGridTab(model);
if (gridTab == null)
{
return false;
}
final GridField gridField = gridTab.getField(columnName);
return gridField != null;
}
public final boolean hasColumnName(final String columnName)
{
final GridField gridField = getGridTab().getField(columnName);
return gridField != null;
}
public static int getId(Object model)
{
return getGridTab(model).getRecord_ID();
}
public static boolean isNew(Object model)
{
return getGridTab(model).getRecord_ID() <= 0;
}
public <T> T getDynAttribute(final String attributeName)
{
if (recordId2dynAttributes == null)
{
return null;
}
final int recordId = getGridTab().getRecord_ID();
final Map<String, Object> dynAttributes = recordId2dynAttributes.get(recordId);
// Cleanup old entries to avoid weird cases
// e.g. dynattributes shall be destroyed when user is switching to another record
removeOldDynAttributesEntries(recordId);
if (dynAttributes == null)
{
return null;
}
@SuppressWarnings("unchecked")
final T value = (T)dynAttributes.get(attributeName);
return value;
}
public Object setDynAttribute(final String attributeName, final Object value)
{
Check.assumeNotEmpty(attributeName, "attributeName not empty"); | final int recordId = getGridTab().getRecord_ID();
Map<String, Object> dynAttributes = recordId2dynAttributes.get(recordId);
if (dynAttributes == null)
{
dynAttributes = new HashMap<>();
recordId2dynAttributes.put(recordId, dynAttributes);
}
final Object valueOld = dynAttributes.put(attributeName, value);
// Cleanup old entries because in most of the cases we won't use them
removeOldDynAttributesEntries(recordId);
//
// return the old value
return valueOld;
}
private void removeOldDynAttributesEntries(final int recordIdToKeep)
{
for (final Iterator<Integer> recordIds = recordId2dynAttributes.keySet().iterator(); recordIds.hasNext();)
{
final Integer dynAttribute_recordId = recordIds.next();
if (dynAttribute_recordId != null && dynAttribute_recordId == recordIdToKeep)
{
continue;
}
recordIds.remove();
}
}
public final IModelInternalAccessor getModelInternalAccessor()
{
return modelInternalAccessorSupplier.get();
}
public final boolean isOldValues()
{
return useOldValues;
}
public static final boolean isOldValues(final Object model)
{
final GridTabWrapper wrapper = getWrapper(model);
return wrapper == null ? false : wrapper.isOldValues();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GridTabWrapper.java | 1 |
请完成以下Java代码 | private static String getTruncSql(final String trunc)
{
if (TimeUtil.TRUNC_DAY.equals(trunc))
{
return "DD";
}
else if (TimeUtil.TRUNC_WEEK.equals(trunc))
{
return "WW";
}
else if (TimeUtil.TRUNC_MONTH.equals(trunc))
{
return "MM";
}
else if (TimeUtil.TRUNC_YEAR.equals(trunc))
{
return "Y";
}
else if (TimeUtil.TRUNC_QUARTER.equals(trunc))
{
return "Q";
}
else
{
throw new IllegalArgumentException("Invalid date truncate option: " + trunc);
}
}
@Override
public @NonNull String getColumnSql(final @NonNull String columnName)
{
if (truncSql == null)
{
return columnName;
}
// TODO: optimization: instead of using TRUNC we shall use BETWEEN and precalculated values because:
// * using BETWEEN is INDEX friendly
// * using functions is not INDEX friendly at all and if we have an index on this date column, the index won't be used
final String columnSqlNew = "TRUNC(" + columnName + ", " + DB.TO_STRING(truncSql) + ")";
return columnSqlNew;
}
@Override
public String getValueSql(final Object value, final List<Object> params)
{
final String valueSql;
if (value instanceof ModelColumnNameValue<?>)
{
final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value;
valueSql = modelValue.getColumnName();
}
else
{
valueSql = "?";
params.add(value);
}
if (truncSql == null) | {
return valueSql;
}
// note: cast is needed for postgresql, else you get "ERROR: function trunc(unknown, unknown) is not unique"
return "TRUNC(?::timestamp, " + DB.TO_STRING(truncSql) + ")";
}
/**
* @deprecated Please use {@link #convertValue(java.util.Date)}
*/
@Nullable
@Override
@Deprecated
public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model)
{
return convertValue(TimeUtil.asTimestamp(value));
}
public java.util.Date convertValue(final java.util.Date date)
{
if (date == null)
{
return null;
}
return TimeUtil.trunc(date, trunc);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateTruncQueryFilterModifier.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void waitForQueryToComplete(@NonNull final String queryExecutionId) {
QueryExecutionState queryState;
do {
final var response = athenaClient.getQueryExecution(request ->
request.queryExecutionId(queryExecutionId));
queryState = response.queryExecution().status().state();
switch (queryState) {
case FAILED:
case CANCELLED:
final var error = response.queryExecution().status().athenaError().errorMessage();
log.error("Query execution failed: {}", error);
throw new QueryExecutionFailureException();
case QUEUED:
case RUNNING:
TimeUnit.MILLISECONDS.sleep(WAIT_PERIOD);
break;
case SUCCEEDED:
queryState = QueryExecutionState.SUCCEEDED;
return;
default:
throw new IllegalStateException("Invalid query state");
}
} while (queryState != QueryExecutionState.SUCCEEDED);
}
@SneakyThrows
private <T> List<T> transformQueryResult(@NonNull final GetQueryResultsResponse queryResultsResponse,
@NonNull final Class<T> targetClass) {
final var response = new ArrayList<T>();
final var rows = queryResultsResponse.resultSet().rows();
if (rows.isEmpty()) {
return Collections.emptyList();
}
final var headers = rows.get(0).data().stream() | .map(Datum::varCharValue)
.toList();
rows.stream()
.skip(1)
.forEach(row -> {
final var element = new JSONObject();
final var data = row.data();
for (int i = 0; i < headers.size(); i++) {
final var key = headers.get(i);
final var value = data.get(i).varCharValue();
element.put(key, value);
}
final var obj = OBJECT_MAPPER.convertValue(element, targetClass);
response.add(obj);
});
return response;
}
public record User(Integer id, String name, Integer age, String city) {};
} | repos\tutorials-master\aws-modules\amazon-athena\src\main\java\com\baeldung\athena\service\QueryService.java | 2 |
请完成以下Java代码 | final class XorCsrfTokenUtils {
private XorCsrfTokenUtils() {
}
static @Nullable String getTokenValue(@Nullable String actualToken, String token) {
byte[] actualBytes;
try {
actualBytes = Base64.getUrlDecoder().decode(actualToken);
}
catch (Exception ex) {
return null;
}
byte[] tokenBytes = Utf8.encode(token);
int tokenSize = tokenBytes.length;
if (actualBytes.length != tokenSize * 2) {
return null;
}
// extract token and random bytes
byte[] xoredCsrf = new byte[tokenSize];
byte[] randomBytes = new byte[tokenSize];
System.arraycopy(actualBytes, 0, randomBytes, 0, tokenSize);
System.arraycopy(actualBytes, tokenSize, xoredCsrf, 0, tokenSize); | byte[] csrfBytes = xorCsrf(randomBytes, xoredCsrf);
return Utf8.decode(csrfBytes);
}
private static byte[] xorCsrf(byte[] randomBytes, byte[] csrfBytes) {
Assert.isTrue(randomBytes.length == csrfBytes.length, "arrays must be equal length");
int len = csrfBytes.length;
byte[] xoredCsrf = new byte[len];
System.arraycopy(csrfBytes, 0, xoredCsrf, 0, len);
for (int i = 0; i < len; i++) {
xoredCsrf[i] ^= randomBytes[i];
}
return xoredCsrf;
}
} | repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\web\csrf\XorCsrfTokenUtils.java | 1 |
请完成以下Java代码 | public void sendToRuleEngine(TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> producer,
TenantId tenantId, TbMsg tbMsg, TbQueueCallback callback) {
List<TopicPartitionInfo> tpis = partitionService.resolveAll(ServiceType.TB_RULE_ENGINE, tbMsg.getQueueName(), tenantId, tbMsg.getOriginator());
if (tpis.size() > 1) {
UUID correlationId = UUID.randomUUID();
for (int i = 0; i < tpis.size(); i++) {
TopicPartitionInfo tpi = tpis.get(i);
Integer partition = tpi.getPartition().orElse(null);
UUID id = i > 0 ? UUID.randomUUID() : tbMsg.getId();
tbMsg = tbMsg.transform()
.id(id)
.correlationId(correlationId)
.partition(partition)
.build();
sendToRuleEngine(producer, tpi, tenantId, tbMsg, i == tpis.size() - 1 ? callback : null);
}
} else { | sendToRuleEngine(producer, tpis.get(0), tenantId, tbMsg, callback);
}
}
private void sendToRuleEngine(TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> producer, TopicPartitionInfo tpi,
TenantId tenantId, TbMsg tbMsg, TbQueueCallback callback) {
if (log.isTraceEnabled()) {
log.trace("[{}][{}] Pushing to topic {} message {}", tenantId, tbMsg.getOriginator(), tpi.getFullTopicName(), tbMsg);
}
ToRuleEngineMsg msg = ToRuleEngineMsg.newBuilder()
.setTbMsgProto(TbMsg.toProto(tbMsg))
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits()).build();
producer.send(tpi, new TbProtoQueueMsg<>(tbMsg.getId(), msg), callback);
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\TbRuleEngineProducerService.java | 1 |
请完成以下Java代码 | private static Mono<OidcIdToken> validateNonce(
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication, OidcIdToken idToken) {
String requestNonce = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationRequest()
.getAttribute(OidcParameterNames.NONCE);
if (requestNonce != null) {
String nonceHash = getNonceHash(requestNonce);
String nonceHashClaim = idToken.getNonce();
if (nonceHashClaim == null || !nonceHashClaim.equals(nonceHash)) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
}
return Mono.just(idToken);
}
private static String getNonceHash(String requestNonce) { | try {
return createHash(requestNonce);
}
catch (NoSuchAlgorithmException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
}
static String createHash(String nonce) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(nonce.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeReactiveAuthenticationManager.java | 1 |
请完成以下Java代码 | public Map<String, Employee> xmlToHashMapUsingJAXB(String xmlData) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Employees.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Employees employees = (Employees) unmarshaller.unmarshal(new StringReader(xmlData));
return employees.getEmployeeList()
.stream()
.collect(Collectors.toMap(Employee::getId, Function.identity()));
}
public Map<String, Employee> xmlToHashMapUsingDOMParserXpath(String xmlData) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlData)));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression xPathExpr = xpath.compile("/employees/employee");
NodeList nodes = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
HashMap<String, Employee> map = new HashMap<>();
for (int i = 0; i < nodes.getLength(); i++) {
Element node = (Element) nodes.item(i);
Employee employee = new Employee();
employee.setId(node.getElementsByTagName("id")
.item(0)
.getTextContent());
employee.setFirstName(node.getElementsByTagName("firstName")
.item(0)
.getTextContent());
employee.setLastName(node.getElementsByTagName("lastName")
.item(0)
.getTextContent()); | map.put(employee.getId(), employee);
}
return map;
}
private static void parseXmlToMap(Map<String, Employee> employeeMap, List<LinkedHashMap<String, String>> list) {
list.forEach(empMap -> {
Employee employee = new Employee();
for (Map.Entry<String, String> key : empMap.entrySet()) {
switch (key.getKey()) {
case "id":
employee.setId(key.getValue());
break;
case "firstName":
employee.setFirstName(key.getValue());
break;
case "lastName":
employee.setLastName(key.getValue());
break;
default:
break;
}
}
employeeMap.put(employee.getId(), employee);
});
}
} | repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xml\tohashmap\XmlToHashMap.java | 1 |
请完成以下Java代码 | public class Student {
private int no;
private String name;
public Student() {
}
public Student(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
} | public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void destroy() {
System.out.println("Student(no: " + no + ") is destroyed");
}
} | repos\tutorials-master\spring-core-2\src\main\java\com\baeldung\applicationcontext\Student.java | 1 |
请完成以下Java代码 | public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() {return relatedProcesses;}
@Override
public DocumentFilterList getFilters() {return DocumentFilterList.ofNullable(getRowsData().getFilter());}
@Override
protected OIViewData getRowsData() {return OIViewData.cast(super.getRowsData());}
@Override
public ViewHeaderProperties getHeaderProperties() {return getRowsData().getHeaderProperties();}
public void markRowsAsSelected(final DocumentIdsSelection rowIds)
{
getRowsData().markRowsAsSelected(rowIds);
ViewChangesCollector.getCurrentOrAutoflush().collectRowsAndHeaderPropertiesChanged(this, rowIds);
}
public boolean hasSelectedRows() | {
return getRowsData().hasSelectedRows();
}
public void clearUserInputAndResetFilter()
{
final OIViewData rowsData = getRowsData();
rowsData.clearUserInput();
rowsData.clearFilter();
invalidateAll();
}
public OIRowUserInputParts getUserInput() {return getRowsData().getUserInput();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIView.java | 1 |
请完成以下Java代码 | public void destroy() {
if (this.httpClient != null) {
this.httpClient.destroy();
}
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
boolean hasChanges = false;
switch (fromVersion) {
case 0:
if (!oldConfiguration.has(PARSE_TO_PLAIN_TEXT) && oldConfiguration.has(TRIM_DOUBLE_QUOTES)) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(PARSE_TO_PLAIN_TEXT, oldConfiguration.get(TRIM_DOUBLE_QUOTES).booleanValue());
((ObjectNode) oldConfiguration).remove(TRIM_DOUBLE_QUOTES);
}
case 1: | if (oldConfiguration.has("useRedisQueueForMsgPersistence")) {
hasChanges = true;
((ObjectNode) oldConfiguration).remove(List.of("useRedisQueueForMsgPersistence", "trimQueue", "maxQueueSize"));
}
case 2:
if (!oldConfiguration.has(MAX_IN_MEMORY_BUFFER_SIZE_IN_KB)) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(MAX_IN_MEMORY_BUFFER_SIZE_IN_KB, 256);
}
break;
default:
break;
}
return new TbPair<>(hasChanges, oldConfiguration);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\rest\TbRestApiCallNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public org.springframework.amqp.support.converter.MessageConverter amqpMessageConverter(final ObjectMapper jsonObjectMapper)
{
return new Jackson2JsonMessageConverter(jsonObjectMapper);
}
@Bean
public org.springframework.messaging.converter.MessageConverter messageConverter()
{
return new MappingJackson2MessageConverter();
}
@Bean
public MessageHandlerMethodFactory messageHandlerMethodFactory()
{
final DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
factory.setMessageConverter(messageConverter());
return factory;
} | /**
* Attempt to set the application name (e.g. metasfresh-webui-api) as the rabbitmq connection name.
* Thx to <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-messaging.html#boot-features-rabbitmq">spring-boot-features-rabbitmq</a>
* <p>
* (although right now it doesn't need to work..)
*/
@Bean
public ConnectionNameStrategy connectionNameStrategy()
{
return connectionFactory -> appName;
}
@Bean
public EventBusMonitoringService eventBusMonitoringService(@NonNull final Optional<PerformanceMonitoringService> performanceMonitoringService)
{
return new EventBusMonitoringService(performanceMonitoringService.orElse(NoopPerformanceMonitoringService.INSTANCE));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\RabbitMQEventBusConfiguration.java | 2 |
请完成以下Java代码 | final class PermissionInternalUtils
{
/**
* Checks if given permission is compatible with our permission and returns the given permission casted to our type.
*
* @param from
* @return permission, casted to our type; never returns null
* @throws AdempiereException if the permision is not compatible
*/
public static final <PermissionType extends Permission> PermissionType checkCompatibleAndCastToTarget(final Permission target, final Permission from)
{
if (!sameResource(target, from))
{
throw new AdempiereException("Incompatible permission to be merged: " + target + ", " + from);
} | if (target.getClass() != from.getClass())
{
throw new AdempiereException("Incompatible permission to be merged: " + target + ", " + from
+ " Required class: " + target.getClass()
+ " Actual class: " + from.getClass());
}
@SuppressWarnings("unchecked")
final PermissionType permissionCasted = (PermissionType)from;
return permissionCasted;
}
private static final boolean sameResource(final Permission permission1, final Permission permission2)
{
return permission1.getResource().equals(permission2.getResource());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\PermissionInternalUtils.java | 1 |
请完成以下Java代码 | protected void deleteC_Invoice_Clearing_AllocsOnReactivate(final I_C_Flatrate_Term term)
{
// note: we assume that invoice candidate validator will take care of the invoice candidate's IsToClear flag
final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class);
final List<I_C_Invoice_Clearing_Alloc> icas = flatrateDAO.retrieveClearingAllocs(term);
for (final I_C_Invoice_Clearing_Alloc ica : icas)
{
InterfaceWrapperHelper.delete(ica);
}
}
/**
* When a term is reactivated, its invoice candidate needs to be deleted.
* Note that we assume the deletion will fail with a meaningful error message if the invoice candidate has already been invoiced.
*/
public void deleteInvoiceCandidates(@NonNull final I_C_Flatrate_Term term)
{
Services.get(IInvoiceCandDAO.class).deleteAllReferencingInvoiceCandidates(term);
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void afterSaveOfNextTermForPredecessor(final I_C_Flatrate_Term next, final I_C_Flatrate_Term predecessor)
{
// nothing
} | /**
* Does nothing; Feel free to override.
*/
@Override
public void afterFlatrateTermEnded(final I_C_Flatrate_Term term)
{
// nothing
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void beforeSaveOfNextTermForPredecessor(final I_C_Flatrate_Term next, final I_C_Flatrate_Term predecessor)
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\spi\FallbackFlatrateTermEventListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ConsignmentItemInformationExtensionType {
@XmlElement(name = "ConsignmentItemInformationExtension", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
protected at.erpel.schemas._1p0.documents.extensions.edifact.ConsignmentItemInformationExtensionType consignmentItemInformationExtension;
@XmlElement(name = "ErpelConsignmentItemInformationExtension")
protected CustomType erpelConsignmentItemInformationExtension;
/**
* Gets the value of the consignmentItemInformationExtension property.
*
* @return
* possible object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.ConsignmentItemInformationExtensionType }
*
*/
public at.erpel.schemas._1p0.documents.extensions.edifact.ConsignmentItemInformationExtensionType getConsignmentItemInformationExtension() {
return consignmentItemInformationExtension;
}
/**
* Sets the value of the consignmentItemInformationExtension property.
*
* @param value
* allowed object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.ConsignmentItemInformationExtensionType }
*
*/
public void setConsignmentItemInformationExtension(at.erpel.schemas._1p0.documents.extensions.edifact.ConsignmentItemInformationExtensionType value) {
this.consignmentItemInformationExtension = value;
} | /**
* Gets the value of the erpelConsignmentItemInformationExtension property.
*
* @return
* possible object is
* {@link CustomType }
*
*/
public CustomType getErpelConsignmentItemInformationExtension() {
return erpelConsignmentItemInformationExtension;
}
/**
* Sets the value of the erpelConsignmentItemInformationExtension property.
*
* @param value
* allowed object is
* {@link CustomType }
*
*/
public void setErpelConsignmentItemInformationExtension(CustomType value) {
this.erpelConsignmentItemInformationExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\ConsignmentItemInformationExtensionType.java | 2 |
请完成以下Java代码 | public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_MD_Stock_WarehouseAndProduct_ID (final int T_MD_Stock_WarehouseAndProduct_ID)
{
if (T_MD_Stock_WarehouseAndProduct_ID < 1)
set_ValueNoCheck (COLUMNNAME_T_MD_Stock_WarehouseAndProduct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_T_MD_Stock_WarehouseAndProduct_ID, T_MD_Stock_WarehouseAndProduct_ID); | }
@Override
public int getT_MD_Stock_WarehouseAndProduct_ID()
{
return get_ValueAsInt(COLUMNNAME_T_MD_Stock_WarehouseAndProduct_ID);
}
@Override
public void setUUID (final java.lang.String UUID)
{
set_Value (COLUMNNAME_UUID, UUID);
}
@Override
public java.lang.String getUUID()
{
return get_ValueAsString(COLUMNNAME_UUID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_T_MD_Stock_WarehouseAndProduct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class VendorProductInfo
{
BPartnerId vendorId;
ProductAndCategoryAndManufacturerId product;
AttributeSetInstanceId attributeSetInstanceId;
String vendorProductNo;
String vendorProductName;
boolean aggregatePOs;
/** vendor specific discount that comes from the {@code C_BPartner} record. I.e. not related to "flat-percent" pricing conditions. */
Percent vendorFlatDiscount;
private PricingConditions pricingConditions;
boolean defaultVendor;
@Builder
private VendorProductInfo(
@NonNull final BPartnerId vendorId,
@NonNull final Boolean defaultVendor,
//
@NonNull final ProductAndCategoryAndManufacturerId product,
@NonNull final AttributeSetInstanceId attributeSetInstanceId,
@NonNull final String vendorProductNo,
@NonNull final String vendorProductName,
//
final boolean aggregatePOs,
//
final Percent vendorFlatDiscount,
@NonNull final PricingConditions pricingConditions)
{
this.vendorId = vendorId;
this.defaultVendor = defaultVendor;
this.product = product;
this.attributeSetInstanceId = attributeSetInstanceId;
this.vendorProductNo = vendorProductNo; | this.vendorProductName = vendorProductName;
this.aggregatePOs = aggregatePOs;
this.vendorFlatDiscount = vendorFlatDiscount != null ? vendorFlatDiscount : Percent.ZERO;
this.pricingConditions = pricingConditions;
}
public ProductId getProductId()
{
return getProduct().getProductId();
}
public PricingConditionsBreak getPricingConditionsBreakOrNull(final Quantity qtyToDeliver)
{
final PricingConditionsBreakQuery query = createPricingConditionsBreakQuery(qtyToDeliver);
return getPricingConditions().pickApplyingBreak(query);
}
public VendorProductInfo assertThatAttributeSetInstanceIdCompatibleWith(@NonNull final AttributeSetInstanceId otherId)
{
if (AttributeSetInstanceId.NONE.equals(attributeSetInstanceId))
{
return this;
}
Check.errorUnless(Objects.equals(otherId, attributeSetInstanceId),
"The given atributeSetInstanceId is not compatible with our id; otherId={}; this={}", otherId, this);
return this;
}
private PricingConditionsBreakQuery createPricingConditionsBreakQuery(final Quantity qtyToDeliver)
{
return PricingConditionsBreakQuery.builder()
.product(getProduct())
// .attributeInstances(attributeInstances)// TODO
.qty(qtyToDeliver.toBigDecimal())
.price(BigDecimal.ZERO) // N/A
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\VendorProductInfo.java | 2 |
请完成以下Java代码 | public class C_Flatrate_Matching
{
public static final transient C_Flatrate_Matching instance = new C_Flatrate_Matching();
private C_Flatrate_Matching()
{
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void updateDataEntry(final I_C_Flatrate_Matching matching)
{
final I_C_Flatrate_Conditions fc = matching.getC_Flatrate_Conditions();
if (matching.getM_Product_Category_Matching_ID() <= 0 | && X_C_Flatrate_Conditions.TYPE_CONDITIONS_HoldingFee.equals(fc.getType_Conditions()))
{
throw new FillMandatoryException(I_C_Flatrate_Matching.COLUMNNAME_M_Product_Category_Matching_ID);
}
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_VOID, ModelValidator.TIMING_BEFORE_CLOSE })
public void disallowNotSupportedDocActions(final I_C_Flatrate_Matching matching)
{
throw new AdempiereException(MainValidator.MSG_FLATRATE_DOC_ACTION_NOT_SUPPORTED_0P);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_Matching.java | 1 |
请完成以下Java代码 | /* package */class LambdaDocumentFieldCallout implements IDocumentFieldCallout
{
private final String id;
private final Set<String> dependsOnFieldNames;
private final ILambdaDocumentFieldCallout lambdaCallout;
public LambdaDocumentFieldCallout(final String triggeringFieldName, final ILambdaDocumentFieldCallout lambdaCallout)
{
super();
Check.assumeNotEmpty(triggeringFieldName, "triggeringFieldName is not empty");
Check.assumeNotNull(lambdaCallout, "Parameter lambdaCallout is not null");
id = "lambda-" + triggeringFieldName + "-" + lambdaCallout.toString();
dependsOnFieldNames = ImmutableSet.of(triggeringFieldName);
this.lambdaCallout = lambdaCallout;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("id", id)
.toString();
}
@Override
public String getId() | {
return id;
}
@Override
public Set<String> getDependsOnFieldNames()
{
return dependsOnFieldNames;
}
@Override
public void execute(final ICalloutExecutor executor, final ICalloutField field) throws Exception
{
lambdaCallout.execute(field);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LambdaDocumentFieldCallout.java | 1 |
请完成以下Java代码 | private void exportText()
{
JFileChooser jc = new JFileChooser();
jc.setDialogTitle(msgBL.getMsg(Env.getCtx(), "ExportText"));
jc.setDialogType(JFileChooser.SAVE_DIALOG);
jc.setFileSelectionMode(JFileChooser.FILES_ONLY);
//
if (jc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
return;
try
{
BufferedWriter bout = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (jc.getSelectedFile())));
bout.write(textArea.getText());
bout.flush();
bout.close();
}
catch (Exception e)
{
log.warn(e.getMessage());
}
} // exportText
/**
* ChangeListener for TabbedPane
* @param e event
*/
@Override
public void stateChanged(ChangeEvent e)
{
if (tabbedPane.getSelectedIndex() == 1) // switch to HTML
textPane.setText(textArea.getText());
} // stateChanged
@Override
public void keyTyped (KeyEvent e)
{
}
@Override
public void keyPressed (KeyEvent e)
{
}
@Override
public void keyReleased (KeyEvent e)
{
updateStatusBar();
}
// metas: begin
public Editor(Frame frame, String header, String text, boolean editable, int maxSize, GridField gridField)
{
this(frame, header, text, editable, maxSize);
BoilerPlateMenu.createFieldMenu(textArea, null, gridField);
}
private static final GridField getGridField(Container c) | {
if (c == null)
{
return null;
}
GridField field = null;
if (c instanceof VEditor)
{
VEditor editor = (VEditor)c;
field = editor.getField();
}
else
{
try
{
field = (GridField)c.getClass().getMethod("getField").invoke(c);
}
catch (Exception e)
{
final AdempiereException ex = new AdempiereException("Cannot get GridField from " + c, e);
log.warn(ex.getLocalizedMessage(), ex);
}
}
return field;
}
// metas: end
} // Editor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\Editor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HuPackingInstructionsItemId implements RepoIdAware
{
@JsonCreator
public static HuPackingInstructionsItemId ofRepoId(final int repoId)
{
if (repoId == TEMPLATE_MATERIAL_ITEM.repoId)
{
return TEMPLATE_MATERIAL_ITEM;
}
if (repoId == TEMPLATE_PACKING_ITEM.repoId)
{
return TEMPLATE_PACKING_ITEM;
}
else if (repoId == VIRTUAL.repoId)
{
return VIRTUAL;
}
else
{
return new HuPackingInstructionsItemId(repoId);
}
}
public static HuPackingInstructionsItemId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(final HuPackingInstructionsItemId id)
{
return id != null ? id.getRepoId() : -1;
}
public static final HuPackingInstructionsItemId TEMPLATE_MATERIAL_ITEM = new HuPackingInstructionsItemId(540004);
private static final HuPackingInstructionsItemId TEMPLATE_PACKING_ITEM = new HuPackingInstructionsItemId(100);
public static final HuPackingInstructionsItemId VIRTUAL = new HuPackingInstructionsItemId(101);
int repoId;
private HuPackingInstructionsItemId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Item_ID");
}
@Override
@JsonValue
public int getRepoId() | {
return repoId;
}
public static boolean equals(final HuPackingInstructionsItemId o1, final HuPackingInstructionsItemId o2)
{
return Objects.equals(o1, o2);
}
public boolean isTemplate()
{
return isTemplateRepoId(repoId);
}
public static boolean isTemplateRepoId(final int repoId)
{
return repoId == TEMPLATE_MATERIAL_ITEM.repoId
|| repoId == TEMPLATE_PACKING_ITEM.repoId;
}
public boolean isVirtual()
{
return isVirtualRepoId(repoId);
}
public static boolean isVirtualRepoId(final int repoId)
{
return repoId == VIRTUAL.repoId;
}
public boolean isRealPackingInstructions()
{
return isRealPackingInstructionsRepoId(repoId);
}
public static boolean isRealPackingInstructionsRepoId(final int repoId)
{
return repoId > 0
&& !isTemplateRepoId(repoId)
&& !isVirtualRepoId(repoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HuPackingInstructionsItemId.java | 2 |
请完成以下Java代码 | public ProcessInstanceStartEventSubscriptionDeletionBuilder processDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
return this;
}
@Override
public ProcessInstanceStartEventSubscriptionDeletionBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public ProcessInstanceStartEventSubscriptionDeletionBuilder addCorrelationParameterValue(String parameterName, Object parameterValue) {
correlationParameterValues.put(parameterName, parameterValue);
return this;
}
@Override
public ProcessInstanceStartEventSubscriptionDeletionBuilder addCorrelationParameterValues(Map<String, Object> parameters) {
correlationParameterValues.putAll(parameters);
return this;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public boolean hasCorrelationParameterValues() {
return correlationParameterValues.size() > 0;
} | public Map<String, Object> getCorrelationParameterValues() {
return correlationParameterValues;
}
@Override
public void deleteSubscriptions() {
checkValidInformation();
runtimeService.deleteProcessInstanceStartEventSubscriptions(this);
}
protected void checkValidInformation() {
if (StringUtils.isEmpty(processDefinitionId)) {
throw new FlowableIllegalArgumentException("The process definition must be provided using the exact id of the version the subscription was registered for.");
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceStartEventSubscriptionDeletionBuilderImpl.java | 1 |
请完成以下Java代码 | public final void setDebugTrxCreateStacktrace(final boolean debugTrxCreateStacktrace)
{
this.debugTrxCreateStacktrace = debugTrxCreateStacktrace;
}
@Override
public final boolean isDebugTrxCloseStacktrace()
{
return debugTrxCloseStacktrace;
}
@Override
public final void setDebugTrxCloseStacktrace(final boolean debugTrxCloseStacktrace)
{
this.debugTrxCloseStacktrace = debugTrxCloseStacktrace;
}
@Override
public final void setDebugClosedTransactions(final boolean enabled)
{
trxName2trxLock.lock();
try
{
if (enabled)
{
if (debugClosedTransactionsList == null)
{
debugClosedTransactionsList = new ArrayList<>();
}
}
else
{
debugClosedTransactionsList = null;
}
}
finally
{
trxName2trxLock.unlock();
}
}
@Override
public final boolean isDebugClosedTransactions()
{
return debugClosedTransactionsList != null;
}
@Override
public final List<ITrx> getDebugClosedTransactions()
{
trxName2trxLock.lock();
try
{
if (debugClosedTransactionsList == null)
{
return Collections.emptyList(); | }
return new ArrayList<>(debugClosedTransactionsList);
}
finally
{
trxName2trxLock.unlock();
}
}
@Override
public void setDebugConnectionBackendId(boolean debugConnectionBackendId)
{
this.debugConnectionBackendId = debugConnectionBackendId;
}
@Override
public boolean isDebugConnectionBackendId()
{
return debugConnectionBackendId;
}
@Override
public String toString()
{
return "AbstractTrxManager [trxName2trx=" + trxName2trx + ", trxName2trxLock=" + trxName2trxLock + ", trxNameGenerator=" + trxNameGenerator + ", threadLocalTrx=" + threadLocalTrx + ", threadLocalOnRunnableFail=" + threadLocalOnRunnableFail + ", debugTrxCreateStacktrace=" + debugTrxCreateStacktrace + ", debugTrxCloseStacktrace=" + debugTrxCloseStacktrace + ", debugClosedTransactionsList="
+ debugClosedTransactionsList + ", debugConnectionBackendId=" + debugConnectionBackendId + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrxManager.java | 1 |
请完成以下Java代码 | public String getPosthumousTitle() {
return posthumousTitle;
}
public void setPosthumousTitle(String posthumousTitle) {
this.posthumousTitle = posthumousTitle;
}
public String getSon() {
return son;
}
public void setSon(String son) {
this.son = son;
}
public String getRemark() { | return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public King getKing() {
return king;
}
public void setKing(King king) {
this.king = king;
}
} | repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\Queen.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeleteExternalWorkerJobCmd implements Command<Object> {
protected String jobId;
protected JobServiceConfiguration jobServiceConfiguration;
public DeleteExternalWorkerJobCmd(String jobId, JobServiceConfiguration jobServiceConfiguration) {
this.jobId = jobId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Void execute(CommandContext commandContext) {
if (jobId == null) {
throw new FlowableIllegalArgumentException("jobId is null");
}
ExternalWorkerJobEntityManager jobEntityManager = jobServiceConfiguration.getExternalWorkerJobEntityManager(); | ExternalWorkerJobEntity job = jobEntityManager.findById(jobId);
if (job == null) {
throw new FlowableObjectNotFoundException("No external worker job found with id '" + jobId + "'", Job.class);
}
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, job),
jobServiceConfiguration.getEngineName());
}
jobEntityManager.delete(job);
return null;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\DeleteExternalWorkerJobCmd.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<Method> getMethods() {
return this.methods;
}
/**
* Set a method list.
* @param methods the methods.
* @since 3.2
*/
public void setMethods(List<Method> methods) {
this.methods = methods;
}
/**
* Get a default method.
* @return the default method.
* @since 3.2
*/
public @Nullable Method getDefaultMethod() {
return this.defaultMethod;
}
/**
* Set a default method.
* @param defaultMethod the default method.
* @since 3.2
*/
public void setDefaultMethod(@Nullable Method defaultMethod) {
this.defaultMethod = defaultMethod;
}
/**
* Set a payload validator.
* @param validator the validator.
* @since 2.5.11
*/
public void setValidator(Validator validator) {
this.validator = validator;
} | @Override
protected HandlerAdapter configureListenerAdapter(MessagingMessageListenerAdapter<K, V> messageListener) {
List<InvocableHandlerMethod> invocableHandlerMethods = new ArrayList<>();
InvocableHandlerMethod defaultHandler = null;
for (Method method : this.methods) {
MessageHandlerMethodFactory messageHandlerMethodFactory = getMessageHandlerMethodFactory();
if (messageHandlerMethodFactory != null) {
InvocableHandlerMethod handler = messageHandlerMethodFactory
.createInvocableHandlerMethod(getBean(), method);
invocableHandlerMethods.add(handler);
if (method.equals(this.defaultMethod)) {
defaultHandler = handler;
}
}
}
DelegatingInvocableHandler delegatingHandler = new DelegatingInvocableHandler(invocableHandlerMethods,
defaultHandler, getBean(), getResolver(), getBeanExpressionContext(), getBeanFactory(), this.validator);
return new HandlerAdapter(delegatingHandler);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\MultiMethodKafkaListenerEndpoint.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DomainUserDetailsService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
if (new EmailValidator().isValid(login, null)) {
return userRepository.findOneWithAuthoritiesByEmail(login)
.map(user -> createSpringSecurityUser(login, user))
.orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
}
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin)
.map(user -> createSpringSecurityUser(lowercaseLogin, user))
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); | }
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
grantedAuthorities);
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\security\DomainUserDetailsService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TelemetryConfig {
private static final String OTLP_TRACES_ENDPOINT = "http://telemetry-collector:4318/v1/traces";
private static final String OTLP_METRICS_ENDPOINT = "http://telemetry-collector:4318/v1/metrics";
private static final String OTLP_LOGS_ENDPOINT = "http://telemetry-collector:4317";
private static TelemetryConfig telemetryConfig;
private final OpenTelemetry openTelemetry;
private TelemetryConfig() {
Resource resource = Resource.getDefault()
.toBuilder()
.put(AttributeKey.stringKey("service.name"), "trivia-service")
.put(AttributeKey.stringKey("service.version"), "1.0-SNAPSHOT")
.build();
// Tracing setup
SpanExporter spanExporter = OtlpHttpSpanExporter.builder().setEndpoint(OTLP_TRACES_ENDPOINT).build();
SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
.setResource(resource)
.addSpanProcessor(SimpleSpanProcessor.create(spanExporter))
.build();
// Metrics setup
MetricExporter metricExporter = OtlpHttpMetricExporter.builder().setEndpoint(OTLP_METRICS_ENDPOINT).build();
MetricReader metricReader = PeriodicMetricReader.builder(metricExporter)
.setInterval(30, TimeUnit.SECONDS)
.build();
SdkMeterProvider meterProvider = SdkMeterProvider.builder()
.setResource(resource)
.registerMetricReader(metricReader)
.build();
// Logging setup | LogRecordExporter logRecordExporter = OtlpGrpcLogRecordExporter.builder().setEndpoint(OTLP_LOGS_ENDPOINT).build();
LogRecordProcessor logRecordProcessor = BatchLogRecordProcessor.builder(logRecordExporter).build();
SdkLoggerProvider sdkLoggerProvider = SdkLoggerProvider.builder()
.setResource(resource)
.addLogRecordProcessor(logRecordProcessor).build();
openTelemetry = OpenTelemetrySdk.builder()
.setMeterProvider(meterProvider)
.setTracerProvider(tracerProvider)
.setLoggerProvider(sdkLoggerProvider)
.setPropagators(ContextPropagators.create(TextMapPropagator.composite(W3CTraceContextPropagator.getInstance(), W3CBaggagePropagator.getInstance())))
.buildAndRegisterGlobal();
//OpenTelemetryAppender in log4j configuration and install
OpenTelemetryAppender.install(openTelemetry);
}
public OpenTelemetry getOpenTelemetry() {
return openTelemetry;
}
public static TelemetryConfig getInstance() {
if (telemetryConfig == null) {
telemetryConfig = new TelemetryConfig();
}
return telemetryConfig;
}
} | repos\tutorials-master\libraries-open-telemetry\otel-collector\trivia-service\src\main\java\com\baeldung\TelemetryConfig.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setC_Queue_Element_ID (final int C_Queue_Element_ID)
{
if (C_Queue_Element_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_Element_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_Element_ID, C_Queue_Element_ID);
}
@Override
public int getC_Queue_Element_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_Element_ID);
}
@Override
public I_C_Queue_WorkPackage getC_Queue_WorkPackage()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_WorkPackage_ID, I_C_Queue_WorkPackage.class);
}
@Override
public void setC_Queue_WorkPackage(final I_C_Queue_WorkPackage C_Queue_WorkPackage)
{
set_ValueFromPO(COLUMNNAME_C_Queue_WorkPackage_ID, I_C_Queue_WorkPackage.class, C_Queue_WorkPackage);
}
@Override
public void setC_Queue_WorkPackage_ID (final int C_Queue_WorkPackage_ID)
{
if (C_Queue_WorkPackage_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, C_Queue_WorkPackage_ID);
}
@Override
public int getC_Queue_WorkPackage_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_WorkPackage_ID);
}
@Override
public I_C_Queue_WorkPackage getC_Queue_Workpackage_Preceeding()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class);
}
@Override
public void setC_Queue_Workpackage_Preceeding(final I_C_Queue_WorkPackage C_Queue_Workpackage_Preceeding) | {
set_ValueFromPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class, C_Queue_Workpackage_Preceeding);
}
@Override
public void setC_Queue_Workpackage_Preceeding_ID (final int C_Queue_Workpackage_Preceeding_ID)
{
throw new IllegalArgumentException ("C_Queue_Workpackage_Preceeding_ID is virtual column"); }
@Override
public int getC_Queue_Workpackage_Preceeding_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Element.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static MultiQueryRequest buildQueryParentProductRequest(@NonNull final String parentId)
{
return MultiQueryRequest.builder()
.filter(JsonQuery.builder()
.field(FIELD_PRODUCT_ID)
.queryType(QueryType.EQUALS)
.value(parentId)
.build())
.build();
}
@NonNull
@VisibleForTesting
public static JsonQuery buildUpdatedAfterJsonQueries(@NonNull final String updatedAfter)
{
final HashMap<String, String> parameters = new HashMap<>();
parameters.put(PARAMETERS_GTE, updatedAfter);
return JsonQuery.builder() | .queryType(QueryType.MULTI)
.operatorType(OperatorType.OR)
.jsonQuery(JsonQuery.builder()
.field(FIELD_UPDATED_AT)
.queryType(QueryType.RANGE)
.parameters(parameters)
.build())
.jsonQuery(JsonQuery.builder()
.field(FIELD_CREATED_AT)
.queryType(QueryType.RANGE)
.parameters(parameters)
.build())
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\model\QueryHelper.java | 2 |
请完成以下Java代码 | public void handleSimpleDoc() throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph title = document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun = title.createRun();
titleRun.setText("Build Your REST API with Spring");
titleRun.setColor("009933");
titleRun.setBold(true);
titleRun.setFontFamily("Courier");
titleRun.setFontSize(20);
XWPFParagraph subTitle = document.createParagraph();
subTitle.setAlignment(ParagraphAlignment.CENTER);
XWPFRun subTitleRun = subTitle.createRun();
subTitleRun.setText("from HTTP fundamentals to API Mastery");
subTitleRun.setColor("00CC44");
subTitleRun.setFontFamily("Courier");
subTitleRun.setFontSize(16);
subTitleRun.setTextPosition(20);
subTitleRun.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
XWPFParagraph image = document.createParagraph();
image.setAlignment(ParagraphAlignment.CENTER);
XWPFRun imageRun = image.createRun();
imageRun.setTextPosition(20);
Path imagePath = Paths.get(ClassLoader.getSystemResource(logo).toURI());
imageRun.addPicture(Files.newInputStream(imagePath), XWPFDocument.PICTURE_TYPE_PNG, imagePath.getFileName().toString(), Units.toEMU(50), Units.toEMU(50));
XWPFParagraph sectionTitle = document.createParagraph();
XWPFRun sectionTRun = sectionTitle.createRun();
sectionTRun.setText("What makes a good API?");
sectionTRun.setColor("00CC44");
sectionTRun.setBold(true);
sectionTRun.setFontFamily("Courier");
XWPFParagraph para1 = document.createParagraph();
para1.setAlignment(ParagraphAlignment.BOTH);
String string1 = convertTextFileToString(paragraph1);
XWPFRun para1Run = para1.createRun();
para1Run.setText(string1); | XWPFParagraph para2 = document.createParagraph();
para2.setAlignment(ParagraphAlignment.RIGHT);
String string2 = convertTextFileToString(paragraph2);
XWPFRun para2Run = para2.createRun();
para2Run.setText(string2);
para2Run.setItalic(true);
XWPFParagraph para3 = document.createParagraph();
para3.setAlignment(ParagraphAlignment.LEFT);
String string3 = convertTextFileToString(paragraph3);
XWPFRun para3Run = para3.createRun();
para3Run.setText(string3);
FileOutputStream out = new FileOutputStream(output);
document.write(out);
out.close();
document.close();
}
public String convertTextFileToString(String fileName) {
try (Stream<String> stream = Files.lines(Paths.get(ClassLoader.getSystemResource(fileName).toURI()))) {
return stream.collect(Collectors.joining(" "));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
return null;
}
} | repos\tutorials-master\apache-poi\src\main\java\com\baeldung\word\WordDocument.java | 1 |
请完成以下Java代码 | public class Data {
private String packet;
// True if receiver should wait
// False if sender should wait
private boolean transfer = true;
public synchronized String receive() {
while (transfer) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread()
.interrupt();
System.err.println("Thread Interrupted");
}
}
transfer = true;
String returnPacket = packet; | notifyAll();
return returnPacket;
}
public synchronized void send(String packet) {
while (!transfer) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread()
.interrupt();
System.err.println("Thread Interrupted");
}
}
transfer = false;
this.packet = packet;
notifyAll();
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-simple\src\main\java\com\baeldung\concurrent\waitandnotify\Data.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setMyAccessDecisionManager(MyAccessDecisionManager myAccessDecisionManager) {
super.setAccessDecisionManager(myAccessDecisionManager);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
public void invoke(FilterInvocation fi) throws IOException, ServletException {
//fi里面有一个被拦截的url
//里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
//再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
//执行下一个拦截器
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null); | }
}
@Override
public void destroy() {
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
} | repos\springBoot-master\springboot-SpringSecurity1\src\main\java\com\us\example\service\MyFilterSecurityInterceptor.java | 2 |
请完成以下Java代码 | public DataFormatException unableToParseInput(Exception e) {
return new DataFormatException(exceptionMessage("006", "Unable to parse input into DOM document"), e);
}
public DataFormatException unableToCreateTransformer(Exception cause) {
return new DataFormatException(exceptionMessage("007", "Unable to create a transformer to write element"), cause);
}
public DataFormatException unableToTransformElement(Node element, Exception cause) {
return new DataFormatException(exceptionMessage("008", "Unable to transform element '{}:{}'", element.getNamespaceURI(), element.getNodeName()), cause);
}
public DataFormatException unableToWriteInput(Object parameter, Throwable cause) {
return new DataFormatException(exceptionMessage("009", "Unable to write object '{}' to xml element", parameter.toString()), cause);
}
public DataFormatException unableToDeserialize(Object node, String canonicalClassName, Throwable cause) {
return new DataFormatException(
exceptionMessage("010", "Cannot deserialize '{}...' to java class '{}'", node.toString(), canonicalClassName), cause);
} | public DataFormatException unableToCreateMarshaller(Throwable cause) {
return new DataFormatException(exceptionMessage("011", "Cannot create marshaller"), cause);
}
public DataFormatException unableToCreateContext(Throwable cause) {
return new DataFormatException(exceptionMessage("012", "Cannot create context"), cause);
}
public DataFormatException unableToCreateUnmarshaller(Throwable cause) {
return new DataFormatException(exceptionMessage("013", "Cannot create unmarshaller"), cause);
}
public DataFormatException classNotFound(String classname, ClassNotFoundException cause) {
return new DataFormatException(exceptionMessage("014", "Class {} not found ", classname), cause);
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\xml\DomXmlLogger.java | 1 |
请完成以下Java代码 | public void setInvoiceDocumentNo (java.lang.String InvoiceDocumentNo)
{
set_Value (COLUMNNAME_InvoiceDocumentNo, InvoiceDocumentNo);
}
/** Get Invoice Document No.
@return Document Number of the Invoice
*/
@Override
public java.lang.String getInvoiceDocumentNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_InvoiceDocumentNo);
}
/** Set Zahlungseingang.
@param IsReceipt
Dies ist eine Verkaufs-Transaktion (Zahlungseingang)
*/
@Override
public void setIsReceipt (boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, Boolean.valueOf(IsReceipt));
}
/** Get Zahlungseingang.
@return Dies ist eine Verkaufs-Transaktion (Zahlungseingang)
*/
@Override
public boolean isReceipt ()
{
Object oo = get_Value(COLUMNNAME_IsReceipt);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Zahlungsbetrag.
@param PayAmt
Gezahlter Betrag
*/
@Override
public void setPayAmt (BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
/** Get Zahlungsbetrag.
@return Gezahlter Betrag
*/
@Override
public BigDecimal getPayAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
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 */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
@Override
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;
}
/** Set Transaction Code.
@param TransactionCode
The transaction code represents the search definition
*/
@Override
public void setTransactionCode (java.lang.String TransactionCode)
{
set_Value (COLUMNNAME_TransactionCode, TransactionCode);
}
/** Get Transaction Code.
@return The transaction code represents the search definition
*/
@Override
public java.lang.String getTransactionCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_I_Datev_Payment.java | 1 |
请完成以下Java代码 | private PrintFormatId getBPPrintFormatOrNull(
@Nullable final BPartnerId bpartnerId,
@Nullable final DocTypeId docTypeId,
@NonNull final AdTableId adTableId)
{
if (bpartnerId == null)
{
return null;
}
final BPartnerPrintFormatMap bpPrintFormats = util.getBPartnerPrintFormats(bpartnerId);
// By DocType
if (docTypeId != null)
{
final PrintFormatId printFormatId = bpPrintFormats.getPrintFormatIdByDocTypeId(docTypeId).orElse(null);
if (printFormatId != null) | {
return printFormatId;
}
}
// By Table
return bpPrintFormats.getFirstByTableId(adTableId).orElse(null);
}
@Nullable
private PrintFormatId getDocTypePrintFormatOrNull(@Nullable final I_C_DocType docType)
{
return docType != null
? PrintFormatId.ofRepoIdOrNull(docType.getAD_PrintFormat_ID())
: null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\FallbackDocumentReportAdvisor.java | 1 |
请完成以下Java代码 | public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress2() {
return address2;
} | public void setAddress2(String address2) {
this.address2 = address2;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ContactBased.java | 1 |
请完成以下Java代码 | 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 setHeight(final @Nullable BigDecimal Height)
{
set_Value(COLUMNNAME_Height, Height);
}
@Override
public BigDecimal getHeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Height);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setLength(final @Nullable BigDecimal Length)
{
set_Value(COLUMNNAME_Length, Length);
}
@Override
public BigDecimal getLength()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Length);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMaxVolume(final BigDecimal MaxVolume)
{
set_Value(COLUMNNAME_MaxVolume, MaxVolume);
}
@Override
public BigDecimal getMaxVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxVolume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMaxWeight(final BigDecimal MaxWeight)
{
set_Value(COLUMNNAME_MaxWeight, MaxWeight);
}
@Override
public BigDecimal getMaxWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_PackagingContainer_ID(final int M_PackagingContainer_ID)
{
if (M_PackagingContainer_ID < 1)
set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, null);
else
set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, M_PackagingContainer_ID);
}
@Override
public int getM_PackagingContainer_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PackagingContainer_ID);
} | @Override
public void setM_Product_ID(final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value(COLUMNNAME_M_Product_ID, null);
else
set_Value(COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName(final java.lang.String Name)
{
set_Value(COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue(final @Nullable java.lang.String Value)
{
set_Value(COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWidth(final @Nullable BigDecimal Width)
{
set_Value(COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
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_M_PackagingContainer.java | 1 |
请完成以下Java代码 | public int getEDI_cctop_invoic_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID);
}
@Override
public void setISO_Code (final @Nullable java.lang.String ISO_Code)
{
set_Value (COLUMNNAME_ISO_Code, ISO_Code);
}
@Override
public java.lang.String getISO_Code()
{
return get_ValueAsString(COLUMNNAME_ISO_Code);
}
@Override
public void setnetdate (final @Nullable java.sql.Timestamp netdate)
{
set_Value (COLUMNNAME_netdate, netdate);
}
@Override
public java.sql.Timestamp getnetdate()
{
return get_ValueAsTimestamp(COLUMNNAME_netdate);
}
@Override
public void setNetDays (final int NetDays)
{
set_Value (COLUMNNAME_NetDays, NetDays);
}
@Override
public int getNetDays()
{
return get_ValueAsInt(COLUMNNAME_NetDays);
}
@Override | public void setsinglevat (final @Nullable BigDecimal singlevat)
{
set_Value (COLUMNNAME_singlevat, singlevat);
}
@Override
public BigDecimal getsinglevat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_singlevat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void settaxfree (final boolean taxfree)
{
set_Value (COLUMNNAME_taxfree, taxfree);
}
@Override
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_120_v.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private PathPatternRequestMatcher.Builder constructRequestMatcherBuilder(ApplicationContext context) {
PathPatternRequestMatcherBuilderFactoryBean requestMatcherBuilder = new PathPatternRequestMatcherBuilderFactoryBean();
requestMatcherBuilder.setApplicationContext(context);
requestMatcherBuilder.setBeanFactory(context.getAutowireCapableBeanFactory());
requestMatcherBuilder.setBeanName(requestMatcherBuilder.toString());
return ThrowingSupplier.of(requestMatcherBuilder::getObject).get();
}
static class DefaultPasswordEncoderAuthenticationManagerBuilder extends AuthenticationManagerBuilder {
private PasswordEncoder defaultPasswordEncoder;
/**
* Creates a new instance
* @param objectPostProcessor the {@link ObjectPostProcessor} instance to use.
*/
DefaultPasswordEncoderAuthenticationManagerBuilder(ObjectPostProcessor<Object> objectPostProcessor,
PasswordEncoder defaultPasswordEncoder) {
super(objectPostProcessor);
this.defaultPasswordEncoder = defaultPasswordEncoder;
}
@Override
public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication() {
return super.inMemoryAuthentication().passwordEncoder(this.defaultPasswordEncoder);
}
@Override
public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication() {
return super.jdbcAuthentication().passwordEncoder(this.defaultPasswordEncoder);
}
@Override
public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder, T> userDetailsService(
T userDetailsService) {
return super.userDetailsService(userDetailsService).passwordEncoder(this.defaultPasswordEncoder);
}
}
static class LazyPasswordEncoder implements PasswordEncoder {
private ApplicationContext applicationContext;
private PasswordEncoder passwordEncoder;
LazyPasswordEncoder(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public String encode(CharSequence rawPassword) {
return getPasswordEncoder().encode(rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) { | return getPasswordEncoder().matches(rawPassword, encodedPassword);
}
@Override
public boolean upgradeEncoding(String encodedPassword) {
return getPasswordEncoder().upgradeEncoding(encodedPassword);
}
private PasswordEncoder getPasswordEncoder() {
if (this.passwordEncoder != null) {
return this.passwordEncoder;
}
this.passwordEncoder = this.applicationContext.getBeanProvider(PasswordEncoder.class)
.getIfUnique(PasswordEncoderFactories::createDelegatingPasswordEncoder);
return this.passwordEncoder;
}
@Override
public String toString() {
return getPasswordEncoder().toString();
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\HttpSecurityConfiguration.java | 2 |
请完成以下Java代码 | public class X_M_ProductGroup_Product extends org.compiere.model.PO implements I_M_ProductGroup_Product, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -2013704372L;
/** Standard Constructor */
public X_M_ProductGroup_Product (final Properties ctx, final int M_ProductGroup_Product_ID, @Nullable final String trxName)
{
super (ctx, M_ProductGroup_Product_ID, trxName);
}
/** Load Constructor */
public X_M_ProductGroup_Product (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public de.metas.invoicecandidate.model.I_M_ProductGroup getM_ProductGroup()
{
return get_ValueAsPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class);
}
@Override
public void setM_ProductGroup(final de.metas.invoicecandidate.model.I_M_ProductGroup M_ProductGroup)
{
set_ValueFromPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class, M_ProductGroup); | }
@Override
public void setM_ProductGroup_ID (final int M_ProductGroup_ID)
{
if (M_ProductGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID);
}
@Override
public int getM_ProductGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_ID);
}
@Override
public void setM_ProductGroup_Product_ID (final int M_ProductGroup_Product_ID)
{
if (M_ProductGroup_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_Product_ID, M_ProductGroup_Product_ID);
}
@Override
public int getM_ProductGroup_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_Product_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_M_ProductGroup_Product.java | 1 |
请完成以下Java代码 | public void setCareDegree(@Nullable final BigDecimal careDegree)
{
this.careDegree = careDegree;
this.careDegreeSet = true;
}
public void setCreatedAt(@Nullable final Instant createdAt)
{
this.createdAt = createdAt;
this.createdAtSet = true;
}
public void setCreatedByIdentifier(@Nullable final String createdByIdentifier)
{
this.createdByIdentifier = createdByIdentifier; | this.createdByIdentifierSet = true;
}
public void setUpdatedAt(@Nullable final Instant updatedAt)
{
this.updatedAt = updatedAt;
this.updatedAtSet = true;
}
public void setUpdateByIdentifier(@Nullable final String updateByIdentifier)
{
this.updateByIdentifier = updateByIdentifier;
this.updateByIdentifierSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaPatient.java | 1 |
请完成以下Java代码 | public class ManagedAsyncJobExecutor extends DefaultAsyncJobExecutor {
private static Logger log = LoggerFactory.getLogger(ManagedAsyncJobExecutor.class);
protected ManagedThreadFactory threadFactory;
public ManagedThreadFactory getThreadFactory() {
return threadFactory;
}
public void setThreadFactory(ManagedThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
protected void initAsyncJobExecutionThreadPool() {
if (threadFactory == null) {
log.warn("A managed thread factory was not found, falling back to self-managed threads");
super.initAsyncJobExecutionThreadPool();
} else {
if (threadPoolQueue == null) {
log.info("Creating thread pool queue of size {}", queueSize);
threadPoolQueue = new ArrayBlockingQueue<Runnable>(queueSize);
} | if (executorService == null) {
log.info(
"Creating executor service with corePoolSize {}, maxPoolSize {} and keepAliveTime {}",
corePoolSize,
maxPoolSize,
keepAliveTime
);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
keepAliveTime,
TimeUnit.MILLISECONDS,
threadPoolQueue,
threadFactory
);
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executorService = threadPoolExecutor;
}
startJobAcquisitionThread();
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\ManagedAsyncJobExecutor.java | 1 |
请完成以下Java代码 | public Optional<BPGroup> getDefaultGroup(@NonNull final ClientAndOrgId clientAndOrgId)
{
final I_C_BP_Group groupRecord = Services.get(IBPGroupDAO.class)
.getDefaultByClientOrgId(clientAndOrgId);
return ofRecord(groupRecord);
}
private Optional<BPGroup> ofRecord(@Nullable final I_C_BP_Group groupRecord)
{
if (groupRecord == null)
{
return Optional.empty();
}
return Optional.of(BPGroup.builder()
.id(BPGroupId.ofRepoId(groupRecord.getC_BP_Group_ID()))
.orgId(OrgId.ofRepoIdOrAny(groupRecord.getAD_Org_ID()))
.value(groupRecord.getValue())
.name(groupRecord.getName()) | .build());
}
public BPGroupId save(@NonNull final BPGroup bpGroup)
{
final I_C_BP_Group groupRecord = loadOrNew(bpGroup.getId(), I_C_BP_Group.class);
groupRecord.setAD_Org_ID(bpGroup.getOrgId().getRepoId());
groupRecord.setName(bpGroup.getName());
groupRecord.setValue(bpGroup.getValue());
saveRecord(groupRecord);
return BPGroupId.ofRepoId(groupRecord.getC_BP_Group_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPGroupRepository.java | 1 |
请完成以下Java代码 | public Action getCopyPasteAction(final CopyPasteActionType actionType)
{
return copyPasteActions.get(actionType);
}
@Override
public void putCopyPasteAction(final CopyPasteActionType actionType, final Action action, final KeyStroke keyStroke)
{
// do nothing because we already provided the right action to be used
// comboBoxCopyPasteSupport.putCopyPasteAction(actionType, action, keyStroke);
// textFieldCopyPasteSupport.putCopyPasteAction(actionType, action, keyStroke);
}
@Override
public boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType)
{
if (activeCopyPasteSupport == null)
{
return false;
}
return activeCopyPasteSupport.isCopyPasteActionAllowed(actionType);
}
private class CopyPasteActionProxy extends AbstractAction
{
private static final long serialVersionUID = 1L;
private final CopyPasteActionType actionType;
public CopyPasteActionProxy(final CopyPasteActionType actionType)
{
super();
this.actionType = actionType;
}
@Override
public void actionPerformed(final ActionEvent e)
{
final ICopyPasteSupportEditor copyPasteSupport = getActiveCopyPasteEditor();
if (copyPasteSupport == null)
{
return;
}
copyPasteSupport.executeCopyPasteAction(actionType);
}
private final ICopyPasteSupportEditor getActiveCopyPasteEditor()
{
return activeCopyPasteSupport;
}
}
/**
* Action implementation which forwards a given {@link CopyPasteActionType} to {@link ICopyPasteSupportEditor}.
*
* To be used only when the component does not already have a registered handler for this action type.
* | * @author tsa
*
*/
private static class CopyPasteAction extends AbstractAction
{
private static final Action getCreateAction(final ICopyPasteSupportEditor copyPasteSupport, final CopyPasteActionType actionType)
{
Action action = copyPasteSupport.getCopyPasteAction(actionType);
if (action == null)
{
action = new CopyPasteAction(copyPasteSupport, actionType);
}
copyPasteSupport.putCopyPasteAction(actionType, action, actionType.getKeyStroke());
return action;
}
private static final long serialVersionUID = 1L;
private final ICopyPasteSupportEditor copyPasteSupport;
private final CopyPasteActionType actionType;
public CopyPasteAction(final ICopyPasteSupportEditor copyPasteSupport, final CopyPasteActionType actionType)
{
super();
this.copyPasteSupport = copyPasteSupport;
this.actionType = actionType;
}
@Override
public void actionPerformed(final ActionEvent e)
{
copyPasteSupport.executeCopyPasteAction(actionType);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookupCopyPasteSupportEditor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ApplicationListener<SessionUnsubscribeEvent> sessionUnsubscribeListener() {return this::onSessionUnsubribeEvent;}
@Bean
public ApplicationListener<SessionDisconnectEvent> sessionDisconnectListener() {return this::onSessionDisconnectEvent;}
private void onSessionSubscribeEvent(final SessionSubscribeEvent event)
{
final WebsocketSubscriptionId subscriptionId = extractUniqueSubscriptionId(event);
final WebsocketTopicName topicName = extractTopicName(event);
final WebsocketHeaders headers = WebsocketHeaders.of(extractNativeHeaders(event));
activeSubscriptionsIndex.addSubscription(subscriptionId, topicName);
websocketProducersRegistry.onTopicSubscribed(subscriptionId, topicName, headers);
logger.debug("Subscribed to topicName={} [ subscriptionId={} ]", topicName, subscriptionId);
}
private void onSessionUnsubribeEvent(final SessionUnsubscribeEvent event)
{
final WebsocketSubscriptionId subscriptionId = extractUniqueSubscriptionId(event);
final WebsocketTopicName topicName = activeSubscriptionsIndex.removeSubscriptionAndGetTopicName(subscriptionId);
websocketProducersRegistry.onTopicUnsubscribed(subscriptionId, topicName);
logger.debug("Unsubscribed from topicName={} [ subscriptionId={} ]", topicName, subscriptionId);
}
private void onSessionDisconnectEvent(final SessionDisconnectEvent event)
{
final WebsocketSessionId sessionId = WebsocketSessionId.ofString(event.getSessionId());
final Set<WebsocketTopicName> topicNames = activeSubscriptionsIndex.removeSessionAndGetTopicNames(sessionId);
websocketProducersRegistry.onSessionDisconnect(sessionId, topicNames); | logger.debug("Disconnected from topicName={} [ sessionId={} ]", topicNames, sessionId);
}
private static WebsocketTopicName extractTopicName(final AbstractSubProtocolEvent event)
{
return WebsocketTopicName.ofString(SimpMessageHeaderAccessor.getDestination(event.getMessage().getHeaders()));
}
private static WebsocketSubscriptionId extractUniqueSubscriptionId(final AbstractSubProtocolEvent event)
{
final MessageHeaders headers = event.getMessage().getHeaders();
final WebsocketSessionId sessionId = WebsocketSessionId.ofString(SimpMessageHeaderAccessor.getSessionId(headers));
final String simpSubscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
return WebsocketSubscriptionId.of(sessionId, Objects.requireNonNull(simpSubscriptionId, "simpSubscriptionId"));
}
@NonNull
private static Map<String, List<String>> extractNativeHeaders(@NonNull final AbstractSubProtocolEvent event)
{
final Object nativeHeaders = event.getMessage().getHeaders().get("nativeHeaders");
return Optional.ofNullable(nativeHeaders)
.filter(headers -> headers instanceof Map)
.filter(headers -> !((Map<?, ?>)headers).isEmpty())
.map(headers -> (Map<String, List<String>>)headers)
.map(ImmutableMap::copyOf)
.orElseGet(ImmutableMap::of);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducerConfiguration.java | 2 |
请完成以下Java代码 | public class OrServerWebExchangeMatcher implements ServerWebExchangeMatcher {
private static final Log logger = LogFactory.getLog(OrServerWebExchangeMatcher.class);
private final List<ServerWebExchangeMatcher> matchers;
public OrServerWebExchangeMatcher(List<ServerWebExchangeMatcher> matchers) {
Assert.notEmpty(matchers, "matchers cannot be empty");
this.matchers = matchers;
}
public OrServerWebExchangeMatcher(ServerWebExchangeMatcher... matchers) {
this(Arrays.asList(matchers));
}
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) { | return Flux.fromIterable(this.matchers)
.doOnNext((matcher) -> logger.debug(LogMessage.format("Trying to match using %s", matcher)))
.flatMap((matcher) -> matcher.matches(exchange))
.filter(MatchResult::isMatch)
.next()
.switchIfEmpty(MatchResult.notMatch())
.doOnNext((matchResult) -> logger.debug(matchResult.isMatch() ? "matched" : "No matches found"));
}
@Override
public String toString() {
return "OrServerWebExchangeMatcher{matchers=" + this.matchers + '}';
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\OrServerWebExchangeMatcher.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.