instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public java.lang.String getWEBUI_NameNewBreadcrumb ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNewBreadcrumb);
}
/**
* WidgetSize AD_Reference_ID=540724
* Reference name: WidgetSize_WEBUI
*/
public static final int WIDGETSIZE_AD_Reference_ID=540724;
/** Small = S */
public static final String WIDGETSIZE_Small = "S";
/** Medium = M */
public static final String WIDGETSIZE_Medium = "M";
/** Large = L */
public static final String WIDGETSIZE_Large = "L";
/** Set Widget size.
|
@param WidgetSize Widget size */
@Override
public void setWidgetSize (java.lang.String WidgetSize)
{
set_Value (COLUMNNAME_WidgetSize, WidgetSize);
}
/** Get Widget size.
@return Widget size */
@Override
public java.lang.String getWidgetSize ()
{
return (java.lang.String)get_Value(COLUMNNAME_WidgetSize);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Element.java
| 1
|
请完成以下Java代码
|
public static boolean isChildRecordFoundError(final Exception e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_foreign_key_violation);
}
return isErrorCode(e, 2292);
}
public static boolean isForeignKeyViolation(final Throwable e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_foreign_key_violation);
}
// NOTE: on oracle there are many ORA-codes for foreign key violation
// below i am adding a few of them, but pls note that it's not tested at all
return isErrorCode(e, 2291) // integrity constraint (string.string) violated - parent key not found
|| isErrorCode(e, 2292) // integrity constraint (string.string) violated - child record found
//
;
}
/**
* Check if "invalid identifier" exception (aka ORA-00904)
*
* @param e exception
*/
public static boolean isInvalidIdentifierError(final Exception e)
{
return isErrorCode(e, 904);
}
/**
* Check if "invalid username/password" exception (aka ORA-01017)
*
* @param e exception
*/
public static boolean isInvalidUserPassError(final Exception e)
{
return isErrorCode(e, 1017);
}
/**
* Check if "time out" exception (aka ORA-01013)
|
*/
public static boolean isTimeout(final Exception e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_query_canceled);
}
return isErrorCode(e, 1013);
}
/**
* Task 08353
*/
public static boolean isDeadLockDetected(final Throwable e)
{
if (DB.isPostgreSQL())
{
return isSQLState(e, PG_SQLSTATE_deadlock_detected);
}
return isErrorCode(e, 40001); // not tested for oracle, just did a brief googling
}
} // DBException
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\DBException.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static List<Node> asNodes(@Nullable List<String> nodes) {
if (nodes == null) {
return Collections.emptyList();
}
return nodes.stream().map(PropertiesDataRedisConnectionDetails::asNode).toList();
}
private static Node asNode(String node) {
int portSeparatorIndex = node.lastIndexOf(':');
String host = node.substring(0, portSeparatorIndex);
int port = Integer.parseInt(node.substring(portSeparatorIndex + 1));
return new Node(host, port);
}
/**
* {@link Cluster} implementation backed by properties.
*/
private static class PropertiesCluster implements Cluster {
private final List<Node> nodes;
PropertiesCluster(DataRedisProperties.Cluster properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link MasterReplica} implementation backed by properties.
*/
private static class PropertiesMasterReplica implements MasterReplica {
private final List<Node> nodes;
PropertiesMasterReplica(DataRedisProperties.Masterreplica properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link Sentinel} implementation backed by properties.
*/
private static class PropertiesSentinel implements Sentinel {
private final int database;
|
private final DataRedisProperties.Sentinel properties;
PropertiesSentinel(int database, DataRedisProperties.Sentinel properties) {
this.database = database;
this.properties = properties;
}
@Override
public int getDatabase() {
return this.database;
}
@Override
public String getMaster() {
String master = this.properties.getMaster();
Assert.state(master != null, "'master' must not be null");
return master;
}
@Override
public List<Node> getNodes() {
return asNodes(this.properties.getNodes());
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
}
|
repos\spring-boot-main\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\PropertiesDataRedisConnectionDetails.java
| 2
|
请完成以下Java代码
|
public static String sortByValueForQueryEntityRelationCondition(QueryEntityRelationCondition relationCondition) {
QueryProperty property = relationCondition.getProperty();
QueryProperty comparisonProperty = relationCondition.getComparisonProperty();
if (VariableInstanceQueryProperty.EXECUTION_ID.equals(property) && TaskQueryProperty.PROCESS_INSTANCE_ID.equals(comparisonProperty)) {
return SORT_BY_PROCESS_VARIABLE;
}
else if (VariableInstanceQueryProperty.EXECUTION_ID.equals(property) && TaskQueryProperty.EXECUTION_ID.equals(comparisonProperty)) {
return SORT_BY_EXECUTION_VARIABLE;
}
else if (VariableInstanceQueryProperty.TASK_ID.equals(property) && TaskQueryProperty.TASK_ID.equals(comparisonProperty)) {
return SORT_BY_TASK_VARIABLE;
}
else if (VariableInstanceQueryProperty.CASE_EXECUTION_ID.equals(property) && TaskQueryProperty.CASE_INSTANCE_ID.equals(comparisonProperty)) {
return SORT_BY_CASE_INSTANCE_VARIABLE;
}
else if (VariableInstanceQueryProperty.CASE_EXECUTION_ID.equals(property) && TaskQueryProperty.CASE_EXECUTION_ID.equals(comparisonProperty)) {
return SORT_BY_CASE_EXECUTION_VARIABLE;
}
else {
throw new RestException("Unknown relation condition for task query with query property " + property + " and comparison property " + comparisonProperty);
}
}
|
public static Map<String,Object> sortParametersForVariableOrderProperty(VariableOrderProperty variableOrderProperty) {
Map<String, Object> parameters = new HashMap<>();
for (QueryEntityRelationCondition relationCondition : variableOrderProperty.getRelationConditions()) {
QueryProperty property = relationCondition.getProperty();
if (VariableInstanceQueryProperty.VARIABLE_NAME.equals(property)) {
parameters.put(SORT_PARAMETERS_VARIABLE_NAME, relationCondition.getScalarValue());
}
else if (VariableInstanceQueryProperty.VARIABLE_TYPE.equals(property)) {
String type = VariableValueDto.toRestApiTypeName((String) relationCondition.getScalarValue());
parameters.put(SORT_PARAMETERS_VALUE_TYPE, type);
}
}
return parameters;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\TaskQueryDto.java
| 1
|
请完成以下Java代码
|
public class AD_Org
{
public static final transient AD_Org instance = new AD_Org();
private final transient Logger logger = LogManager.getLogger(getClass());
@ModelChange(timings = ModelValidator.TYPE_AFTER_NEW)
public void addAccessToRolesWithAutomaticMaintenance(final I_AD_Org org)
{
final ClientId orgClientId = ClientId.ofRepoId(org.getAD_Client_ID());
int orgAccessCreatedCounter = 0;
final IUserRolePermissionsDAO permissionsDAO = Services.get(IUserRolePermissionsDAO.class);
for (final Role role : Services.get(IRoleDAO.class).retrieveAllRolesWithAutoMaintenance())
{
// Don't create org access for system role
if (role.getId().isSystem())
{
continue;
}
// Don't create org access for roles which are not defined on system level nor on org's AD_Client_ID level
final ClientId roleClientId = role.getClientId();
if (!roleClientId.equals(orgClientId)
&& !roleClientId.isSystem())
{
|
continue;
}
final OrgId orgId = OrgId.ofRepoId(org.getAD_Org_ID());
permissionsDAO.createOrgAccess(role.getId(), orgId);
orgAccessCreatedCounter++;
}
logger.info("{} - created #{} role org access entries", org, orgAccessCreatedCounter);
// Reset role permissions, just to make sure we are on the safe side
// NOTE: not needed shall be triggered automatically
// if (orgAccessCreatedCounter > 0)
// {
// Services.get(IUserRolePermissionsDAO.class).resetCacheAfterTrxCommit();
// }
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\model\interceptor\AD_Org.java
| 1
|
请完成以下Java代码
|
private void ensureYesNoTypeExists()
{
if (refTypes.containsKey(XSD_TYPE_YES_NO))
{
return; // nothing to do
}
// 02585
final Element e = document.createElement(XSD_SIMPLE_TYPE);
e.setAttribute(XSD_NAME, XSD_TYPE_YES_NO);
final Element e2 = document.createElement(XSD_RESTRICTION);
e2.setAttribute("base", "xsd:string");
e.appendChild(e2);
final Element e3 = document.createElement("xsd:pattern");
e3.setAttribute("value", "[YN]");
e2.appendChild(e3);
rootElement.appendChild(e);
refTypes.put(XSD_TYPE_YES_NO, e);
}
public static void validateXML(final File xmlFile, final File schemaFile) throws SAXException, IOException
{
System.out.println("Validating:");
System.out.println("Schema: " + schemaFile);
System.out.println("Test XML File: " + xmlFile);
final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
final Schema schema = factory.newSchema(schemaFile);
final Validator validator = schema.newValidator();
final Source source = new StreamSource(xmlFile);
validator.validate(source);
System.out.println("File " + xmlFile + " is valid");
}
/**
|
*
* @param line
* @param defaultDisplayType
* @return
*/
private int getDisplayType(final I_EXP_FormatLine line, final int defaultDisplayType)
{
if (line.getAD_Reference_Override_ID() > 0)
{
return line.getAD_Reference_Override_ID();
}
final I_AD_Column column = line.getAD_Column();
if (column == null || column.getAD_Column_ID() <= 0)
{
return defaultDisplayType;
}
final int displayType = column.getAD_Reference_ID();
if (displayType <= 0)
{
return defaultDisplayType;
}
return displayType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\esb\util\CanonicalXSDGenerator.java
| 1
|
请完成以下Java代码
|
public boolean isProcessed()
{
return false;
}
@Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
|
}
public DocumentZoomIntoInfo getZoomIntoInfo(@NonNull final String fieldName)
{
if (FIELDNAME_M_Product_ID.equals(fieldName))
{
return lookups.getZoomInto(productId);
}
else
{
throw new AdempiereException("Field " + fieldName + " does not support zoom info");
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BaseMailHostServerConfiguration implements MailHostServerConfiguration {
protected String host;
protected int port = 25;
protected Transport transport = Transport.SMTP;
protected boolean startTlsEnabled;
protected String user;
protected String password;
@Override
public String host() {
return host;
}
public void setHost(String host) {
this.host = host;
}
@Override
public int port() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Override
public Transport transport() {
return transport;
}
public void setTransport(Transport transport) {
this.transport = transport;
}
|
@Override
public boolean isStartTlsEnabled() {
return startTlsEnabled;
}
public void setStartTlsEnabled(boolean startTlsEnabled) {
this.startTlsEnabled = startTlsEnabled;
}
@Override
public String user() {
return user;
}
public void setUser(String user) {
this.user = user;
}
@Override
public String password() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
repos\flowable-engine-main\modules\flowable-mail\src\main\java\org\flowable\mail\common\impl\BaseMailHostServerConfiguration.java
| 2
|
请完成以下Java代码
|
public class JuelElProvider implements ElProvider {
protected final ExpressionFactoryImpl factory;
protected final JuelElContextFactory elContextFactory;
protected final ELContext parsingElContext;
public JuelElProvider() {
this(new ExpressionFactoryImpl(), new JuelElContextFactory(createDefaultResolver()));
}
public JuelElProvider(ExpressionFactoryImpl expressionFactory, JuelElContextFactory elContextFactory) {
this.factory = expressionFactory;
this.elContextFactory = elContextFactory;
this.parsingElContext = createDefaultParsingElContext();
}
protected SimpleContext createDefaultParsingElContext() {
return new SimpleContext();
}
public ElExpression createExpression(String expression) {
TreeValueExpression juelExpr = factory.createValueExpression(parsingElContext, expression, Object.class);
return new JuelExpression(juelExpr, elContextFactory);
}
public ExpressionFactoryImpl getFactory() {
return factory;
}
|
public JuelElContextFactory getElContextFactory() {
return elContextFactory;
}
public ELContext getParsingElContext() {
return parsingElContext;
}
protected static ELResolver createDefaultResolver() {
CompositeELResolver resolver = new CompositeELResolver();
resolver.add(new VariableContextElResolver());
resolver.add(new ArrayELResolver(true));
resolver.add(new ListELResolver(true));
resolver.add(new MapELResolver(true));
resolver.add(new ResourceBundleELResolver());
resolver.add(new BeanELResolver());
return resolver;
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\el\JuelElProvider.java
| 1
|
请完成以下Java代码
|
private JwtEncoder getJwsEncoder() {
return this.jwsEncoder;
}
private JWK getJwk() {
return this.jwk;
}
}
/**
* A context that holds client authentication-specific state and is used by
* {@link NimbusJwtClientAuthenticationParametersConverter} when attempting to
* customize the JSON Web Token (JWS) client assertion.
*
* @param <T> the type of {@link AbstractOAuth2AuthorizationGrantRequest}
* @since 5.7
*/
public static final class JwtClientAuthenticationContext<T extends AbstractOAuth2AuthorizationGrantRequest> {
private final T authorizationGrantRequest;
private final JwsHeader.Builder headers;
private final JwtClaimsSet.Builder claims;
private JwtClientAuthenticationContext(T authorizationGrantRequest, JwsHeader.Builder headers,
JwtClaimsSet.Builder claims) {
this.authorizationGrantRequest = authorizationGrantRequest;
this.headers = headers;
this.claims = claims;
}
/**
* Returns the {@link AbstractOAuth2AuthorizationGrantRequest authorization grant
* request}.
* @return the {@link AbstractOAuth2AuthorizationGrantRequest authorization grant
* request}
*/
public T getAuthorizationGrantRequest() {
return this.authorizationGrantRequest;
}
/**
* Returns the {@link JwsHeader.Builder} to be used to customize headers of the
* JSON Web Token (JWS).
|
* @return the {@link JwsHeader.Builder} to be used to customize headers of the
* JSON Web Token (JWS)
*/
public JwsHeader.Builder getHeaders() {
return this.headers;
}
/**
* Returns the {@link JwtClaimsSet.Builder} to be used to customize claims of the
* JSON Web Token (JWS).
* @return the {@link JwtClaimsSet.Builder} to be used to customize claims of the
* JSON Web Token (JWS)
*/
public JwtClaimsSet.Builder getClaims() {
return this.claims;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\NimbusJwtClientAuthenticationParametersConverter.java
| 1
|
请完成以下Java代码
|
public MovementUserNotificationsProducer notifyProcessed(final Collection<? extends I_M_Movement> movements)
{
if (movements == null || movements.isEmpty())
{
return this;
}
postNotifications(movements.stream()
.map(this::createUserNotification)
.collect(ImmutableList.toImmutableList()));
return this;
}
public final MovementUserNotificationsProducer notifyProcessed(@NonNull final I_M_Movement movement)
{
notifyProcessed(ImmutableList.of(movement));
return this;
}
private UserNotificationRequest createUserNotification(@NonNull final I_M_Movement movement)
{
final UserId recipientUserId = getNotificationRecipientUserId(movement);
final TableRecordReference movementRef = TableRecordReference.of(movement);
return newUserNotificationRequest()
.recipientUserId(recipientUserId)
.contentADMessage(MSG_Event_MovementGenerated)
.contentADMessageParam(movementRef)
.targetAction(TargetRecordAction.of(movementRef))
.build();
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(USER_NOTIFICATIONS_TOPIC);
}
private UserId getNotificationRecipientUserId(final I_M_Movement movement)
{
//
// In case of reversal i think we shall notify the current user too
final DocStatus docStatus = DocStatus.ofCode(movement.getDocStatus());
|
if (docStatus.isReversedOrVoided())
{
final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user
if (currentUserId > 0)
{
return UserId.ofRepoId(currentUserId);
}
return UserId.ofRepoId(movement.getUpdatedBy()); // last updated
}
//
// Fallback: notify only the creator
else
{
return UserId.ofRepoId(movement.getCreatedBy());
}
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
notificationBL.sendAfterCommit(notifications);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\movement\event\MovementUserNotificationsProducer.java
| 1
|
请完成以下Java代码
|
public class SimpleFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(SimpleFilter.class);
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
|
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL()
.toString()));
return null;
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-security\auth-client\src\main\java\com\baeldung\filters\SimpleFilter.java
| 1
|
请完成以下Java代码
|
public class SysUserDepPost implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键id")
private String id;
/**
* 用户id
*/
@Schema(description = "用户id")
private String userId;
/**
* 部门岗位id
*/
@Schema(description = "部门岗位id")
private String depId;
/**
* 创建人
*/
@Schema(description = "创建人")
private String createBy;
/**
* 创建时间
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "创建时间")
private Date createTime;
|
/**
* 更新人
*/
@Schema(description = "更新人")
private String updateBy;
/**
* 更新时间
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "更新时间")
private Date updateTime;
/**
* 机构编码
*/
@Excel(name = "机构编码", width = 15)
@Schema(description = "机构编码")
private String orgCode;
public SysUserDepPost(String id, String userId, String depId) {
super();
this.id = id;
this.userId = userId;
this.depId = depId;
}
public SysUserDepPost(String userId, String departId) {
this.userId = userId;
this.depId = departId;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysUserDepPost.java
| 1
|
请完成以下Java代码
|
public IValidationRule build()
{
if (rules.isEmpty())
{
return NullValidationRule.instance;
}
else if (rules.size() == 1)
{
return rules.get(0);
}
else
{
return new CompositeValidationRule(this);
}
}
public Builder add(final IValidationRule rule)
{
add(rule, false);
return this;
}
public Builder addExploded(final IValidationRule rule)
{
add(rule, true);
return this;
}
private Builder add(final IValidationRule rule, final boolean explodeComposite)
{
// Don't add null rules
if (NullValidationRule.isNull(rule))
{
return this;
}
|
// Don't add if already exists
if (rules.contains(rule))
{
return this;
}
if (explodeComposite && rule instanceof CompositeValidationRule)
{
final CompositeValidationRule compositeRule = (CompositeValidationRule)rule;
addAll(compositeRule.getValidationRules(), true);
}
else
{
rules.add(rule);
}
return this;
}
private Builder addAll(final Collection<IValidationRule> rules)
{
return addAll(rules, false);
}
private Builder addAll(final Collection<IValidationRule> rules, final boolean explodeComposite)
{
rules.forEach(includedRule -> add(includedRule, explodeComposite));
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\CompositeValidationRule.java
| 1
|
请完成以下Java代码
|
public int getPageNo() {
return pageNo;
}
public int getPageSize() {
return pageSize;
}
public int getTotalCount() {
return totalCount;
}
public int getTotalPage() {
int totalPage = totalCount / pageSize;
if (totalCount % pageSize != 0 || totalPage == 0) {
totalPage++;
}
return totalPage;
}
public boolean isFirstPage() {
return pageNo <= 1;
}
public boolean isLastPage() {
return pageNo >= getTotalPage();
}
public int getNextPage() {
if (isLastPage()) {
return pageNo;
} else {
return pageNo + 1;
}
}
public int getPrePage() {
if (isFirstPage()) {
return pageNo;
} else {
return pageNo - 1;
|
}
}
protected int totalCount = 0;
protected int pageSize = 20;
protected int pageNo = 1;
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
protected int filterNo;
public int getFilterNo() {
return filterNo;
}
public void setFilterNo(int filterNo) {
this.filterNo = filterNo;
}
}
|
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\page\SimplePage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setMaxSentenceSize(int maxSentenceSize)
{
this.maxSentenceSize = maxSentenceSize;
}
public void incrementBufferHead()
{
if (bufferHead == maxSentenceSize)
bufferHead = -1;
else
bufferHead++;
}
public void setBufferHead(int bufferHead)
{
this.bufferHead = bufferHead;
}
@Override
public State clone()
{
State state = new State(arcs.length - 1);
state.stack = new ArrayDeque<Integer>(stack);
for (int dependent = 0; dependent < arcs.length; dependent++)
{
if (arcs[dependent] != null)
{
|
Edge head = arcs[dependent];
state.arcs[dependent] = head;
int h = head.headIndex;
if (rightMostArcs[h] != 0)
{
state.rightMostArcs[h] = rightMostArcs[h];
state.rightValency[h] = rightValency[h];
state.rightDepLabels[h] = rightDepLabels[h];
}
if (leftMostArcs[h] != 0)
{
state.leftMostArcs[h] = leftMostArcs[h];
state.leftValency[h] = leftValency[h];
state.leftDepLabels[h] = leftDepLabels[h];
}
}
}
state.rootIndex = rootIndex;
state.bufferHead = bufferHead;
state.maxSentenceSize = maxSentenceSize;
state.emptyFlag = emptyFlag;
return state;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\configuration\State.java
| 2
|
请完成以下Java代码
|
public void setMaxAgeInSeconds(long maxAgeInSeconds) {
Assert.isTrue(maxAgeInSeconds >= 0, () -> "maxAgeInSeconds must be non-negative. Got " + maxAgeInSeconds);
this.maxAgeInSeconds = maxAgeInSeconds;
updateHstsHeaderValue();
}
/**
* <p>
* If true, subdomains should be considered HSTS Hosts too. The default is true.
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.2">Section 6.1.2</a>
* for additional details.
* </p>
* @param includeSubDomains true to include subdomains, else false
*/
public void setIncludeSubDomains(boolean includeSubDomains) {
this.includeSubDomains = includeSubDomains;
updateHstsHeaderValue();
}
/**
* <p>
* If true, preload will be included in HSTS Header. The default is false.
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.2">Section 6.1.2</a>
* for additional details.
* </p>
* @param preload true to include preload, else false
* @since 5.2.0
*/
public void setPreload(boolean preload) {
this.preload = preload;
updateHstsHeaderValue();
}
|
private void updateHstsHeaderValue() {
String headerValue = "max-age=" + this.maxAgeInSeconds;
if (this.includeSubDomains) {
headerValue += " ; includeSubDomains";
}
if (this.preload) {
headerValue += " ; preload";
}
this.hstsHeaderValue = headerValue;
}
private static final class SecureRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
return request.isSecure();
}
@Override
public String toString() {
return "Is Secure";
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\HstsHeaderWriter.java
| 1
|
请完成以下Java代码
|
public Integer getManagerId() {
return managerId;
}
/**
* 设置 管理用户ID.
*
* @param managerId 管理用户ID.
*/
public void setManagerId(Integer managerId) {
this.managerId = managerId;
}
/**
* 获取 角色ID.
*
* @return 角色ID.
*/
public Integer getRoleId() {
return roleId;
}
/**
* 设置 角色ID.
*
* @param roleId 角色ID.
*/
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
/**
* 获取 创建时间.
*
* @return 创建时间.
*/
public Date getCreatedTime() {
|
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间.
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取 更新时间.
*
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
}
|
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\ManagerRole.java
| 1
|
请完成以下Java代码
|
public class FoodInfo {
@ExcelCellName("Category")
private String category; //food category
@ExcelCellName("Name")
private String name; // food name
@ExcelCellName("Measure")
private String measure;
@ExcelCellName("Calories")
private double calories; //amount of calories in kcal/measure
@Override
public String toString() {
return "FoodInfo{" + "category='" + category + '\'' + ", name='" + name + '\'' + ", measure='" + measure + '\'' + ", calories=" + calories + "} \n";
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public String getMeasure() {
return measure;
}
public void setMeasure(String measure) {
this.measure = measure;
}
public double getCalories() {
return calories;
}
public void setCalories(double calories) {
this.calories = calories;
}
}
|
repos\tutorials-master\apache-poi\src\main\java\com\baeldung\convert\exceldatatolist\FoodInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserAccessServiceImpl implements UserAccessService {
private static final Logger LOG = LoggerFactory.getLogger(UserAccessServiceImpl.class);
private final Map<String, UserData> sessions;
private final Map<String, UserData> users;
public UserAccessServiceImpl() {
this.sessions = new ConcurrentHashMap<>();
this.users = new HashMap<>();
this.users.put("bob", new UserData("bob", "secret"));
this.users.put("alice", new UserData("alice", "secret"));
}
@Override
public Optional<UserData> login(String sessionId, LoginRequest loginRequest) {
UserData userData = users.get(loginRequest.getUserName());
if (userData != null && userData.verifyPassword(loginRequest.getPassword())) {
LOG.info("login OK: {} {}", sessionId, loginRequest.getUserName());
sessions.put(sessionId, userData);
return Optional.of(userData);
}
LOG.info("login Failed: {} {}", sessionId, loginRequest.getUserName());
|
return Optional.empty();
}
@Override
public Optional<UserData> isAuthenticated(String sessionId) {
return Optional.ofNullable(sessions.get(sessionId));
}
@Override
public void logout(String sessionId) {
LOG.info("logout: {}", sessionId);
sessions.remove(sessionId);
}
}
|
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\services\UserAccessServiceImpl.java
| 2
|
请完成以下Java代码
|
public int getMD_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID);
}
@Override
public void setMD_Candidate_QtyDetails_ID (final int MD_Candidate_QtyDetails_ID)
{
if (MD_Candidate_QtyDetails_ID < 1)
set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, MD_Candidate_QtyDetails_ID);
}
@Override
public int getMD_Candidate_QtyDetails_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_QtyDetails_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
|
@Override
public void setStock_MD_Candidate_ID (final int Stock_MD_Candidate_ID)
{
if (Stock_MD_Candidate_ID < 1)
set_Value (COLUMNNAME_Stock_MD_Candidate_ID, null);
else
set_Value (COLUMNNAME_Stock_MD_Candidate_ID, Stock_MD_Candidate_ID);
}
@Override
public int getStock_MD_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_Stock_MD_Candidate_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_QtyDetails.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class HazelcastServerConfigFileConfiguration {
@Bean
HazelcastInstance hazelcastInstance(HazelcastProperties properties, ResourceLoader resourceLoader,
ObjectProvider<HazelcastConfigCustomizer> hazelcastConfigCustomizers) throws IOException {
Resource configLocation = properties.resolveConfigLocation();
Config config = (configLocation != null) ? loadConfig(configLocation) : Config.load();
config.setClassLoader(resourceLoader.getClassLoader());
hazelcastConfigCustomizers.orderedStream().forEach((customizer) -> customizer.customize(config));
return getHazelcastInstance(config);
}
private Config loadConfig(Resource configLocation) throws IOException {
URL configUrl = configLocation.getURL();
Config config = loadConfig(configUrl);
if (ResourceUtils.isFileURL(configUrl)) {
config.setConfigurationFile(configLocation.getFile());
}
else {
config.setConfigurationUrl(configUrl);
}
return config;
}
private Config loadConfig(URL configUrl) throws IOException {
try (InputStream stream = configUrl.openStream()) {
return Config.loadFromStream(stream);
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnSingleCandidate(Config.class)
static class HazelcastServerConfigConfiguration {
@Bean
HazelcastInstance hazelcastInstance(Config config) {
return getHazelcastInstance(config);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(SpringManagedContext.class)
static class SpringManagedContextHazelcastConfigCustomizerConfiguration {
@Bean
@Order(0)
HazelcastConfigCustomizer springManagedContextHazelcastConfigCustomizer(ApplicationContext applicationContext) {
|
return (config) -> {
SpringManagedContext managementContext = new SpringManagedContext();
managementContext.setApplicationContext(applicationContext);
config.setManagedContext(managementContext);
};
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(org.slf4j.Logger.class)
static class HazelcastLoggingConfigCustomizerConfiguration {
@Bean
@Order(0)
HazelcastConfigCustomizer loggingHazelcastConfigCustomizer() {
return (config) -> {
if (!config.getProperties().containsKey(HAZELCAST_LOGGING_TYPE)) {
config.setProperty(HAZELCAST_LOGGING_TYPE, "slf4j");
}
};
}
}
/**
* {@link HazelcastConfigResourceCondition} that checks if the
* {@code spring.hazelcast.config} configuration key is defined.
*/
static class ConfigAvailableCondition extends HazelcastConfigResourceCondition {
ConfigAvailableCondition() {
super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast.xml", "classpath:/hazelcast.xml", "file:./hazelcast.yaml",
"classpath:/hazelcast.yaml", "file:./hazelcast.yml", "classpath:/hazelcast.yml");
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-hazelcast\src\main\java\org\springframework\boot\hazelcast\autoconfigure\HazelcastServerConfiguration.java
| 2
|
请完成以下Java代码
|
public String getTopicName() {
return subscriptionConfiguration.getTopicName();
}
@Override
public Long getLockDuration() {
return subscriptionConfiguration.getLockDuration();
}
@Override
public ExternalTaskHandler getExternalTaskHandler() {
return externalTaskHandler;
}
@Override
public List<String> getVariableNames() {
return subscriptionConfiguration.getVariableNames();
}
@Override
public boolean isLocalVariables() {
return subscriptionConfiguration.getLocalVariables();
}
@Override
public String getBusinessKey() {
return subscriptionConfiguration.getBusinessKey();
}
@Override
public String getProcessDefinitionId() {
return subscriptionConfiguration.getProcessDefinitionId();
}
@Override
public List<String> getProcessDefinitionIdIn() {
return subscriptionConfiguration.getProcessDefinitionIdIn();
}
@Override
public String getProcessDefinitionKey() {
return subscriptionConfiguration.getProcessDefinitionKey();
}
@Override
public List<String> getProcessDefinitionKeyIn() {
return subscriptionConfiguration.getProcessDefinitionKeyIn();
}
@Override
public String getProcessDefinitionVersionTag() {
return subscriptionConfiguration.getProcessDefinitionVersionTag();
}
|
@Override
public Map<String, Object> getProcessVariables() {
return subscriptionConfiguration.getProcessVariables();
}
@Override
public boolean isWithoutTenantId() {
return subscriptionConfiguration.getWithoutTenantId();
}
@Override
public List<String> getTenantIdIn() {
return subscriptionConfiguration.getTenantIdIn();
}
@Override
public boolean isIncludeExtensionProperties() {
return subscriptionConfiguration.getIncludeExtensionProperties();
}
protected String[] toArray(List<String> list) {
return list.toArray(new String[0]);
}
@Override
public void afterPropertiesSet() throws Exception {
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\subscription\SpringTopicSubscriptionImpl.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQtyItemCapacity()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyItemCapacityInternal (final @Nullable BigDecimal QtyItemCapacityInternal)
{
set_Value (COLUMNNAME_QtyItemCapacityInternal, QtyItemCapacityInternal);
}
@Override
public BigDecimal getQtyItemCapacityInternal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacityInternal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyShipped (final @Nullable BigDecimal QtyShipped)
{
set_Value (COLUMNNAME_QtyShipped, QtyShipped);
}
@Override
public BigDecimal getQtyShipped()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyShipped_CatchWeight (final @Nullable BigDecimal QtyShipped_CatchWeight)
{
set_Value (COLUMNNAME_QtyShipped_CatchWeight, QtyShipped_CatchWeight);
}
@Override
public BigDecimal getQtyShipped_CatchWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped_CatchWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyShipped_CatchWeight_UOM_ID (final int QtyShipped_CatchWeight_UOM_ID)
|
{
if (QtyShipped_CatchWeight_UOM_ID < 1)
set_Value (COLUMNNAME_QtyShipped_CatchWeight_UOM_ID, null);
else
set_Value (COLUMNNAME_QtyShipped_CatchWeight_UOM_ID, QtyShipped_CatchWeight_UOM_ID);
}
@Override
public int getQtyShipped_CatchWeight_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_QtyShipped_CatchWeight_UOM_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setReplicationTrxErrorMsg (final @Nullable java.lang.String ReplicationTrxErrorMsg)
{
throw new IllegalArgumentException ("ReplicationTrxErrorMsg is virtual column"); }
@Override
public java.lang.String getReplicationTrxErrorMsg()
{
return get_ValueAsString(COLUMNNAME_ReplicationTrxErrorMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCand.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DeviceMapping _id(UUID _id) {
this._id = _id;
return this;
}
/**
* Alberta-Id des Geräts
* @return _id
**/
@Schema(example = "c496a0f9-ab4e-47b1-9f76-42f363e0420f", required = true, description = "Alberta-Id des Geräts")
public UUID getId() {
return _id;
}
public void setId(UUID _id) {
this._id = _id;
}
public DeviceMapping serialNumber(String serialNumber) {
this.serialNumber = serialNumber;
return this;
}
/**
* eindeutige Seriennumer aus WaWi
* @return serialNumber
**/
@Schema(example = "2005-F540053-EB-0430", required = true, description = "eindeutige Seriennumer aus WaWi")
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public DeviceMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(example = "2020-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
|
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceMapping deviceMapping = (DeviceMapping) o;
return Objects.equals(this._id, deviceMapping._id) &&
Objects.equals(this.serialNumber, deviceMapping.serialNumber) &&
Objects.equals(this.updated, deviceMapping.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, serialNumber, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" serialNumber: ").append(toIndentedString(serialNumber)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceMapping.java
| 2
|
请完成以下Java代码
|
public class HazelcastNotificationTrigger extends NotificationTrigger {
private static final Logger log = LoggerFactory.getLogger(HazelcastNotificationTrigger.class);
private final ConcurrentMap<InstanceId, Long> sentNotifications;
public HazelcastNotificationTrigger(Notifier notifier, Publisher<InstanceEvent> events,
ConcurrentMap<InstanceId, Long> sentNotifications) {
super(notifier, events);
this.sentNotifications = sentNotifications;
}
@Override
protected Mono<Void> sendNotifications(InstanceEvent event) {
while (true) {
Long lastSentEvent = this.sentNotifications.getOrDefault(event.getInstance(), -1L);
if (lastSentEvent >= event.getVersion()) {
log.debug("Notifications already sent. Not triggering notifiers for {}", event);
|
return Mono.empty();
}
if (lastSentEvent < 0) {
if (this.sentNotifications.putIfAbsent(event.getInstance(), event.getVersion()) == null) {
log.debug("Triggering notifiers for {}", event);
return super.sendNotifications(event);
}
}
else {
if (this.sentNotifications.replace(event.getInstance(), lastSentEvent, event.getVersion())) {
log.debug("Triggering notifiers for {}", event);
return super.sendNotifications(event);
}
}
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\HazelcastNotificationTrigger.java
| 1
|
请完成以下Java代码
|
public BigDecimal getFullPrice() {
return fullPrice;
}
public void setFullPrice(BigDecimal fullPrice) {
this.fullPrice = fullPrice;
}
public BigDecimal getReducePrice() {
return reducePrice;
}
public void setReducePrice(BigDecimal reducePrice) {
this.reducePrice = reducePrice;
}
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", fullPrice=").append(fullPrice);
sb.append(", reducePrice=").append(reducePrice);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductFullReduction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return historicVariableInstanceEntityManager;
}
public VariableServiceConfiguration setHistoricVariableInstanceEntityManager(HistoricVariableInstanceEntityManager historicVariableInstanceEntityManager) {
this.historicVariableInstanceEntityManager = historicVariableInstanceEntityManager;
return this;
}
public VariableTypes getVariableTypes() {
return variableTypes;
}
public VariableServiceConfiguration setVariableTypes(VariableTypes variableTypes) {
this.variableTypes = variableTypes;
return this;
}
public InternalHistoryVariableManager getInternalHistoryVariableManager() {
return internalHistoryVariableManager;
}
public VariableServiceConfiguration setInternalHistoryVariableManager(InternalHistoryVariableManager internalHistoryVariableManager) {
this.internalHistoryVariableManager = internalHistoryVariableManager;
return this;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public VariableServiceConfiguration setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
return this;
}
public int getMaxLengthString() {
return maxLengthString;
}
public VariableServiceConfiguration setMaxLengthString(int maxLengthString) {
this.maxLengthString = maxLengthString;
return this;
}
public boolean isLoggingSessionEnabled() {
return loggingSessionEnabled;
}
|
public VariableServiceConfiguration setLoggingSessionEnabled(boolean loggingSessionEnabled) {
this.loggingSessionEnabled = loggingSessionEnabled;
return this;
}
public boolean isSerializableVariableTypeTrackDeserializedObjects() {
return serializableVariableTypeTrackDeserializedObjects;
}
public void setSerializableVariableTypeTrackDeserializedObjects(boolean serializableVariableTypeTrackDeserializedObjects) {
this.serializableVariableTypeTrackDeserializedObjects = serializableVariableTypeTrackDeserializedObjects;
}
public VariableJsonMapper getVariableJsonMapper() {
return variableJsonMapper;
}
public void setVariableJsonMapper(VariableJsonMapper variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
}
public VariableInstanceValueModifier getVariableInstanceValueModifier() {
return variableInstanceValueModifier;
}
public void setVariableInstanceValueModifier(VariableInstanceValueModifier variableInstanceValueModifier) {
this.variableInstanceValueModifier = variableInstanceValueModifier;
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\VariableServiceConfiguration.java
| 2
|
请完成以下Java代码
|
public CleanableHistoricCaseInstanceReport caseDefinitionIdIn(String... caseDefinitionIds) {
ensureNotNull(NotValidException.class, "", "caseDefinitionIdIn", (Object[]) caseDefinitionIds);
this.caseDefinitionIdIn = caseDefinitionIds;
return this;
}
@Override
public CleanableHistoricCaseInstanceReport caseDefinitionKeyIn(String... caseDefinitionKeys) {
ensureNotNull(NotValidException.class, "", "caseDefinitionKeyIn", (Object[]) caseDefinitionKeys);
this.caseDefinitionKeyIn = caseDefinitionKeys;
return this;
}
@Override
public CleanableHistoricCaseInstanceReport tenantIdIn(String... tenantIds) {
ensureNotNull(NotValidException.class, "", "tenantIdIn", (Object[]) tenantIds);
this.tenantIdIn = tenantIds;
isTenantIdSet = true;
return this;
}
@Override
public CleanableHistoricCaseInstanceReport withoutTenantId() {
this.tenantIdIn = null;
isTenantIdSet = true;
return this;
}
@Override
public CleanableHistoricCaseInstanceReport compact() {
this.isCompact = true;
return this;
}
@Override
public CleanableHistoricCaseInstanceReport orderByFinished() {
orderBy(CleanableHistoricInstanceReportProperty.FINISHED_AMOUNT);
return this;
}
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricCaseInstanceManager()
.findCleanableHistoricCaseInstancesReportCountByCriteria(this);
}
@Override
|
public List<CleanableHistoricCaseInstanceReportResult> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricCaseInstanceManager()
.findCleanableHistoricCaseInstancesReportByCriteria(this, page);
}
public String[] getCaseDefinitionIdIn() {
return caseDefinitionIdIn;
}
public void setCaseDefinitionIdIn(String[] caseDefinitionIdIn) {
this.caseDefinitionIdIn = caseDefinitionIdIn;
}
public String[] getCaseDefinitionKeyIn() {
return caseDefinitionKeyIn;
}
public void setCaseDefinitionKeyIn(String[] caseDefinitionKeyIn) {
this.caseDefinitionKeyIn = caseDefinitionKeyIn;
}
public Date getCurrentTimestamp() {
return currentTimestamp;
}
public void setCurrentTimestamp(Date currentTimestamp) {
this.currentTimestamp = currentTimestamp;
}
public String[] getTenantIdIn() {
return tenantIdIn;
}
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isCompact() {
return isCompact;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricCaseInstanceReportImpl.java
| 1
|
请完成以下Java代码
|
public Optional<I_C_Doc_Outbound_Log> setEdiExportStatusFromInvoiceRecord(@NonNull final TableRecordReference recordReference)
{
if (!I_C_Invoice.Table_Name.equals(recordReference.getTableName()))
{
return Optional.empty();
}
final I_C_Doc_Outbound_Log logRecord = create(docOutboundDAO.retrieveLog(recordReference), I_C_Doc_Outbound_Log.class);
if (logRecord != null)
{
logRecord.setEDI_ExportStatus(getEDIExportStatusFromInvoiceRecord(recordReference));
}
return Optional.ofNullable(logRecord);
}
@Nullable
public String getEDIExportStatusFromInvoiceRecord(final @NonNull TableRecordReference recordReference)
{
if (!I_C_Invoice.Table_Name.equals(recordReference.getTableName()))
{
return null;
}
|
final I_C_Invoice invoiceRecord = recordReference.getModel(I_C_Invoice.class);
return invoiceRecord.getEDI_ExportStatus();
}
public I_C_Doc_Outbound_Log retreiveById(@NonNull final DocOutboundLogId docOutboundLogId)
{
return load(docOutboundLogId, I_C_Doc_Outbound_Log.class);
}
public I_C_Invoice retreiveById(@NonNull final InvoiceId invoiceId)
{
return load(invoiceId, I_C_Invoice.class);
}
public void save(@NonNull final de.metas.edi.model.I_C_Doc_Outbound_Log docOutboundLog)
{
InterfaceWrapperHelper.save(docOutboundLog);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\EDIDocOutBoundLogService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//@formatter:off
return http
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
.requestMatchers("/api/auth/**", "/swagger-ui-custom.html" ,"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**",
"/swagger-ui/index.html","/api-docs/**")
.permitAll()
.anyRequest()
.authenticated())
.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
.and())
.build();
//@formatter:on
}
/**
* For demonstration/example, we use the InMemoryUserDetailsManager.
*
* @return Returns the UserDetailsService with pre-configure credentials.
* @see InMemoryUserDetailsManager
*/
@Bean
UserDetailsService allUsers() {
// @formatter:off
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager
.createUser(User.builder()
.passwordEncoder(password -> password)
.username("john")
.password("password")
.authorities("USER")
.roles("USER").build());
manager
|
.createUser(User.builder()
.passwordEncoder(password -> password)
.username("jane")
.password("password")
.authorities("USER")
.roles("USER").build());
return manager;
// @formatter:on
}
/**
* This bean is used to decode the JWT token.
*
* @return Returns the JwtDecoder bean to decode JWT tokens.
*/
@Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(this.publicKey).build();
}
/**
* This bean is used to encode the JWT token.
*
* @return Returns the JwtEncoder bean to encode JWT tokens.
*/
@Bean
JwtEncoder jwtEncoder() {
JWK jwk = new RSAKey.Builder(this.publicKey).privateKey(this.privateKey).build();
return new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(jwk)));
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\java\com\baeldung\jwt\SecurityConfiguration.java
| 2
|
请完成以下Java代码
|
public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID)
{
if (M_AttributeSetExclude_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID));
}
/** Get Exclude Attribute Set.
@return Exclude the ability to enter Attribute Sets
*/
@Override
public int getM_AttributeSetExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Exclude attribute.
@param M_AttributeSetExcludeLine_ID
Only excludes selected attributes from the attribute set
*/
|
@Override
public void setM_AttributeSetExcludeLine_ID (int M_AttributeSetExcludeLine_ID)
{
if (M_AttributeSetExcludeLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExcludeLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExcludeLine_ID, Integer.valueOf(M_AttributeSetExcludeLine_ID));
}
/** Get Exclude attribute.
@return Only excludes selected attributes from the attribute set
*/
@Override
public int getM_AttributeSetExcludeLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExcludeLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_M_AttributeSetExcludeLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String returnSuccessForRootUrl() {
return "Success";
}
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// Path Parameters
// /users/{id}/todos/{id} => /users/2/todos/200
// /hello-world/path-variable/{name}
// /hello-world/path-variable/Ranga
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
|
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale );
//return "Hello World V2";
//1:
//2:
// - Example: `en` - English (Good Morning)
// - Example: `nl` - Dutch (Goedemorgen)
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
}
|
repos\master-spring-and-spring-boot-main\91-aws\02-rest-api-mysql\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\helloworld\HelloWorldController.java
| 2
|
请完成以下Java代码
|
public @Nullable Resource resolve(String subUriPath) {
if (subUriPath.startsWith(LOADER_RESOURCE_PATH_PREFIX)) {
return null;
}
Resource resolved = this.delegate.resolve(subUriPath);
return (resolved != null) ? new LoaderHidingResource(this.base, resolved) : null;
}
@Override
public boolean isAlias() {
return this.delegate.isAlias();
}
@Override
public URI getRealURI() {
return this.delegate.getRealURI();
}
|
@Override
public void copyTo(Path destination) throws IOException {
this.delegate.copyTo(destination);
}
@Override
public Collection<Resource> getAllResources() {
return asLoaderHidingResources(this.delegate.getAllResources());
}
@Override
public String toString() {
return this.delegate.toString();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\LoaderHidingResource.java
| 1
|
请完成以下Java代码
|
public class SearchArrayBenchmark {
@State(Scope.Benchmark)
public static class SearchData {
static int count = 1000;
static String[] strings = seedArray(1000);
}
@Benchmark
public void searchArrayLoop() {
for (int i = 0; i < SearchData.count; i++) {
searchLoop(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayAllocNewList() {
for (int i = 0; i < SearchData.count; i++) {
searchList(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayAllocNewSet() {
for (int i = 0; i < SearchData.count; i++) {
searchSet(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayReuseList() {
List<String> asList = Arrays.asList(SearchData.strings);
for (int i = 0; i < SearchData.count; i++) {
asList.contains("T");
}
}
@Benchmark
public void searchArrayReuseSet() {
Set<String> asSet = new HashSet<>(Arrays.asList(SearchData.strings));
for (int i = 0; i < SearchData.count; i++) {
asSet.contains("T");
}
}
@Benchmark
public void searchArrayBinarySearch() {
Arrays.sort(SearchData.strings);
for (int i = 0; i < SearchData.count; i++) {
Arrays.binarySearch(SearchData.strings, "T");
|
}
}
private boolean searchList(String[] strings, String searchString) {
return Arrays.asList(strings).contains(searchString);
}
private boolean searchSet(String[] strings, String searchString) {
Set<String> set = new HashSet<>(Arrays.asList(strings));
return set.contains(searchString);
}
private boolean searchLoop(String[] strings, String searchString) {
for (String s : strings) {
if (s.equals(searchString))
return true;
}
return false;
}
private static String[] seedArray(int length) {
String[] strings = new String[length];
Random random = new Random();
for (int i = 0; i < length; i++)
{
strings[i] = String.valueOf(random.nextInt());
}
return strings;
}
}
|
repos\tutorials-master\core-java-modules\core-java-arrays-operations-basic-3\src\main\java\com\baeldung\array\SearchArrayBenchmark.java
| 1
|
请完成以下Java代码
|
public abstract class ContextAwareActor extends AbstractTbActor {
public static final int ENTITY_PACK_LIMIT = 1024;
protected final ActorSystemContext systemContext;
public ContextAwareActor(ActorSystemContext systemContext) {
super();
this.systemContext = systemContext;
}
@Override
public boolean process(TbActorMsg msg) {
if (log.isDebugEnabled()) {
log.debug("Processing msg: {}", msg);
}
if (!doProcess(msg)) {
log.warn("Unprocessed message: {}!", msg);
}
return false;
|
}
protected abstract boolean doProcess(TbActorMsg msg);
@Override
public ProcessFailureStrategy onProcessFailure(TbActorMsg msg, Throwable t) {
log.debug("[{}] Processing failure for msg {}", getActorRef().getActorId(), msg, t);
return doProcessFailure(t);
}
protected ProcessFailureStrategy doProcessFailure(Throwable t) {
if (t instanceof Error) {
return ProcessFailureStrategy.stop();
} else {
return ProcessFailureStrategy.resume();
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\service\ContextAwareActor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JdbcUserDetailsManagerConfigurer<B> groupAuthoritiesByUsername(String query) {
JdbcUserDetailsManager userDetailsService = getUserDetailsService();
userDetailsService.setEnableGroups(true);
userDetailsService.setGroupAuthoritiesByUsernameQuery(query);
return this;
}
/**
* A non-empty string prefix that will be added to role strings loaded from persistent
* storage (default is "").
* @param rolePrefix
* @return The {@link JdbcUserDetailsManagerConfigurer} used for additional
* customizations
*/
public JdbcUserDetailsManagerConfigurer<B> rolePrefix(String rolePrefix) {
getUserDetailsService().setRolePrefix(rolePrefix);
return this;
}
/**
* Defines the {@link UserCache} to use
* @param userCache the {@link UserCache} to use
* @return the {@link JdbcUserDetailsManagerConfigurer} for further customizations
*/
public JdbcUserDetailsManagerConfigurer<B> userCache(UserCache userCache) {
getUserDetailsService().setUserCache(userCache);
return this;
}
@Override
protected void initUserDetailsService() {
if (!this.initScripts.isEmpty()) {
getDataSourceInit().afterPropertiesSet();
}
super.initUserDetailsService();
}
@Override
public JdbcUserDetailsManager getUserDetailsService() {
|
return (JdbcUserDetailsManager) super.getUserDetailsService();
}
/**
* Populates the default schema that allows users and authorities to be stored.
* @return The {@link JdbcUserDetailsManagerConfigurer} used for additional
* customizations
*/
public JdbcUserDetailsManagerConfigurer<B> withDefaultSchema() {
this.initScripts.add(new ClassPathResource("org/springframework/security/core/userdetails/jdbc/users.ddl"));
return this;
}
protected DatabasePopulator getDatabasePopulator() {
ResourceDatabasePopulator dbp = new ResourceDatabasePopulator();
dbp.setScripts(this.initScripts.toArray(new Resource[0]));
return dbp;
}
private DataSourceInitializer getDataSourceInit() {
DataSourceInitializer dsi = new DataSourceInitializer();
dsi.setDatabasePopulator(getDatabasePopulator());
dsi.setDataSource(this.dataSource);
return dsi;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\provisioning\JdbcUserDetailsManagerConfigurer.java
| 2
|
请完成以下Java代码
|
public Map<String, String> getProperties() {
return commandExecutor.execute(new GetPropertiesCmd());
}
public String databaseSchemaUpgrade(final Connection connection, final String catalog, final String schema) {
CommandConfig config = commandExecutor.getDefaultConfig().transactionNotSupported();
return commandExecutor.execute(
config,
new Command<String>() {
public String execute(CommandContext commandContext) {
DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) commandContext
.getSessionFactories()
.get(DbSqlSession.class);
DbSqlSession dbSqlSession = new DbSqlSession(
dbSqlSessionFactory,
commandContext.getEntityCache(),
connection,
catalog,
schema
);
commandContext.getSessions().put(DbSqlSession.class, dbSqlSession);
return dbSqlSession.dbSchemaUpdate();
}
}
);
}
public <T> T executeCommand(Command<T> command) {
if (command == null) {
throw new ActivitiIllegalArgumentException("The command is null");
}
return commandExecutor.execute(command);
}
public <T> T executeCommand(CommandConfig config, Command<T> command) {
if (config == null) {
throw new ActivitiIllegalArgumentException("The config is null");
}
if (command == null) {
|
throw new ActivitiIllegalArgumentException("The command is null");
}
return commandExecutor.execute(config, command);
}
@Override
public <MapperType, ResultType> ResultType executeCustomSql(
CustomSqlExecution<MapperType, ResultType> customSqlExecution
) {
Class<MapperType> mapperClass = customSqlExecution.getMapperClass();
return commandExecutor.execute(
new ExecuteCustomSqlCmd<MapperType, ResultType>(mapperClass, customSqlExecution)
);
}
@Override
public List<EventLogEntry> getEventLogEntries(Long startLogNr, Long pageSize) {
return commandExecutor.execute(new GetEventLogEntriesCmd(startLogNr, pageSize));
}
@Override
public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) {
return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId));
}
@Override
public void deleteEventLogEntry(long logNr) {
commandExecutor.execute(new DeleteEventLogEntry(logNr));
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ManagementServiceImpl.java
| 1
|
请完成以下Java代码
|
public void setGO_URL (java.lang.String GO_URL)
{
set_Value (COLUMNNAME_GO_URL, GO_URL);
}
/** Get GO URL.
@return GO URL */
@Override
public java.lang.String getGO_URL ()
{
return (java.lang.String)get_Value(COLUMNNAME_GO_URL);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
|
/** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
@Override
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_Shipper_Config.java
| 1
|
请完成以下Java代码
|
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 static void copy(
@NonNull final IHUDeliveryQuantities to,
@NonNull final I_M_ShipmentSchedule shipmentSchedule)
{
final List<I_M_ShipmentSchedule_QtyPicked> shipmentScheduleQtyPickedList = //
Services.get(IQueryBL.class)
.createQueryBuilder(I_M_ShipmentSchedule_QtyPicked.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_M_ShipmentSchedule_ID, shipmentSchedule.getM_ShipmentSchedule_ID())
.create()
.list();
BigDecimal qtyDeliveredLU = BigDecimal.ZERO;
BigDecimal qtyDeliveredTU = BigDecimal.ZERO;
for (final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked : shipmentScheduleQtyPickedList)
{
qtyDeliveredLU = add(qtyDeliveredLU, shipmentScheduleQtyPicked.getQtyLU());
qtyDeliveredTU = add(qtyDeliveredTU, shipmentScheduleQtyPicked.getQtyTU());
}
to.setQtyOrdered_LU(shipmentSchedule.getQtyOrdered_LU());
to.setQtyDelivered_LU(qtyDeliveredLU);
to.setQtyOrdered_TU(shipmentSchedule.getQtyOrdered_TU());
to.setQtyDelivered_TU(qtyDeliveredTU);
}
/**
*
* @param bd1
* @param bd2
* @return bd1 + bd2
*/
private static final BigDecimal add(final BigDecimal bd1, final BigDecimal bd2)
{
BigDecimal result;
if (bd1 != null)
{
result = bd1;
}
else
{
result = BigDecimal.ZERO;
}
if (bd2 != null)
{
result = result.add(bd2);
}
return result;
}
|
/**
*
* @param bd1
* @param bd2
* @return bd1 - bd2
*/
private static final BigDecimal subtract(final BigDecimal bd1, final BigDecimal bd2)
{
BigDecimal result;
if (bd1 != null)
{
result = bd1;
}
else
{
result = BigDecimal.ZERO;
}
if (bd2 != null)
{
result = result.subtract(bd2);
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUDeliveryQuantitiesHelper.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
datasource:
primary:
jdbc-url: jdbc:mysql://localhost:3306/test1
username: root
password: root
secondary:
jdbc-url: jdbc:mysql://localhost:3306/test2
username: root
password: root
j
|
pa:
database: mysql
generate-ddl: true
show-sql: true
hibernate:
ddl-auto: update
|
repos\spring-boot-leaning-master\2.x_data\1-5 Spring Boot 下的(分布式)事务解决方案\spring-boot-multi-Jpa\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public static Collector<Money, ?, ImmutableMap<CurrencyId, Money>> sumByCurrency()
{
return sumByCurrencyAnd(ImmutableMap::copyOf);
}
public static <T> Collector<Money, ?, T> sumByCurrencyAnd(final Function<Map<CurrencyId, Money>, T> finisher)
{
final Supplier<Map<CurrencyId, Money>> supplier = HashMap::new;
final BiConsumer<Map<CurrencyId, Money>, Money> accumulator = (map, money) -> map.compute(money.getCurrencyId(), (currency, moneyOld) -> moneyOld != null ? moneyOld.add(money) : money);
final BinaryOperator<Map<CurrencyId, Money>> combiner = (l, r) -> {
r.values().forEach(money -> accumulator.accept(l, money));
return l;
};
return Collector.of(supplier, accumulator, combiner, finisher);
}
public Amount toAmount(@NonNull final Function<CurrencyId, CurrencyCode> currencyCodeMapper)
{
return Amount.of(toBigDecimal(), currencyCodeMapper.apply(getCurrencyId()));
}
public Money round(@NonNull final CurrencyPrecision precision)
{
return withValue(precision.round(this.value));
}
public Money roundIfNeeded(@NonNull final CurrencyPrecision precision)
{
return withValue(precision.roundIfNeeded(this.value));
}
public Money round(@NonNull final Function<CurrencyId, CurrencyPrecision> precisionProvider)
{
final CurrencyPrecision precision = precisionProvider.apply(currencyId);
if (precision == null)
{
throw new AdempiereException("No precision was returned by " + precisionProvider + " for " + currencyId);
}
return round(precision);
}
private Money withValue(@NonNull final BigDecimal newValue)
{
|
return value.compareTo(newValue) != 0 ? of(newValue, currencyId) : this;
}
public static int countNonZero(final Money... array)
{
if (array == null || array.length == 0)
{
return 0;
}
int count = 0;
for (final Money money : array)
{
if (money != null && money.signum() != 0)
{
count++;
}
}
return count;
}
public static boolean equals(@Nullable Money money1, @Nullable Money money2) {return Objects.equals(money1, money2);}
public Percent percentageOf(@NonNull final Money whole)
{
assertCurrencyIdMatching(whole);
return Percent.of(toBigDecimal(), whole.toBigDecimal());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\Money.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<String> updateById(@RequestBody AiOcr aiOcr){
Object aiOcrList = redisUtil.get(AI_OCR_REDIS_KEY);
if(null != aiOcrList){
List<AiOcr> aiOcrs = JSONObject.parseArray(aiOcrList.toString(), AiOcr.class);
aiOcrs.forEach(item->{
if(item.getId().equals(aiOcr.getId())){
BeanUtils.copyProperties(aiOcr,item);
}
});
redisUtil.set(AI_OCR_REDIS_KEY,JSONObject.toJSONString(aiOcrs));
}else{
return Result.OK("编辑失败,未找到该数据");
}
return Result.OK("编辑成功");
}
@DeleteMapping("/deleteById")
public Result<String> deleteById(@RequestBody AiOcr aiOcr){
Object aiOcrObj = redisUtil.get(AI_OCR_REDIS_KEY);
|
if(null != aiOcrObj){
List<AiOcr> aiOcrs = JSONObject.parseArray(aiOcrObj.toString(), AiOcr.class);
List<AiOcr> aiOcrList = new ArrayList<>();
for(AiOcr ocr: aiOcrs){
if(!ocr.getId().equals(aiOcr.getId())){
aiOcrList.add(ocr);
}
}
if(CollectionUtils.isNotEmpty(aiOcrList)){
redisUtil.set(AI_OCR_REDIS_KEY,JSONObject.toJSONString(aiOcrList));
}else{
redisUtil.removeAll(AI_OCR_REDIS_KEY);
}
}else{
return Result.OK("删除失败,未找到该数据");
}
return Result.OK("删除成功");
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\ocr\controller\AiOcrController.java
| 2
|
请完成以下Java代码
|
public BigDecimal getPdctQty() {
return pdctQty;
}
/**
* Sets the value of the pdctQty property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setPdctQty(BigDecimal value) {
this.pdctQty = value;
}
/**
* Gets the value of the unitPric property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getUnitPric() {
return unitPric;
}
/**
* Sets the value of the unitPric property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setUnitPric(BigDecimal value) {
this.unitPric = value;
}
/**
* Gets the value of the pdctAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getPdctAmt() {
return pdctAmt;
}
/**
* Sets the value of the pdctAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setPdctAmt(BigDecimal value) {
this.pdctAmt = value;
}
/**
* Gets the value of the taxTp property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTaxTp() {
return taxTp;
}
/**
* Sets the value of the taxTp property.
*
|
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxTp(String value) {
this.taxTp = value;
}
/**
* Gets the value of the addtlPdctInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlPdctInf() {
return addtlPdctInf;
}
/**
* Sets the value of the addtlPdctInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlPdctInf(String value) {
this.addtlPdctInf = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\Product2.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MqConfig {
private static final Log LOG = LogFactory.getLog(MqConfig.class);
/** 商户通知队列 **/
public static String MERCHANT_NOTIFY_QUEUE = "";
/** 订单通知队列 **/
public static String ORDER_NOTIFY_QUEUE = "";
private static Properties properties = null;
static{
if(null == properties){
properties = new Properties();
|
}
InputStream proFile = Thread.currentThread().getContextClassLoader().getResourceAsStream("mq_config.properties");
try {
properties.load(proFile);
init(properties);
} catch (IOException e) {
LOG.error("=== load and init mq exception:" + e);
}
}
private static void init(Properties properties){
MERCHANT_NOTIFY_QUEUE = properties.getProperty("tradeQueueName.notify");
ORDER_NOTIFY_QUEUE = properties.getProperty("orderQueryQueueName.query");
}
}
|
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\config\MqConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean sendDelay() {
// 创建 Message
Demo01Message message = new Demo01Message()
.setId(new Random().nextInt());
// 创建 Spring Message 对象
Message<Demo01Message> springMessage = MessageBuilder.withPayload(message)
.setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "3") // 设置延迟级别为 3,10 秒后消费。
.build();
// 发送消息
boolean sendResult = mySource.demo01Output().send(springMessage);
logger.info("[sendDelay][发送消息完成, 结果 = {}]", sendResult);
return sendResult;
}
@GetMapping("/send_tag")
public boolean sendTag() {
|
for (String tag : new String[]{"yunai", "yutou", "tudou"}) {
// 创建 Message
Demo01Message message = new Demo01Message()
.setId(new Random().nextInt());
// 创建 Spring Message 对象
Message<Demo01Message> springMessage = MessageBuilder.withPayload(message)
.setHeader(MessageConst.PROPERTY_TAGS, tag) // 设置 Tag
.build();
// 发送消息
mySource.demo01Output().send(springMessage);
}
return true;
}
}
|
repos\SpringBoot-Labs-master\labx-06-spring-cloud-stream-rocketmq\labx-06-sca-stream-rocketmq-producer-actuator\src\main\java\cn\iocoder\springcloudalibaba\labx6\rocketmqdemo\producerdemo\controller\Demo01Controller.java
| 2
|
请完成以下Java代码
|
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public Date getCreateTime() {
return getStartTime();
}
public void setCreateTime(Date createTime) {
setStartTime(createTime);
}
public Date getCloseTime() {
return getEndTime();
}
public void setCloseTime(Date closeTime) {
setEndTime(closeTime);
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String userId) {
createUserId = userId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public void setSuperCaseInstanceId(String superCaseInstanceId) {
this.superCaseInstanceId = superCaseInstanceId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public void setSuperProcessInstanceId(String superProcessInstanceId) {
this.superProcessInstanceId = superProcessInstanceId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public boolean isActive() {
return state == ACTIVE.getStateCode();
}
public boolean isCompleted() {
|
return state == COMPLETED.getStateCode();
}
public boolean isTerminated() {
return state == TERMINATED.getStateCode();
}
public boolean isFailed() {
return state == FAILED.getStateCode();
}
public boolean isSuspended() {
return state == SUSPENDED.getStateCode();
}
public boolean isClosed() {
return state == CLOSED.getStateCode();
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[businessKey=" + businessKey
+ ", startUserId=" + createUserId
+ ", superCaseInstanceId=" + superCaseInstanceId
+ ", superProcessInstanceId=" + superProcessInstanceId
+ ", durationInMillis=" + durationInMillis
+ ", createTime=" + startTime
+ ", closeTime=" + endTime
+ ", id=" + id
+ ", eventType=" + eventType
+ ", caseExecutionId=" + caseExecutionId
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricCaseInstanceEventEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCOUNTRY() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCOUNTRY(String value) {
this.country = value;
}
/**
* Gets the value of the locationcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONCODE() {
return locationcode;
}
/**
* Sets the value of the locationcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONCODE(String value) {
this.locationcode = value;
}
/**
* Gets the value of the locationname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONNAME() {
return locationname;
}
/**
* Sets the value of the locationname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONNAME(String value) {
|
this.locationname = value;
}
/**
* Gets the value of the drfad1 property.
*
* @return
* possible object is
* {@link DRFAD1 }
*
*/
public DRFAD1 getDRFAD1() {
return drfad1;
}
/**
* Sets the value of the drfad1 property.
*
* @param value
* allowed object is
* {@link DRFAD1 }
*
*/
public void setDRFAD1(DRFAD1 value) {
this.drfad1 = value;
}
/**
* Gets the value of the dctad1 property.
*
* @return
* possible object is
* {@link DCTAD1 }
*
*/
public DCTAD1 getDCTAD1() {
return dctad1;
}
/**
* Sets the value of the dctad1 property.
*
* @param value
* allowed object is
* {@link DCTAD1 }
*
*/
public void setDCTAD1(DCTAD1 value) {
this.dctad1 = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DADRE1.java
| 2
|
请完成以下Java代码
|
public int getStatistic_Count ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Count);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistic Milliseconds.
@param Statistic_Millis
Internal statistics how many milliseconds a process took
*/
@Override
public void setStatistic_Millis (int Statistic_Millis)
{
|
set_Value (COLUMNNAME_Statistic_Millis, Integer.valueOf(Statistic_Millis));
}
/** Get Statistic Milliseconds.
@return Internal statistics how many milliseconds a process took
*/
@Override
public int getStatistic_Millis ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Millis);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Stats.java
| 1
|
请完成以下Java代码
|
public String getCallbackId() {
return this.callbackId;
}
@Override
public String getCallbackType() {
return this.callbackType;
}
@Override
public String getReferenceId() {
return referenceId;
}
@Override
public String getReferenceType() {
return referenceType;
}
|
@Override
public String getParentId() {
return this.parentId;
}
@Override
public boolean isFallbackToDefaultTenant() {
return this.fallbackToDefaultTenant;
}
@Override
public boolean isStartWithForm() {
return this.startWithForm;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceBuilderImpl.java
| 1
|
请完成以下Java代码
|
public static Duration toWorkDurationRoundUp(@NonNull final BigDecimal durationBD, @NonNull final TemporalUnit unit)
{
return toWorkDuration(durationBD.setScale(0, RoundingMode.UP), unit);
}
public static BigDecimal toBigDecimal(@NonNull final Duration duration, @NonNull final TemporalUnit unit)
{
return BigDecimal.valueOf(toLong(duration, unit));
}
public static Duration fromBigDecimal(@NonNull final BigDecimal duration, @NonNull final TemporalUnit unit)
{
return Duration.of(duration.longValue(), unit);
}
public static int toInt(@NonNull final Duration duration, @NonNull final TemporalUnit unit)
{
return (int)toLong(duration, unit);
}
public static long toLong(@NonNull final Duration duration, @NonNull final TemporalUnit unit)
{
if (unit == ChronoUnit.SECONDS)
{
return duration.getSeconds();
}
else if (unit == ChronoUnit.MINUTES)
{
return duration.toMinutes();
}
else if (unit == ChronoUnit.HOURS)
{
return duration.toHours();
}
else if (unit == ChronoUnit.DAYS)
{
return duration.toDays();
}
else
{
throw Check.newException("Cannot convert " + duration + " to " + unit);
|
}
}
private static BigDecimal getEquivalentInSmallerTemporalUnit(@NonNull final BigDecimal durationBD, @NonNull final TemporalUnit unit)
{
if (unit == ChronoUnit.DAYS)
{
return durationBD.multiply(BigDecimal.valueOf(WORK_HOURS_PER_DAY));// This refers to work hours, not calendar hours
}
if (unit == ChronoUnit.HOURS)
{
return durationBD.multiply(BigDecimal.valueOf(60));
}
if (unit == ChronoUnit.MINUTES)
{
return durationBD.multiply(BigDecimal.valueOf(60));
}
if (unit == ChronoUnit.SECONDS)
{
return durationBD.multiply(BigDecimal.valueOf(1000));
}
throw Check.newException("No smaller temporal unit defined for {}", unit);
}
public static boolean isCompleteDays(@NonNull final Duration duration)
{
if (duration.isZero())
{
return true;
}
final Duration daysAsDuration = Duration.ofDays(duration.toDays());
return daysAsDuration.equals(duration);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\DurationUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JwtConfig {
@Bean
ServerAuthenticationConverter jwtServerAuthenticationConverter(TokenExtractor tokenExtractor) {
return ex -> Mono.justOrEmpty(ex).flatMap(exchange -> {
var headers = exchange.getRequest().getHeaders().get(HttpHeaders.AUTHORIZATION);
if (headers == null || headers.isEmpty()) {
return Mono.empty();
}
var authHeader = headers.get(0);
var token = tokenExtractor.extractToken(authHeader);
return Mono.just(new UsernamePasswordAuthenticationToken(token, token));
});
}
@Bean
ReactiveAuthenticationManager jwtAuthenticationManager(JwtSigner tokenService) {
return authentication -> Mono.justOrEmpty(authentication).map(auth -> {
var token = (String) auth.getCredentials();
var jws = tokenService.validate(token);
var authority = new SimpleGrantedAuthority(("ROLE_USER"));
var userId = jws.getBody().getSubject();
|
var tokenPrincipal = new TokenPrincipal(userId, token);
return new UsernamePasswordAuthenticationToken(
tokenPrincipal,
token,
List.of(authority)
);
});
}
@Bean
AuthenticationWebFilter authenticationFilter(ReactiveAuthenticationManager manager, ServerAuthenticationConverter converter) {
var authenticationWebFilter = new AuthenticationWebFilter(manager);
authenticationWebFilter.setServerAuthenticationConverter(converter);
return authenticationWebFilter;
}
}
|
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\security\JwtConfig.java
| 2
|
请完成以下Java代码
|
public class GuiceModule extends AbstractModule {
@Override
protected void configure() {
try {
bind(AccountService.class).to(AccountServiceImpl.class);
bind(Person.class).toConstructor(Person.class.getConstructor());
// bind(Person.class).toProvider(new Provider<Person>() {
// public Person get() {
// Person p = new Person();
// return p;
// }
// });
bind(Foo.class).toProvider(new Provider<Foo>() {
public Foo get() {
return new Foo();
}
});
|
bind(PersonDao.class).to(PersonDaoImpl.class);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Provides
public BookService bookServiceGenerator() {
return new BookServiceImpl();
}
}
|
repos\tutorials-master\di-modules\guice\src\main\java\com\baeldung\guice\modules\GuiceModule.java
| 1
|
请完成以下Java代码
|
private Document getParentDocument()
{
return parentDocument;
}
public SqlDocumentQueryBuilder setParentDocument(final Document parentDocument)
{
this.parentDocument = parentDocument;
return this;
}
public SqlDocumentQueryBuilder setRecordIds(final Set<DocumentId> recordIds)
{
this.recordIds = recordIds != null
? ImmutableSet.copyOf(recordIds)
: ImmutableSet.of();
return this;
}
public SqlDocumentQueryBuilder noSorting(final boolean noSorting)
{
this.noSorting = noSorting;
if (noSorting)
{
orderBys = DocumentQueryOrderByList.EMPTY;
}
return this;
}
public boolean isSorting()
{
return !isNoSorting();
}
public SqlDocumentQueryBuilder setOrderBys(final DocumentQueryOrderByList orderBys)
{
// Don't throw exception if noSorting is true. Just do nothing.
// REASON: it gives us better flexibility when this builder is handled by different methods, each of them adding stuff to it
// Check.assume(!noSorting, "sorting enabled for {}", this);
if (noSorting)
{
return this;
}
this.orderBys = orderBys != null ? orderBys : DocumentQueryOrderByList.EMPTY;
return this;
}
public SqlDocumentQueryBuilder setPage(final int firstRow, final int pageLength)
{
this.firstRow = firstRow;
this.pageLength = pageLength;
return this;
}
private int getFirstRow()
{
return firstRow;
}
private int getPageLength()
{
return pageLength;
}
public static SqlComposedKey extractComposedKey(
final DocumentId recordId,
final List<? extends SqlEntityFieldBinding> keyFields)
{
|
final int count = keyFields.size();
if (count < 1)
{
throw new AdempiereException("Invalid composed key: " + keyFields);
}
final List<Object> composedKeyParts = recordId.toComposedKeyParts();
if (composedKeyParts.size() != count)
{
throw new AdempiereException("Invalid composed key '" + recordId + "'. Expected " + count + " parts but it has " + composedKeyParts.size());
}
final ImmutableSet.Builder<String> keyColumnNames = ImmutableSet.builder();
final ImmutableMap.Builder<String, Object> values = ImmutableMap.builder();
for (int i = 0; i < count; i++)
{
final SqlEntityFieldBinding keyField = keyFields.get(i);
final String keyColumnName = keyField.getColumnName();
keyColumnNames.add(keyColumnName);
final Object valueObj = composedKeyParts.get(i);
@Nullable final Object valueConv = DataTypes.convertToValueClass(
keyColumnName,
valueObj,
keyField.getWidgetType(),
keyField.getSqlValueClass(),
null);
if (!JSONNullValue.isNull(valueConv))
{
values.put(keyColumnName, valueConv);
}
}
return SqlComposedKey.of(keyColumnNames.build(), values.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentQueryBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private RawMaterialsIssueLine recomputeQtyToIssueForSteps(@NonNull final RawMaterialsIssueLine line)
{
Quantity qtyLeftToBeIssued = line.getQtyLeftToIssue().toZeroIfNegative();
final ImmutableList.Builder<RawMaterialsIssueStep> updatedStepsListBuilder = ImmutableList.builder();
for (final RawMaterialsIssueStep step : line.getSteps())
{
if (step.isIssued())
{
updatedStepsListBuilder.add(step);
}
else if (qtyLeftToBeIssued.isGreaterThan(step.getQtyToIssue()))
{
updatedStepsListBuilder.add(step);
qtyLeftToBeIssued = qtyLeftToBeIssued.subtract(step.getQtyToIssue());
}
else
{
ppOrderIssueScheduleService.updateQtyToIssue(step.getId(), qtyLeftToBeIssued);
updatedStepsListBuilder.add(step.withQtyToIssue(qtyLeftToBeIssued));
qtyLeftToBeIssued = qtyLeftToBeIssued.toZero();
}
}
return line.withSteps(updatedStepsListBuilder.build());
}
@NonNull
private Optional<Quantity> extractTargetCatchWeight(@NonNull final JsonManufacturingOrderEvent.ReceiveFrom receiveFrom)
{
if (receiveFrom.getCatchWeight() == null || Check.isBlank(receiveFrom.getCatchWeightUomSymbol()))
{
return Optional.empty();
}
|
return uomDAO.getBySymbol(receiveFrom.getCatchWeightUomSymbol())
.map(uom -> Quantity.of(receiveFrom.getCatchWeight(), uom));
}
public QueryLimit getLaunchersLimit()
{
final int limitInt = sysConfigBL.getIntValue(Constants.SYSCONFIG_LaunchersLimit, -100);
return limitInt == -100
? Constants.DEFAULT_LaunchersLimit
: QueryLimit.ofInt(limitInt);
}
public ManufacturingJob autoIssueWhatWasReceived(
@NonNull final ManufacturingJob job,
@NonNull final RawMaterialsIssueStrategy issueStrategy)
{
return newIssueWhatWasReceivedCommand()
.job(job)
.issueStrategy(issueStrategy)
.build().execute();
}
public IssueWhatWasReceivedCommandBuilder newIssueWhatWasReceivedCommand()
{
return IssueWhatWasReceivedCommand.builder()
.issueScheduleService(ppOrderIssueScheduleService)
.jobService(this)
.ppOrderSourceHUService(ppOrderSourceHUService)
.sourceHUsService(sourceHUsService);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private String getDeviceClassname(@NonNull final String deviceName)
{
// note: assume not null because in that case, the method above would fail
return getSysconfigValueWithHostNameFallback(CFG_DEVICE_PREFIX + "." + deviceName, DEVICE_PARAM_DeviceClass, null);
}
private Set<String> getDeviceRequestClassnames(final String deviceName, final AttributeCode attributeCode)
{
final Map<String, String> requestClassNames = sysConfigBL.getValuesForPrefix(CFG_DEVICE_PREFIX + "." + deviceName + "." + attributeCode.getCode(), clientAndOrgId);
return ImmutableSet.copyOf(requestClassNames.values());
}
/**
* @return value; never returns null
* @throws DeviceConfigException if configuration parameter was not found and given <code>defaultStr</code> is <code>null</code>.
*/
private String getSysconfigValueWithHostNameFallback(final String prefix, final String suffix, final @Nullable String defaultValue)
{
//
// Try by hostname
final String deviceKeyWithHostName = prefix + "." + clientHost.getHostName() + "." + suffix;
{
final String value = sysConfigBL.getValue(deviceKeyWithHostName, clientAndOrgId);
if (value != null)
{
return value;
}
}
//
// Try by host's IP
final String deviceKeyWithIP = prefix + "." + clientHost.getIP() + "." + suffix;
{
final String value = sysConfigBL.getValue(deviceKeyWithIP, clientAndOrgId);
if (value != null)
{
return value;
}
}
|
//
// Try by any host (i.e. 0.0.0.0)
final String deviceKeyWithWildCard = prefix + "." + IPADDRESS_ANY + "." + suffix;
{
final String value = sysConfigBL.getValue(deviceKeyWithWildCard, clientAndOrgId);
if (value != null)
{
return value;
}
}
//
// Fallback to default
if (defaultValue != null)
{
return defaultValue;
}
//
// Throw exception
throw new DeviceConfigException("@NotFound@: @AD_SysConfig@ " + deviceKeyWithHostName
+ ", " + deviceKeyWithIP + ", " + deviceKeyWithWildCard
+ "; @AD_Client_ID@=" + clientAndOrgId.getClientId()
+ " @AD_Org_ID@=" + clientAndOrgId.getOrgId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\SysConfigDeviceConfigPool.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getTAXQUAL() {
return taxqual;
}
/**
* Sets the value of the taxqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXQUAL(String value) {
this.taxqual = value;
}
/**
* Gets the value of the taxcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXCODE() {
return taxcode;
}
/**
* Sets the value of the taxcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXCODE(String value) {
this.taxcode = value;
}
/**
* Gets the value of the taxrate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXRATE() {
return taxrate;
}
/**
* Sets the value of the taxrate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXRATE(String value) {
this.taxrate = value;
}
/**
* Gets the value of the taxcategory property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXCATEGORY() {
return taxcategory;
}
/**
* Sets the value of the taxcategory property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXCATEGORY(String value) {
this.taxcategory = value;
}
/**
* Gets the value of the taxamount property.
*
* @return
|
* possible object is
* {@link String }
*
*/
public String getTAXAMOUNT() {
return taxamount;
}
/**
* Sets the value of the taxamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXAMOUNT(String value) {
this.taxamount = value;
}
/**
* Gets the value of the taxableamount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXABLEAMOUNT() {
return taxableamount;
}
/**
* Sets the value of the taxableamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXABLEAMOUNT(String value) {
this.taxableamount = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DTAXI1.java
| 2
|
请完成以下Java代码
|
public VariableResource getVariablesResource() {
return new ExecutionVariablesResource(engine, processInstanceId, true, objectMapper);
}
@Override
public ActivityInstanceDto getActivityInstanceTree() {
RuntimeService runtimeService = engine.getRuntimeService();
ActivityInstance activityInstance = null;
try {
activityInstance = runtimeService.getActivityInstance(processInstanceId);
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
}
if (activityInstance == null) {
throw new InvalidRequestException(Status.NOT_FOUND, "Process instance with id " + processInstanceId + " does not exist");
}
ActivityInstanceDto result = ActivityInstanceDto.fromActivityInstance(activityInstance);
return result;
}
@Override
public void updateSuspensionState(SuspensionStateDto dto) {
dto.updateSuspensionState(engine, processInstanceId);
}
@Override
public void modifyProcessInstance(ProcessInstanceModificationDto dto) {
if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) {
ProcessInstanceModificationBuilder modificationBuilder =
engine.getRuntimeService().createProcessInstanceModification(processInstanceId);
dto.applyTo(modificationBuilder, engine, objectMapper);
if (dto.getAnnotation() != null) {
modificationBuilder.setAnnotation(dto.getAnnotation());
|
}
modificationBuilder.cancellationSourceExternal(true);
modificationBuilder.execute(dto.isSkipCustomListeners(), dto.isSkipIoMappings());
}
}
@Override
public BatchDto modifyProcessInstanceAsync(ProcessInstanceModificationDto dto) {
Batch batch = null;
if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) {
ProcessInstanceModificationBuilder modificationBuilder =
engine.getRuntimeService().createProcessInstanceModification(processInstanceId);
dto.applyTo(modificationBuilder, engine, objectMapper);
if (dto.getAnnotation() != null) {
modificationBuilder.setAnnotation(dto.getAnnotation());
}
modificationBuilder.cancellationSourceExternal(true);
try {
batch = modificationBuilder.executeAsync(dto.isSkipCustomListeners(), dto.isSkipIoMappings());
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
return BatchDto.fromBatch(batch);
}
throw new InvalidRequestException(Status.BAD_REQUEST, "The provided instuctions are invalid.");
}
@Override
public ProcessInstanceCommentResource getProcessInstanceCommentResource() {
return new ProcessInstanceCommentResourceImpl(engine, processInstanceId);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\ProcessInstanceResourceImpl.java
| 1
|
请完成以下Java代码
|
public List<HistoricActivityStatisticsDto> getHistoricActivityStatistics(UriInfo uriInfo, String processDefinitionId) {
HistoricActivityStatisticsQueryDto queryDto = new HistoricActivityStatisticsQueryDto(getObjectMapper(), processDefinitionId, uriInfo.getQueryParameters());
HistoricActivityStatisticsQuery query = queryDto.toQuery(getProcessEngine());
List<HistoricActivityStatisticsDto> result = new ArrayList<>();
List<HistoricActivityStatistics> statistics = query.unlimitedList();
for (HistoricActivityStatistics currentStatistics : statistics) {
result.add(HistoricActivityStatisticsDto.fromHistoricActivityStatistics(currentStatistics));
}
return result;
}
@Override
public List<CleanableHistoricProcessInstanceReportResultDto> getCleanableHistoricProcessInstanceReport(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
CleanableHistoricProcessInstanceReportDto queryDto = new CleanableHistoricProcessInstanceReportDto(objectMapper, uriInfo.getQueryParameters());
CleanableHistoricProcessInstanceReport query = queryDto.toQuery(getProcessEngine());
List<CleanableHistoricProcessInstanceReportResult> reportResult = QueryUtil.list(query, firstResult, maxResults);
|
return CleanableHistoricProcessInstanceReportResultDto.convert(reportResult);
}
@Override
public CountResultDto getCleanableHistoricProcessInstanceReportCount(UriInfo uriInfo) {
CleanableHistoricProcessInstanceReportDto queryDto = new CleanableHistoricProcessInstanceReportDto(objectMapper, uriInfo.getQueryParameters());
queryDto.setObjectMapper(objectMapper);
CleanableHistoricProcessInstanceReport query = queryDto.toQuery(getProcessEngine());
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricProcessDefinitionRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public class POResultSet<T> implements Iterator<T>
{
private final Properties ctx;
private final String tableName;
private final Class<T> clazz;
private final String trxName;
private PreparedStatement statement;
private ResultSet resultSet;
/** Current fetched PO */
private T currentPO = null;
/** Should we close the statement and resultSet on any exception that occur ? */
private boolean closeOnError = true;
/**
* Constructs the POResultSet.
* By default, closeOnError option is false. You need to set it explicitly.
* @param table
* @param ps
* @param rs
* @param trxName
*/
public POResultSet(final Properties ctx, final String tableName, final Class<T> clazz, final PreparedStatement ps, final ResultSet rs, final String trxName)
{
super();
this.ctx = ctx;
this.tableName = tableName;
this.clazz = clazz;
this.statement = ps;
this.resultSet = rs;
this.trxName = trxName;
this.closeOnError = false;
}
/**
*
* @return true if it has next, false otherwise
* @throws DBException
*/
@Override
public boolean hasNext() throws DBException {
if (currentPO != null)
return true;
currentPO = next();
return currentPO != null;
}
/**
*
* @return PO or null if reach the end of resultset
* @throws DBException
*/
@Override
public T next() throws DBException {
if (currentPO != null) {
T po = currentPO;
currentPO = null;
return po;
}
try {
if ( resultSet.next() )
{
final PO o = TableModelLoader.instance.getPO(ctx, tableName, resultSet, trxName);
if (clazz != null && !o.getClass().isAssignableFrom(clazz))
{
return InterfaceWrapperHelper.create(o, clazz);
}
else
{
@SuppressWarnings("unchecked")
final T retValue = (T)o;
return retValue;
}
}
else
{
this.close(); // close it if there is no more data to read
return null;
}
}
catch (SQLException e) {
if (this.closeOnError) {
this.close();
}
|
throw new DBException(e);
}
// Catching any RuntimeException, and close the resultset (if closeOnError is set)
catch (RuntimeException e) {
if (this.closeOnError) {
this.close();
}
throw e;
}
}
/**
* Should we automatically close the {@link PreparedStatement} and {@link ResultSet} in case
* we get an error.
* @param closeOnError
*/
public void setCloseOnError(boolean closeOnError) {
this.closeOnError = closeOnError;
}
/**
* Will be the {@link PreparedStatement} and {@link ResultSet} closed on any database exception
* @return true if yes, false otherwise
*/
public boolean isCloseOnError() {
return this.closeOnError;
}
/**
* Release database resources.
*/
public void close() {
DB.close(this.resultSet, this.statement);
this.resultSet = null;
this.statement = null;
currentPO = null;
}
@Override
public void remove()
{
throw new UnsupportedOperationException("Remove is not supported");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POResultSet.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DeptWrapper extends BaseEntityWrapper<Dept, DeptVO> {
private static IDeptService deptService;
static {
deptService = SpringUtil.getBean(IDeptService.class);
}
public static DeptWrapper build() {
return new DeptWrapper();
}
@Override
public DeptVO entityVO(Dept dept) {
DeptVO deptVO = BeanUtil.copyProperties(dept, DeptVO.class);
|
if (Func.equals(dept.getParentId(), CommonConstant.TOP_PARENT_ID)) {
deptVO.setParentName(CommonConstant.TOP_PARENT_NAME);
} else {
Dept parent = deptService.getById(dept.getParentId());
deptVO.setParentName(parent.getDeptName());
}
return deptVO;
}
public List<DeptVO> listNodeVO(List<Dept> list) {
List<DeptVO> collect = list.stream().map(dept -> BeanUtil.copyProperties(dept, DeptVO.class)).collect(Collectors.toList());
return ForestNodeMerger.merge(collect);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\wrapper\DeptWrapper.java
| 2
|
请完成以下Java代码
|
public CalloutStatisticsEntry setStatusExecuted()
{
duration = duration == null ? null : duration.stop();
if (status != Status.Started)
{
logger.warn("Callout statistics internal bug: changing status from {} to {} for {}", status, Status.Executed, this);
}
status = Status.Executed;
_nodeSummary = null; // reset
return this;
}
public CalloutStatisticsEntry setStatusSkipped(final String skipReasonSummary)
{
final String skipReasonDetails = null;
return setStatusSkipped(skipReasonSummary, skipReasonDetails);
}
public CalloutStatisticsEntry setStatusSkipped(final String skipReasonSummary, final String skipReasonDetails)
{
if (status != Status.Unknown)
{
logger.warn("Callout statistics internal bug: changing status from {} to {} for {}", status, Status.Skipped, this);
}
status = Status.Skipped;
this.skipReasonSummary = skipReasonSummary;
this.skipReasonDetails = skipReasonDetails;
_nodeSummary = null; // reset
return this;
}
public CalloutStatisticsEntry setStatusFailed(final Throwable exception)
{
duration = duration == null ? null : duration.stop();
this.exception = exception;
status = Status.Failed;
_nodeSummary = null; // reset
return this;
}
|
public CalloutStatisticsEntry getCreateChild(final ICalloutField field, final ICalloutInstance callout)
{
final ArrayKey key = Util.mkKey(field.getColumnName(), callout);
return children.computeIfAbsent(key, (theKey) -> new CalloutStatisticsEntry(indexSupplier, field, callout));
}
public CalloutStatisticsEntry childSkipped(final String columnName, final String reason)
{
logger.trace("Skip executing all callouts for {} because {}", columnName, reason);
countChildFieldsSkipped++;
return this;
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final String reason)
{
logger.trace("Skip executing all callouts for {} because {}", field, reason);
countChildFieldsSkipped++;
return this;
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final ICalloutInstance callout, final String reasonSummary)
{
final String reasonDetails = null;
return childSkipped(field, callout, reasonSummary, reasonDetails);
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final ICalloutInstance callout, final String reasonSummary, final String reasonDetails)
{
logger.trace("Skip executing callout {} for field {} because {} ({})", callout, field, reasonSummary, reasonDetails);
getCreateChild(field, callout).setStatusSkipped(reasonSummary, reasonDetails);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\CalloutExecutor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Job extends BaseEntity implements Serializable {
@Id
@Column(name = "job_id")
@NotNull(groups = Update.class)
@ApiModelProperty(value = "ID", hidden = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@ApiModelProperty(value = "岗位名称")
private String name;
@NotNull
@ApiModelProperty(value = "岗位排序")
private Long jobSort;
@NotNull
@ApiModelProperty(value = "是否启用")
private Boolean enabled;
@Override
public boolean equals(Object o) {
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Job job = (Job) o;
return Objects.equals(id, job.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\domain\Job.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Encoding getEncoding() {
return this.encoding;
}
public void setEncoding(Encoding encoding) {
this.encoding = encoding;
}
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
/**
|
* Zipkin message encoding.
*/
public enum Encoding {
/**
* JSON.
*/
JSON,
/**
* Protocol Buffers v3.
*/
PROTO3
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-zipkin\src\main\java\org\springframework\boot\zipkin\autoconfigure\ZipkinProperties.java
| 2
|
请完成以下Java代码
|
private ImmutableMap<String, Object> getParameters()
{
return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of();
}
public Builder applySecurityRestrictions(final boolean applySecurityRestrictions)
{
this.applySecurityRestrictions = applySecurityRestrictions;
return this;
}
private boolean isApplySecurityRestrictions()
{
return applySecurityRestrictions;
}
}
//
//
//
//
//
@ToString
private static final class WrappedDocumentFilterList
{
public static WrappedDocumentFilterList ofFilters(final DocumentFilterList filters)
{
if (filters == null || filters.isEmpty())
{
return EMPTY;
}
final ImmutableList<JSONDocumentFilter> jsonFiltersEffective = null;
return new WrappedDocumentFilterList(jsonFiltersEffective, filters);
}
public static WrappedDocumentFilterList ofJSONFilters(final List<JSONDocumentFilter> jsonFilters)
{
if (jsonFilters == null || jsonFilters.isEmpty())
{
return EMPTY;
}
final ImmutableList<JSONDocumentFilter> jsonFiltersEffective = ImmutableList.copyOf(jsonFilters);
final DocumentFilterList filtersEffective = null;
|
return new WrappedDocumentFilterList(jsonFiltersEffective, filtersEffective);
}
public static final WrappedDocumentFilterList EMPTY = new WrappedDocumentFilterList();
private final ImmutableList<JSONDocumentFilter> jsonFilters;
private final DocumentFilterList filters;
private WrappedDocumentFilterList(@Nullable final ImmutableList<JSONDocumentFilter> jsonFilters, @Nullable final DocumentFilterList filters)
{
this.jsonFilters = jsonFilters;
this.filters = filters;
}
/**
* empty constructor
*/
private WrappedDocumentFilterList()
{
filters = DocumentFilterList.EMPTY;
jsonFilters = null;
}
public DocumentFilterList unwrap(final DocumentFilterDescriptorsProvider descriptors)
{
if (filters != null)
{
return filters;
}
if (jsonFilters == null || jsonFilters.isEmpty())
{
return DocumentFilterList.EMPTY;
}
return JSONDocumentFilter.unwrapList(jsonFilters, descriptors);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\CreateViewRequest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static Set<Class<?>> getClassesToAdd() {
Set<Class<?>> classesToAdd = new HashSet<>();
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(Configurable.class));
Set<BeanDefinition> components = provider.findCandidateComponents(ROOT_GATEWAY_PACKAGE_NAME);
for (BeanDefinition component : components) {
Class clazz;
try {
clazz = Class.forName(component.getBeanClassName());
if (shouldRegisterClass(clazz)) {
classesToAdd.add(clazz);
}
}
catch (NoClassDefFoundError | ClassNotFoundException exception) {
if (LOG.isDebugEnabled()) {
LOG.debug(exception);
}
}
}
|
return classesToAdd;
}
private static boolean shouldRegisterClass(Class<?> clazz) {
Set<String> conditionClasses = beansConditionalOnClasses.getOrDefault(clazz, Collections.emptySet());
for (String conditionClass : conditionClasses) {
try {
ConfigurableHintsRegistrationProcessor.class.getClassLoader().loadClass(conditionClass);
}
catch (ClassNotFoundException e) {
return false;
}
}
return true;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\ConfigurableHintsRegistrationProcessor.java
| 2
|
请完成以下Java代码
|
public WebuiImageId uploadImage(final MultipartFile file) throws IOException
{
final String name = file.getOriginalFilename();
final byte[] data = file.getBytes();
final String contentType = file.getContentType();
final String filenameNorm = normalizeUploadFilename(name, contentType);
final MImage adImage = new MImage(Env.getCtx(), 0, ITrx.TRXNAME_None);
adImage.setName(filenameNorm);
adImage.setBinaryData(data);
// TODO: introduce adImage.setTemporary(true);
InterfaceWrapperHelper.save(adImage);
return WebuiImageId.ofRepoId(adImage.getAD_Image_ID());
}
@VisibleForTesting
static String normalizeUploadFilename(final String name, final String contentType)
{
final String fileExtension = MimeType.getExtensionByType(contentType);
final String nameNormalized;
if (Check.isEmpty(name, true)
|| "blob".equals(name) // HARDCODED: this happens when the image is taken from webcam
)
{
nameNormalized = DATE_FORMAT.format(SystemTime.asZonedDateTime());
}
else
{
nameNormalized = name.trim();
}
|
return FileUtil.changeFileExtension(nameNormalized, fileExtension);
}
public WebuiImage getWebuiImage(@NonNull final WebuiImageId imageId, final int maxWidth, final int maxHeight)
{
final AdImage adImage = adImageRepository.getById(imageId.toAdImageId());
return WebuiImage.of(adImage, maxWidth, maxHeight);
}
public ResponseEntity<byte[]> getEmptyImage()
{
return ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.IMAGE_PNG)
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"\"")
.body(BaseEncoding.base64().decode(EMPTY_PNG_BASE64));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\WebuiImageService.java
| 1
|
请完成以下Java代码
|
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public Integer getProcessDefinitionVersion() {
return processDefinitionVersion;
}
public String getDeploymentId() {
return deploymentId;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Long getDurationInMillis() {
return durationInMillis;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
|
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public void setProcessDefinitionVersion(Integer processDefinitionVersion) {
this.processDefinitionVersion = processDefinitionVersion;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricScopeInstanceEntity.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8080
spring:
activemq:
switch: true
broker-url: tcp://60.205.191.82:8081
user: admin
password: admin
in-memory: true
pool.enabled: false
dynamic:
attr:
switch: true
count: 5
annotate:
switch: true
key:
|
temp
defaultVal: default-person
unpredictable:
key: dynamic.annotate.key
value: one,two,three
|
repos\spring-boot-quick-master\quick-dynamic-bean\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public Set<Attribute> getByCodes(final Set<AttributeCode> attributeCodes)
{
if (attributeCodes.isEmpty()) {return ImmutableSet.of();}
return attributeCodes.stream()
.distinct()
.map(this::getByCode)
.collect(ImmutableSet.toImmutableSet());
}
@NonNull
public ImmutableList<AttributeCode> getOrderedAttributeCodesByIds(@NonNull final List<AttributeId> orderedAttributeIds)
{
if (orderedAttributeIds.isEmpty())
{
return ImmutableList.of();
}
return orderedAttributeIds.stream()
.map(this::getById)
.filter(Attribute::isActive)
|
.map(Attribute::getAttributeCode)
.collect(ImmutableList.toImmutableList());
}
public Stream<Attribute> streamActive()
{
return attributesById.values().stream().filter(Attribute::isActive);
}
public boolean isActiveAttribute(final AttributeId id)
{
final Attribute attribute = getByIdOrNull(id);
return attribute != null && attribute.isActive();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributesMap.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Optional<JsonRequestWarehouseUpsertItem> mapWarehouseToRequestItem(@NonNull final GetWarehouseFromFileRouteContext routeContext)
{
final WarehouseRow warehouseRow = routeContext.getWarehouseRow();
final PInstanceLogger pInstanceLogger = routeContext.getPInstanceLogger();
if (hasMissingFields(warehouseRow))
{
pInstanceLogger.logMessage("Skipping row due to missing mandatory information, see row: " + warehouseRow);
return Optional.empty();
}
final JsonRequestWarehouseUpsertItem requestWarehouseUpsertItem = JsonRequestWarehouseUpsertItem.builder()
.warehouseIdentifier(ExternalId.ofId(warehouseRow.getWarehouseIdentifier()).toExternalIdentifierString())
.requestWarehouse(getJsonRequestWarehouse(warehouseRow))
.build();
return Optional.of(requestWarehouseUpsertItem);
}
@NonNull
private static JsonRequestWarehouse getJsonRequestWarehouse(@NonNull final WarehouseRow warehouseRow)
{
final JsonRequestWarehouse requestWarehouse = new JsonRequestWarehouse();
requestWarehouse.setName(warehouseRow.getName());
requestWarehouse.setCode(warehouseRow.getWarehouseValue());
requestWarehouse.setBpartnerLocationIdentifier(ExternalId.ofId(warehouseRow.getWarehouseIdentifier()).toExternalIdentifierString());
|
requestWarehouse.setActive(true);
return requestWarehouse;
}
private static boolean hasMissingFields(@NonNull final WarehouseRow warehouseRow)
{
return Check.isBlank(warehouseRow.getWarehouseIdentifier())
|| Check.isBlank(warehouseRow.getName())
|| Check.isBlank(warehouseRow.getWarehouseValue());
}
@NonNull
private static JsonRequestWarehouseUpsert wrapUpsertItem(@NonNull final JsonRequestWarehouseUpsertItem upsertItem)
{
return JsonRequestWarehouseUpsert.builder()
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.requestItems(ImmutableList.of(upsertItem))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\warehouse\processor\CreateWarehouseUpsertRequestProcessor.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Connection getConnection() throws SQLException {
return null;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
|
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
};
}
}
|
repos\tutorials-master\libraries\src\main\java\com\baeldung\activej\config\PersonModule.java
| 2
|
请完成以下Java代码
|
public String getEndUserId() {
return endUserId;
}
@Override
public void setEndUserId(String endUserId) {
this.endUserId = endUserId;
}
@Override
public Map<String, Object> getCaseVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
@Override
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
@Override
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
@Override
public void setCaseDefinitionKey(String caseDefinitionKey) {
this.caseDefinitionKey = caseDefinitionKey;
}
@Override
public String getCaseDefinitionName() {
return caseDefinitionName;
}
|
@Override
public void setCaseDefinitionName(String caseDefinitionName) {
this.caseDefinitionName = caseDefinitionName;
}
@Override
public Integer getCaseDefinitionVersion() {
return caseDefinitionVersion;
}
@Override
public void setCaseDefinitionVersion(Integer caseDefinitionVersion) {
this.caseDefinitionVersion = caseDefinitionVersion;
}
@Override
public String getCaseDefinitionDeploymentId() {
return caseDefinitionDeploymentId;
}
@Override
public void setCaseDefinitionDeploymentId(String caseDefinitionDeploymentId) {
this.caseDefinitionDeploymentId = caseDefinitionDeploymentId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricCaseInstance[id=").append(id)
.append(", caseDefinitionId=").append(caseDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricCaseInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
public void subscribe(Subscriber<? super Payload> subscriber) {
this.subscriber = subscriber;
fireAtWill();
}
/**
* Publish game events asynchronously
*/
private void fireAtWill() {
new Thread(() -> {
for (Long shotDelay : shots) {
try { Thread.sleep(shotDelay); } catch (Exception x) {}
if (truce) {
break;
}
LOG.info("{}: bang!", playerName);
subscriber.onNext(DefaultPayload.create("bang!"));
}
if (!truce) {
LOG.info("{}: I give up!", playerName);
subscriber.onNext(DefaultPayload.create("I give up"));
}
subscriber.onComplete();
}).start();
|
}
/**
* Process events from the opponent
*
* @param payload Payload received from the rSocket
*/
public void processPayload(Payload payload) {
String message = payload.getDataUtf8();
switch (message) {
case "bang!":
String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!";
LOG.info("{}: {}", playerName, result);
break;
case "I give up":
truce = true;
LOG.info("{}: OK, truce", playerName);
break;
}
}
}
|
repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\support\GameController.java
| 1
|
请完成以下Java代码
|
public boolean isValidAlphabeticStringResult() {
return validAlphabeticStringResult;
}
public void setValidAlphabeticStringResult(boolean validAlphabeticStringResult) {
this.validAlphabeticStringResult = validAlphabeticStringResult;
}
public boolean isInvalidAlphabeticStringResult() {
return invalidAlphabeticStringResult;
}
public void setInvalidAlphabeticStringResult(boolean invalidAlphabeticStringResult) {
this.invalidAlphabeticStringResult = invalidAlphabeticStringResult;
}
public boolean isValidFormatOfHorsePower() {
return validFormatOfHorsePower;
|
}
public void setValidFormatOfHorsePower(boolean validFormatOfHorsePower) {
this.validFormatOfHorsePower = validFormatOfHorsePower;
}
@Override
public String toString() {
return "SpelRegex{" +
"validNumericStringResult=" + validNumericStringResult +
", invalidNumericStringResult=" + invalidNumericStringResult +
", validAlphabeticStringResult=" + validAlphabeticStringResult +
", invalidAlphabeticStringResult=" + invalidAlphabeticStringResult +
", validFormatOfHorsePower=" + validFormatOfHorsePower +
'}';
}
}
|
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelRegex.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RpTradePaymentRecordDaoImpl extends BaseDaoImpl<RpTradePaymentRecord> implements RpTradePaymentRecordDao {
/**
* 根据银行订单号获取支付信息
*
* @param bankOrderNo
* @return
*/
@Override
public RpTradePaymentRecord getByBankOrderNo(String bankOrderNo) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("bankOrderNo", bankOrderNo);
return super.getBy(paramMap);
}
/**
* 根据商户编号及商户订单号获取支付结果
*
* @param merchantNo
* @param merchantOrderNo
* @return
*/
@Override
public RpTradePaymentRecord getSuccessRecordByMerchantNoAndMerchantOrderNo(String merchantNo, String merchantOrderNo) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", TradeStatusEnum.SUCCESS.name());
paramMap.put("merchantNo", merchantNo);
paramMap.put("merchantOrderNo", merchantOrderNo);
return super.getBy(paramMap);
}
/**
* 根据支付流水号查询支付记录
*
* @param trxNo
|
* @return
*/
public RpTradePaymentRecord getByTrxNo(String trxNo) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("trxNo", trxNo);
return super.getBy(paramMap);
}
public List<Map<String, String>> getPaymentReport(String merchantNo){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", TradeStatusEnum.SUCCESS.name());
paramMap.put("merchantNo", merchantNo);
return super.getSessionTemplate().selectList(getStatement("getPaymentReport"),paramMap);
}
public List<Map<String, String>> getPayWayReport(String merchantNo){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", TradeStatusEnum.SUCCESS.name());
paramMap.put("merchantNo", merchantNo);
return super.getSessionTemplate().selectList(getStatement("getPayWayReport"),paramMap);
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\dao\impl\RpTradePaymentRecordDaoImpl.java
| 2
|
请完成以下Java代码
|
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
@CamundaQueryParam(value = "includeJobDefinitionsWithoutTenantId", converter = BooleanConverter.class)
public void setIncludeJobDefinitionsWithoutTenantId(Boolean includeJobDefinitionsWithoutTenantId) {
this.includeJobDefinitionsWithoutTenantId = includeJobDefinitionsWithoutTenantId;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected JobDefinitionQuery createNewQuery(ProcessEngine engine) {
return engine.getManagementService().createJobDefinitionQuery();
}
@Override
protected void applyFilters(JobDefinitionQuery query) {
if (jobDefinitionId != null) {
query.jobDefinitionId(jobDefinitionId);
}
if (activityIdIn != null && activityIdIn.length > 0) {
query.activityIdIn(activityIdIn);
}
if (processDefinitionId != null) {
query.processDefinitionId(processDefinitionId);
}
if (processDefinitionKey != null) {
query.processDefinitionKey(processDefinitionKey);
}
if (jobType != null) {
query.jobType(jobType);
}
if (jobConfiguration != null) {
query.jobConfiguration(jobConfiguration);
}
if (TRUE.equals(active)) {
query.active();
}
if (TRUE.equals(suspended)) {
query.suspended();
}
if (TRUE.equals(withOverridingJobPriority)) {
query.withOverridingJobPriority();
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
|
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeJobDefinitionsWithoutTenantId)) {
query.includeJobDefinitionsWithoutTenantId();
}
}
@Override
protected void applySortBy(JobDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_JOB_DEFINITION_ID)) {
query.orderByJobDefinitionId();
} else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) {
query.orderByActivityId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) {
query.orderByProcessDefinitionId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) {
query.orderByProcessDefinitionKey();
} else if (sortBy.equals(SORT_BY_JOB_TYPE)) {
query.orderByJobType();
} else if (sortBy.equals(SORT_BY_JOB_CONFIGURATION)) {
query.orderByJobConfiguration();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\management\JobDefinitionQueryDto.java
| 1
|
请完成以下Java代码
|
public Duration getTimeToLive() {
if (timeToLive == null) {
LOGGER.debug(String.format(
"No TTL configuration found. Default TTL will be applied for cache entries: %s minutes",
DEFAULT_CACHE_TTL_MINUTES));
return DEFAULT_CACHE_TTL_MINUTES;
}
else {
return timeToLive;
}
}
public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive;
}
public RequestOptions getRequest() {
return request;
}
public void setRequest(RequestOptions request) {
this.request = request;
}
@Override
public String toString() {
return "LocalResponseCacheProperties{" + "size=" + size + ", timeToLive=" + timeToLive + ", request=" + request
+ '}';
}
public static class RequestOptions {
private NoCacheStrategy noCacheStrategy = NoCacheStrategy.SKIP_UPDATE_CACHE_ENTRY;
public NoCacheStrategy getNoCacheStrategy() {
|
return noCacheStrategy;
}
public void setNoCacheStrategy(NoCacheStrategy noCacheStrategy) {
this.noCacheStrategy = noCacheStrategy;
}
@Override
public String toString() {
return "RequestOptions{" + "noCacheStrategy=" + noCacheStrategy + '}';
}
}
/**
* When client sends "no-cache" directive in "Cache-Control" header, the response
* should be re-validated from upstream. There are several strategies that indicates
* what to do with the new fresh response.
*/
public enum NoCacheStrategy {
/**
* Update the cache entry by the fresh response coming from upstream with a new
* time to live.
*/
UPDATE_CACHE_ENTRY,
/**
* Skip the update. The client will receive the fresh response, other clients will
* receive the old entry in cache.
*/
SKIP_UPDATE_CACHE_ENTRY
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\LocalResponseCacheProperties.java
| 1
|
请完成以下Java代码
|
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Foo other = (Foo) obj;
if (intValue != other.intValue) {
return false;
}
if (stringValue == null) {
|
if (other.stringValue != null) {
return false;
}
} else if (!stringValue.equals(other.stringValue)) {
return false;
}
return true;
}
@Override
public String toString() {
return "TargetClass{" + "intValue= " + intValue + ", stringValue= " + stringValue + '}';
}
}
|
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\deserialization\Foo.java
| 1
|
请完成以下Java代码
|
public boolean shouldFilter() {
// specific APIs can be filtered out using
// if (RequestContext.getCurrentContext().getRequest().getRequestURI().startsWith("/api")) { ... }
return true;
}
@Override
public Object run() {
String bucketId = getId(RequestContext.getCurrentContext().getRequest());
Bucket bucket = buckets.getProxy(bucketId, getConfigSupplier());
if (bucket.tryConsume(1)) {
// the limit is not exceeded
log.debug("API rate limit OK for {}", bucketId);
} else {
// limit is exceeded
log.info("API rate limit exceeded for {}", bucketId);
apiLimitExceeded();
}
return null;
}
private Supplier<BucketConfiguration> getConfigSupplier() {
return () -> {
JHipsterProperties.Gateway.RateLimiting rateLimitingProperties =
jHipsterProperties.getGateway().getRateLimiting();
|
return Bucket4j.configurationBuilder()
.addLimit(Bandwidth.simple(rateLimitingProperties.getLimit(),
Duration.ofSeconds(rateLimitingProperties.getDurationInSeconds())))
.build();
};
}
/**
* Create a Zuul response error when the API limit is exceeded.
*/
private void apiLimitExceeded() {
RequestContext ctx = RequestContext.getCurrentContext();
ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
if (ctx.getResponseBody() == null) {
ctx.setResponseBody("API rate limit exceeded");
ctx.setSendZuulResponse(false);
}
}
/**
* The ID that will identify the limit: the user login or the user IP address.
*/
private String getId(HttpServletRequest httpServletRequest) {
return SecurityUtils.getCurrentUserLogin().orElse(httpServletRequest.getRemoteAddr());
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\ratelimiting\RateLimitingFilter.java
| 1
|
请完成以下Java代码
|
protected void setReferenceIdentifier(ModelElementInstance referenceSourceElement, String referenceIdentifier) {
if (referenceIdentifier != null && !referenceIdentifier.isEmpty()) {
super.setReferenceIdentifier(referenceSourceElement, referenceIdentifier);
} else {
referenceSourceAttribute.removeAttribute(referenceSourceElement);
}
}
/**
* @param referenceSourceElement
* @param o
*/
protected void performRemoveOperation(ModelElementInstance referenceSourceElement, Object o) {
removeReference(referenceSourceElement, (ModelElementInstance) o);
}
|
protected void performAddOperation(ModelElementInstance referenceSourceElement, T referenceTargetElement) {
String identifier = getReferenceIdentifier(referenceSourceElement);
List<String> references = StringUtil.splitListBySeparator(identifier, separator);
String targetIdentifier = getTargetElementIdentifier(referenceTargetElement);
references.add(targetIdentifier);
identifier = StringUtil.joinList(references, separator);
setReferenceIdentifier(referenceSourceElement, identifier);
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\type\reference\AttributeReferenceCollection.java
| 1
|
请完成以下Java代码
|
public final class DefaultOAuth2TokenContext implements OAuth2TokenContext {
private final Map<Object, Object> context;
private DefaultOAuth2TokenContext(Map<Object, Object> context) {
this.context = Collections.unmodifiableMap(new HashMap<>(context));
}
@SuppressWarnings("unchecked")
@Nullable
@Override
public <V> V get(Object key) {
return hasKey(key) ? (V) this.context.get(key) : null;
}
@Override
public boolean hasKey(Object key) {
Assert.notNull(key, "key cannot be null");
return this.context.containsKey(key);
}
/**
* Returns a new {@link Builder}.
* @return the {@link Builder}
*/
public static Builder builder() {
|
return new Builder();
}
/**
* A builder for {@link DefaultOAuth2TokenContext}.
*/
public static final class Builder extends AbstractBuilder<DefaultOAuth2TokenContext, Builder> {
private Builder() {
}
/**
* Builds a new {@link DefaultOAuth2TokenContext}.
* @return the {@link DefaultOAuth2TokenContext}
*/
@Override
public DefaultOAuth2TokenContext build() {
return new DefaultOAuth2TokenContext(getContext());
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\DefaultOAuth2TokenContext.java
| 1
|
请完成以下Java代码
|
public class GlobalAccessTokenFilter implements GlobalFilter, Ordered {
public final static String X_ACCESS_TOKEN = "X-Access-Token";
public final static String X_GATEWAY_BASE_PATH = "X_GATEWAY_BASE_PATH";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String scheme = exchange.getRequest().getURI().getScheme();
String host = exchange.getRequest().getURI().getHost();
int port = exchange.getRequest().getURI().getPort();
// 代码逻辑说明: 地址中没有带端口(http/https默认)时port是-1------------
String basePath = scheme + "://" + host;
if (port != -1) {
basePath += ":" + port;
}
// 1. 重写StripPrefix(获取真实的URL)
|
addOriginalRequestUrl(exchange, exchange.getRequest().getURI());
String rawPath = exchange.getRequest().getURI().getRawPath();
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/")).skip(1L).collect(Collectors.joining("/"));
ServerHttpRequest newRequest = exchange.getRequest().mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
//2.将现在的request,添加当前身份
ServerHttpRequest mutableReq = exchange.getRequest().mutate().header("Authorization-UserName", "").header(X_GATEWAY_BASE_PATH,basePath).build();
ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
return chain.filter(mutableExchange);
}
@Override
public int getOrder() {
return 0;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\filter\GlobalAccessTokenFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RpcCleanUpService {
@Value("${sql.ttl.rpc.enabled}")
private boolean ttlTaskExecutionEnabled;
private final TenantService tenantService;
private final PartitionService partitionService;
private final TbTenantProfileCache tenantProfileCache;
private final RpcDao rpcDao;
@Scheduled(initialDelayString = "#{T(org.apache.commons.lang3.RandomUtils).nextLong(0, ${sql.ttl.rpc.checking_interval})}", fixedDelayString = "${sql.ttl.rpc.checking_interval}")
public void cleanUp() {
if (ttlTaskExecutionEnabled) {
PageLink tenantsBatchRequest = new PageLink(10_000, 0);
PageData<TenantId> tenantsIds;
do {
tenantsIds = tenantService.findTenantsIds(tenantsBatchRequest);
for (TenantId tenantId : tenantsIds.getData()) {
if (!partitionService.resolve(ServiceType.TB_CORE, tenantId, tenantId).isMyPartition()) {
continue;
}
Optional<DefaultTenantProfileConfiguration> tenantProfileConfiguration = tenantProfileCache.get(tenantId).getProfileConfiguration();
|
if (tenantProfileConfiguration.isEmpty() || tenantProfileConfiguration.get().getRpcTtlDays() == 0) {
continue;
}
long ttl = TimeUnit.DAYS.toMillis(tenantProfileConfiguration.get().getRpcTtlDays());
long expirationTime = System.currentTimeMillis() - ttl;
int totalRemoved = rpcDao.deleteOutdatedRpcByTenantId(tenantId, expirationTime);
if (totalRemoved > 0) {
log.info("Removed {} outdated rpc(s) for tenant {} older than {}", totalRemoved, tenantId, new Date(expirationTime));
}
}
tenantsBatchRequest = tenantsBatchRequest.nextPageLink();
} while (tenantsIds.hasNext());
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ttl\rpc\RpcCleanUpService.java
| 2
|
请完成以下Java代码
|
public class TransactionContextInterceptor extends AbstractCommandInterceptor {
protected TransactionContextFactory transactionContextFactory;
public TransactionContextInterceptor() {}
public TransactionContextInterceptor(TransactionContextFactory transactionContextFactory) {
this.transactionContextFactory = transactionContextFactory;
}
public <T> T execute(CommandConfig config, Command<T> command) {
CommandContext commandContext = Context.getCommandContext();
// Storing it in a variable, to reference later (it can change during command execution)
boolean isReused = commandContext.isReused();
try {
if (transactionContextFactory != null && !isReused) {
TransactionContext transactionContext = transactionContextFactory.openTransactionContext(
commandContext
);
Context.setTransactionContext(transactionContext);
commandContext.addCloseListener(new TransactionCommandContextCloseListener(transactionContext));
}
|
return next.execute(config, command);
} finally {
if (transactionContextFactory != null && !isReused) {
Context.removeTransactionContext();
}
}
}
public TransactionContextFactory getTransactionContextFactory() {
return transactionContextFactory;
}
public void setTransactionContextFactory(TransactionContextFactory transactionContextFactory) {
this.transactionContextFactory = transactionContextFactory;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\TransactionContextInterceptor.java
| 1
|
请完成以下Java代码
|
public Object getValue()
{
return getText();
} // getValue
/**
* Return Display Value
* @return displayed String value
*/
@Override
public String getDisplay()
{
return getText();
} // getDisplay
/**
* key Pressed
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
* @param e
*/
@Override
public void keyPressed(KeyEvent e)
{
} // keyPressed
/**
* key Released
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
* @param e
*/
@Override
public void keyReleased(KeyEvent e)
{
} // keyReleased
/**
* key Typed
|
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
* @param e
*/
@Override
public void keyTyped(KeyEvent e)
{
} // keyTyped
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
@Override
public boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)
{
// NOTE: overridden just to make it public
return super.processKeyBinding(ks, e, condition, pressed);
}
} // CTextField
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextField.java
| 1
|
请完成以下Java代码
|
public String getAuthorizationHttpHeader()
{
return AUTHORIZATION_TYPE_BEARER + getAccessToken();
}
private String getAccessToken()
{
return getAuthResponse().getAccessToken();
}
private synchronized JsonAuthResponse getAuthResponse()
{
JsonAuthResponse authResponse = _authResponse;
if (authResponse == null
|| authResponse.isExpired())
{
authResponse = _authResponse = authenticate(config);
}
return authResponse;
}
public void authenticate()
{
getAuthResponse();
}
private static JsonAuthResponse authenticate(@NonNull final SecurPharmConfig config)
{
try
{
final SSLContext sslContext = createSSLContext(config);
final HttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.build();
final RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(client));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add(AUTH_PARAM_GRANT_TYPE, AUTH_PARAM_GRANT_TYPE_VALUE);
params.add(AUTH_PARAM_CLIENT_ID, AUTH_PARAM_CLIENT_ID_VALUE);
final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
final ResponseEntity<JsonAuthResponse> response = restTemplate.postForEntity(config.getAuthBaseUrl() + AUTH_RELATIVE_PATH, request, JsonAuthResponse.class);
final JsonAuthResponse authResponse = response.getBody();
if (response.getStatusCode() == HttpStatus.OK)
{
return authResponse;
}
else
{
throw new AdempiereException(MSG_AUTHORIZATION_FAILED)
.appendParametersToMessage()
.setParameter("HTTPStatus", response.getStatusCode())
.setParameter("error", authResponse.getError())
.setParameter("errorDescription", authResponse.getErrorDescription());
}
}
catch (final AdempiereException ex)
{
throw ex;
}
catch (final Exception ex)
|
{
final Throwable cause = AdempiereException.extractCause(ex);
throw new AdempiereException(MSG_AUTHORIZATION_FAILED, cause);
}
}
private static SSLContext createSSLContext(final SecurPharmConfig config)
{
try
{
final char[] password = config.getKeystorePassword().toCharArray();
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
final File key = new File(config.getCertificatePath());
try (final InputStream in = new FileInputStream(key))
{
keyStore.load(in, password);
}
return SSLContextBuilder.create()
.loadKeyMaterial(keyStore, password)
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
}
catch (final Exception ex)
{
throw new AdempiereException("Failed creating SSL context " + ex.getLocalizedMessage(), ex)
.appendParametersToMessage()
.setParameter("config", config);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\client\SecurPharmClientAuthenticator.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_M_Warehouse getM_Warehouse_Dest() throws RuntimeException
{
return (org.compiere.model.I_M_Warehouse)MTable.get(getCtx(), org.compiere.model.I_M_Warehouse.Table_Name)
.getPO(getM_Warehouse_Dest_ID(), get_TrxName()); }
/** Set Ziel-Lager.
@param M_Warehouse_Dest_ID Ziel-Lager */
public void setM_Warehouse_Dest_ID (int M_Warehouse_Dest_ID)
{
if (M_Warehouse_Dest_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_Dest_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_Dest_ID, Integer.valueOf(M_Warehouse_Dest_ID));
}
/** Get Ziel-Lager.
@return Ziel-Lager */
public int getM_Warehouse_Dest_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Dest_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Set Verarbeitet.
*
* @param Processed
* Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
public void setProcessed(boolean Processed)
{
|
set_Value(COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/**
* Get Verarbeitet.
*
* @return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTree.java
| 1
|
请完成以下Java代码
|
public Integer getId() {
return id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getJobTitle() {
return jobTitle;
}
|
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public LocalDate getEmpDoj() {
return empDoj;
}
public void setEmpDoj(LocalDate empDoj) {
this.empDoj = empDoj;
}
public Date getCreatedDate() {
return createdDate;
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-mysql\src\main\java\com\baeldung\boot\jpa\Employee.java
| 1
|
请完成以下Java代码
|
protected Object coerceToType(Object value, Class<?> type) {
if (type == String.class) {
return coerceToString(value);
}
if (type == Long.class || type == long.class) {
return coerceToLong(value);
}
if (type == Double.class || type == double.class) {
return coerceToDouble(value);
}
if (type == Boolean.class || type == boolean.class) {
return coerceToBoolean(value);
}
if (type == Integer.class || type == int.class) {
return coerceToInteger(value);
}
if (type == Float.class || type == float.class) {
return coerceToFloat(value);
}
if (type == Short.class || type == short.class) {
return coerceToShort(value);
}
if (type == Byte.class || type == byte.class) {
return coerceToByte(value);
}
if (type == Character.class || type == char.class) {
return coerceToCharacter(value);
}
if (type == BigDecimal.class) {
return coerceToBigDecimal(value);
}
if (type == BigInteger.class) {
return coerceToBigInteger(value);
}
if (type.getSuperclass() == Enum.class) {
|
return coerceToEnum(value, (Class<? extends Enum>) type);
}
if (value == null || value.getClass() == type || type.isInstance(value)) {
return value;
}
if (value instanceof String) {
return coerceStringToType((String) value, type);
}
throw new ELException(LocalMessages.get("error.coerce.type", value, value.getClass(), type));
}
@Override
public boolean equals(Object obj) {
return obj != null && obj.getClass().equals(getClass());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@SuppressWarnings("unchecked")
public <T> T convert(Object value, Class<T> type) throws ELException {
return (T) coerceToType(value, type);
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\misc\TypeConverterImpl.java
| 1
|
请完成以下Java代码
|
private DatabasePurgeReport purgeDatabase(CommandContext commandContext) {
DbEntityManager dbEntityManager = commandContext.getDbEntityManager();
// For MySQL we have to disable foreign key check,
// to delete the table data as bulk operation (execution, incident etc.)
// The flag will be reset by the DBEntityManager after flush.
dbEntityManager.setIgnoreForeignKeysForNextFlush(true);
List<String> tablesNames = dbEntityManager.getTableNamesPresentInDatabase();
String databaseTablePrefix = commandContext.getProcessEngineConfiguration().getDatabaseTablePrefix().trim();
// for each table
DatabasePurgeReport databasePurgeReport = new DatabasePurgeReport();
for (String tableName : tablesNames) {
String tableNameWithoutPrefix = tableName.replace(databaseTablePrefix, EMPTY_STRING);
if (!TABLENAMES_EXCLUDED_FROM_DB_CLEAN_CHECK.contains(tableNameWithoutPrefix)) {
// Check if table contains data
Map<String, String> param = new HashMap<String, String>();
param.put(TABLE_NAME, tableName);
Long count = (Long) dbEntityManager.selectOne(SELECT_TABLE_COUNT, param);
if (count > 0) {
// allow License Key in byte array table
if (tableNameWithoutPrefix.equals("ACT_GE_BYTEARRAY") && commandContext.getResourceManager().findLicenseKeyResource() != null) {
if (count != 1) {
DbBulkOperation purgeByteArrayPreserveLicenseKeyBulkOp = new DbBulkOperation(DbOperationType.DELETE_BULK, ByteArrayEntity.class,
"purgeTablePreserveLicenseKey", LicenseCmd.LICENSE_KEY_BYTE_ARRAY_ID);
databasePurgeReport.addPurgeInformation(tableName, count - 1);
dbEntityManager.getDbOperationManager().addOperation(purgeByteArrayPreserveLicenseKeyBulkOp);
}
databasePurgeReport.setDbContainsLicenseKey(true);
continue;
}
databasePurgeReport.addPurgeInformation(tableName, count);
// Get corresponding entity classes for the table, which contains data
List<Class<? extends DbEntity>> entities = commandContext.getTableDataManager().getEntities(tableName);
if (entities.isEmpty()) {
|
throw new ProcessEngineException("No mapped implementation of "
+ DbEntity.class.getName()
+ " was found for: "
+ tableName);
}
// Delete the table data as bulk operation with the first entity
Class<? extends DbEntity> entity = entities.get(0);
DbBulkOperation deleteBulkOp = new DbBulkOperation(DbOperationType.DELETE_BULK, entity, DELETE_TABLE_DATA, param);
dbEntityManager.getDbOperationManager().addOperation(deleteBulkOp);
}
}
}
return databasePurgeReport;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\PurgeDatabaseAndCacheCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BankAccount
{
@NonNull BankAccountId id;
@NonNull OrgId orgId;
@NonNull CurrencyId currencyId;
@Nullable BankId bankId;
@Nullable String accountName;
@Nullable String accountNo;
@Nullable String routingNo;
@Nullable String accountStreet;
@Nullable String accountZip;
@Nullable String accountCity;
@Nullable String accountCountry;
@Nullable String esrRenderedAccountNo;
@Nullable String IBAN;
@Nullable String QR_IBAN;
@Nullable String SEPA_CreditorIdentifier;
boolean isESRAccount;
public boolean isAccountNoMatching(@NonNull final String accountNo)
{
final String QR_IBAN = StringUtils.trimBlankToNull(getQR_IBAN());
final String IBAN = StringUtils.trimBlankToNull(getIBAN());
final String SEPA_CreditorIdentifier = StringUtils.trimBlankToNull(getSEPA_CreditorIdentifier());
final int indexOfSlash = StringUtils.findIndexOf(accountNo, "/");
final String accountNoWithoutTrailingSlash = indexOfSlash >= 0
? accountNo.substring(0, indexOfSlash)
: accountNo;
|
final String postAcctNoCleaned = StringUtils.cleanWhitespace(accountNoWithoutTrailingSlash);
return postAcctNoCleaned.equals(QR_IBAN)
|| postAcctNoCleaned.equals(IBAN)
|| postAcctNoCleaned.equals(SEPA_CreditorIdentifier);
}
public boolean isAddressComplete()
{
return Check.isNotBlank(accountStreet) &&
Check.isNotBlank(accountZip) &&
Check.isNotBlank(accountCity);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\banking\BankAccount.java
| 2
|
请完成以下Java代码
|
public CurrencyConversionTypeId getConversionTypeId(@NonNull final ConversionTypeMethod method)
{
return getConversionTypesMap().getByMethod(method).getId();
}
@Override
public @NonNull ConversionTypeMethod getConversionTypeMethodById(@NonNull final CurrencyConversionTypeId id)
{
return getConversionTypesMap().getById(id).getMethod();
}
/**
* @return query which is finding the best matching {@link I_C_Conversion_Rate} for given parameters.
*/
protected final IQueryBuilder<I_C_Conversion_Rate> retrieveRateQuery(
@NonNull final CurrencyConversionContext conversionCtx,
@NonNull final CurrencyId currencyFromId,
@NonNull final CurrencyId currencyToId)
{
final CurrencyConversionTypeId conversionTypeId = conversionCtx.getConversionTypeId();
final Instant conversionDate = conversionCtx.getConversionDate();
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_C_Conversion_Rate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Conversion_Rate.COLUMN_C_Currency_ID, currencyFromId)
.addEqualsFilter(I_C_Conversion_Rate.COLUMN_C_Currency_ID_To, currencyToId)
.addEqualsFilter(I_C_Conversion_Rate.COLUMN_C_ConversionType_ID, conversionTypeId)
.addCompareFilter(I_C_Conversion_Rate.COLUMN_ValidFrom, Operator.LESS_OR_EQUAL, conversionDate)
.addCompareFilter(I_C_Conversion_Rate.COLUMN_ValidTo, Operator.GREATER_OR_EQUAL, conversionDate)
.addInArrayOrAllFilter(I_C_Conversion_Rate.COLUMN_AD_Client_ID, ClientId.SYSTEM, conversionCtx.getClientId())
.addInArrayOrAllFilter(I_C_Conversion_Rate.COLUMN_AD_Org_ID, OrgId.ANY, conversionCtx.getOrgId())
//
.orderBy()
.addColumn(I_C_Conversion_Rate.COLUMN_AD_Client_ID, Direction.Descending, Nulls.Last)
.addColumn(I_C_Conversion_Rate.COLUMN_AD_Org_ID, Direction.Descending, Nulls.Last)
.addColumn(I_C_Conversion_Rate.COLUMN_ValidFrom, Direction.Descending, Nulls.Last)
.endOrderBy()
//
.setLimit(QueryLimit.ONE) // first only
;
|
}
@Override
public @Nullable BigDecimal retrieveRateOrNull(
final CurrencyConversionContext conversionCtx,
final CurrencyId currencyFromId,
final CurrencyId currencyToId)
{
final List<Map<String, Object>> recordsList = retrieveRateQuery(conversionCtx, currencyFromId, currencyToId)
.setLimit(QueryLimit.ONE)
.create()
.listColumns(I_C_Conversion_Rate.COLUMNNAME_MultiplyRate);
if (recordsList.isEmpty())
{
return null;
}
final Map<String, Object> record = recordsList.get(0);
return (BigDecimal)record.get(I_C_Conversion_Rate.COLUMNNAME_MultiplyRate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrencyDAO.java
| 1
|
请完成以下Java代码
|
public void setVariableEvents(Set<String> variableEvents) {
this.variableEvents = variableEvents;
}
public String getConditionAsString() {
return conditionAsString;
}
public void setConditionAsString(String conditionAsString) {
this.conditionAsString = conditionAsString;
}
public boolean shouldEvaluateForVariableEvent(VariableEvent event) {
return
((variableName == null || event.getVariableInstance().getName().equals(variableName))
&&
((variableEvents == null || variableEvents.isEmpty()) || variableEvents.contains(event.getEventName())));
}
|
public boolean evaluate(DelegateExecution execution) {
if (condition != null) {
return condition.evaluate(execution, execution);
}
throw new IllegalStateException("Conditional event must have a condition!");
}
public boolean tryEvaluate(DelegateExecution execution) {
if (condition != null) {
return condition.tryEvaluate(execution, execution);
}
throw new IllegalStateException("Conditional event must have a condition!");
}
public boolean tryEvaluate(VariableEvent variableEvent, DelegateExecution execution) {
return (variableEvent == null || shouldEvaluateForVariableEvent(variableEvent)) && tryEvaluate(execution);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\ConditionalEventDefinition.java
| 1
|
请完成以下Java代码
|
public void setLevel(int level) {
this.level = level;
}
private int getMillisForCurrentLevel() {
return 2 * (this.level - 1) + 1;
}
public Board findNextMove(Board board, int playerNo) {
long start = System.currentTimeMillis();
long end = start + 60 * getMillisForCurrentLevel();
opponent = 3 - playerNo;
Tree tree = new Tree();
Node rootNode = tree.getRoot();
rootNode.getState().setBoard(board);
rootNode.getState().setPlayerNo(opponent);
while (System.currentTimeMillis() < end) {
// Phase 1 - Selection
Node promisingNode = selectPromisingNode(rootNode);
// Phase 2 - Expansion
if (promisingNode.getState().getBoard().checkStatus() == Board.IN_PROGRESS)
expandNode(promisingNode);
// Phase 3 - Simulation
Node nodeToExplore = promisingNode;
if (promisingNode.getChildArray().size() > 0) {
nodeToExplore = promisingNode.getRandomChildNode();
}
int playoutResult = simulateRandomPlayout(nodeToExplore);
// Phase 4 - Update
backPropogation(nodeToExplore, playoutResult);
}
Node winnerNode = rootNode.getChildWithMaxScore();
tree.setRoot(winnerNode);
return winnerNode.getState().getBoard();
}
private Node selectPromisingNode(Node rootNode) {
Node node = rootNode;
while (node.getChildArray().size() != 0) {
node = UCT.findBestNodeWithUCT(node);
}
return node;
}
private void expandNode(Node node) {
List<State> possibleStates = node.getState().getAllPossibleStates();
possibleStates.forEach(state -> {
Node newNode = new Node(state);
newNode.setParent(node);
newNode.getState().setPlayerNo(node.getState().getOpponent());
node.getChildArray().add(newNode);
});
|
}
private void backPropogation(Node nodeToExplore, int playerNo) {
Node tempNode = nodeToExplore;
while (tempNode != null) {
tempNode.getState().incrementVisit();
if (tempNode.getState().getPlayerNo() == playerNo)
tempNode.getState().addScore(WIN_SCORE);
tempNode = tempNode.getParent();
}
}
private int simulateRandomPlayout(Node node) {
Node tempNode = new Node(node);
State tempState = tempNode.getState();
int boardStatus = tempState.getBoard().checkStatus();
if (boardStatus == opponent) {
tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
return boardStatus;
}
while (boardStatus == Board.IN_PROGRESS) {
tempState.togglePlayer();
tempState.randomPlay();
boardStatus = tempState.getBoard().checkStatus();
}
return boardStatus;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\montecarlo\MonteCarloTreeSearch.java
| 1
|
请完成以下Java代码
|
public Timestamp getDayStart(final Timestamp date)
{
final Instant dayStart = getDayStart(date.toInstant());
return Timestamp.from(dayStart);
}
public Instant getDayStart(@NonNull final Instant date)
{
return getDayStart(date.atZone(SystemTime.zoneId())).toInstant();
}
public LocalDateTime getDayStart(final LocalDateTime date)
{
return getDayStart(date.atZone(SystemTime.zoneId())).toLocalDateTime();
}
public ZonedDateTime getDayStart(final ZonedDateTime date)
{
if (isTimeSlot())
{
return date.toLocalDate().atTime(getTimeSlotStart()).atZone(date.getZone());
}
else
{
return date.toLocalDate().atStartOfDay().atZone(date.getZone());
}
}
|
@Deprecated
public Timestamp getDayEnd(final Timestamp date)
{
final LocalDateTime dayEnd = getDayEnd(TimeUtil.asLocalDateTime(date));
return TimeUtil.asTimestamp(dayEnd);
}
public Instant getDayEnd(final Instant date)
{
return getDayEnd(date.atZone(SystemTime.zoneId())).toInstant();
}
public LocalDateTime getDayEnd(final LocalDateTime date)
{
return getDayEnd(date.atZone(SystemTime.zoneId())).toLocalDateTime();
}
public ZonedDateTime getDayEnd(final ZonedDateTime date)
{
if (isTimeSlot())
{
return date.toLocalDate().atTime(timeSlotEnd).atZone(date.getZone());
}
else
{
return date.toLocalDate().atTime(LocalTime.MAX).atZone(date.getZone());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ResourceType.java
| 1
|
请完成以下Java代码
|
public java.lang.String getIsAllowIssuingAnyHU()
{
return get_ValueAsString(COLUMNNAME_IsAllowIssuingAnyHU);
}
/**
* IsScanResourceRequired AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int ISSCANRESOURCEREQUIRED_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISSCANRESOURCEREQUIRED_Yes = "Y";
/** No = N */
public static final String ISSCANRESOURCEREQUIRED_No = "N";
@Override
public void setIsScanResourceRequired (final @Nullable java.lang.String IsScanResourceRequired)
{
set_Value (COLUMNNAME_IsScanResourceRequired, IsScanResourceRequired);
}
@Override
public java.lang.String getIsScanResourceRequired()
{
return get_ValueAsString(COLUMNNAME_IsScanResourceRequired);
|
}
@Override
public void setMobileUI_UserProfile_MFG_ID (final int MobileUI_UserProfile_MFG_ID)
{
if (MobileUI_UserProfile_MFG_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_MFG_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_MFG_ID, MobileUI_UserProfile_MFG_ID);
}
@Override
public int getMobileUI_UserProfile_MFG_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_MFG_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_MFG.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
if (deploymentId == null) {
throw new ActivitiIllegalArgumentException("Deployment id is null");
}
DeploymentEntity deployment = commandContext.getDeploymentEntityManager().findById(deploymentId);
if (deployment == null) {
throw new ActivitiObjectNotFoundException(
"No deployment found for id = '" + deploymentId + "'",
Deployment.class
);
}
executeInternal(commandContext, deployment);
return null;
}
protected void executeInternal(CommandContext commandContext, DeploymentEntity deployment) {
// Update category
deployment.setKey(key);
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext
|
.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, deployment));
}
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetDeploymentKeyCmd.java
| 1
|
请完成以下Java代码
|
private static Stream<DDOrderMoveScheduleCreateRequest> toScheduleToMoveRequest(
@NonNull final DDOrderMovePlanLine planLine,
@NonNull final DDOrderId ddOrderId)
{
final DDOrderLineId ddOrderLineId = planLine.getDdOrderLineId();
return planLine.getSteps()
.stream()
.filter(planStep -> planStep.getScheduleId() == null)
.map(planStep -> toScheduleToMoveRequest(planStep, ddOrderId, ddOrderLineId));
}
private static DDOrderMoveScheduleCreateRequest toScheduleToMoveRequest(
@NonNull final DDOrderMovePlanStep planStep,
@NonNull final DDOrderId ddOrderId,
@NonNull final DDOrderLineId ddOrderLineId)
{
return DDOrderMoveScheduleCreateRequest.builder()
.ddOrderId(ddOrderId)
.ddOrderLineId(ddOrderLineId)
.productId(planStep.getProductId())
//
// Pick From
.pickFromLocatorId(planStep.getPickFromLocatorId())
.pickFromHUId(planStep.getPickFromHUId())
.qtyToPick(planStep.getQtyToPick())
.isPickWholeHU(planStep.isPickWholeHU())
//
// Drop To
.dropToLocatorId(planStep.getDropToLocatorId())
//
.build();
}
public DDOrderMoveSchedule pickFromHU(@NonNull final DDOrderPickFromRequest request)
{
return DDOrderPickFromCommand.builder()
.ddOrderLowLevelDAO(ddOrderLowLevelDAO)
.ddOrderMoveScheduleRepository(ddOrderMoveScheduleRepository)
.handlingUnitsBL(handlingUnitsBL)
.request(request)
.build()
.execute();
}
public ImmutableList<DDOrderMoveSchedule> dropTo(@NonNull final DDOrderDropToRequest request)
{
return DDOrderDropToCommand.builder()
.ppOrderSourceHUService(ppOrderSourceHUService)
.ddOrderLowLevelDAO(ddOrderLowLevelDAO)
.ddOrderMoveScheduleRepository(ddOrderMoveScheduleRepository)
.request(request)
.build()
.execute();
}
public void unpick(@NonNull final DDOrderMoveScheduleId scheduleId, @Nullable final HUQRCode unpickToTargetQRCode)
{
DDOrderUnpickCommand.builder()
.ddOrderMoveScheduleRepository(ddOrderMoveScheduleRepository)
|
.huqrCodesService(huqrCodesService)
.scheduleId(scheduleId)
.unpickToTargetQRCode(unpickToTargetQRCode)
.build()
.execute();
}
public Set<DDOrderId> retrieveDDOrderIdsInTransit(@NonNull final LocatorId inTransitLocatorId)
{
return ddOrderMoveScheduleRepository.retrieveDDOrderIdsInTransit(inTransitLocatorId);
}
public boolean hasInTransitSchedules(@NonNull final LocatorId inTransitLocatorId)
{
return ddOrderMoveScheduleRepository.queryInTransitSchedules(inTransitLocatorId).anyMatch();
}
public void printMaterialInTransitReport(
@NonNull final LocatorId inTransitLocatorId,
@NonNull String adLanguage)
{
MaterialInTransitReportCommand.builder()
.adLanguage(adLanguage)
.inTransitLocatorId(inTransitLocatorId)
.build()
.execute();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleService.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.