instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public TemporalUnit getTemporalUnitByUomId(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return UOMUtil.toTemporalUnit(uom);
}
@Override
public I_C_UOM getByTemporalUnit(@NonNull final TemporalUnit temporalUnit)
{
final UomId uomId = getUomIdByTemporalUnit(temporalUnit);
return getById(uomId);
}
@Override
public UomId getUomIdByTemporalUnit(@NonNull final TemporalUnit temporalUnit)
{
final X12DE355 x12de355 = X12DE355.ofTemporalUnit(temporalUnit);
try
{
return getUomIdByX12DE355(x12de355);
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("temporalUnit", temporalUnit)
.setParameter("x12de355", x12de355)
.setParameter("Suggestion", "Create an UOM for that X12DE355 code or activate it if already exists.")
.appendParametersToMessage();
}
}
@Override
public UOMPrecision getStandardPrecision(final UomId uomId)
{
if (uomId == null)
{
// NOTE: if there is no UOM specified, we assume UOM is Each => precision=0
return UOMPrecision.ZERO;
}
final I_C_UOM uom = getById(uomId);
return UOMPrecision.ofInt(uom.getStdPrecision());
}
@Override
public boolean isUOMForTUs(@NonNull final UomId uomId)
{ | final I_C_UOM uom = getById(uomId);
return isUOMForTUs(uom);
}
public static boolean isUOMForTUs(@NonNull final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofCode(uom.getX12DE355());
return X12DE355.COLI.equals(x12de355) || X12DE355.TU.equals(x12de355);
}
@Override
public @NonNull UOMType getUOMTypeById(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return UOMType.ofNullableCodeOrOther(uom.getUOMType());
}
@Override
public @NonNull Optional<I_C_UOM> getBySymbol(@NonNull final String uomSymbol)
{
return Optional.ofNullable(queryBL.createQueryBuilder(I_C_UOM.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_UOM.COLUMNNAME_UOMSymbol, uomSymbol)
.create()
.firstOnlyOrNull(I_C_UOM.class));
}
@Override
public ITranslatableString getUOMSymbolById(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return InterfaceWrapperHelper.getModelTranslationMap(uom).getColumnTrl(I_C_UOM.COLUMNNAME_UOMSymbol, uom.getUOMSymbol());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\impl\UOMDAO.java | 1 |
请完成以下Java代码 | protected AutoDeploymentStrategy<ProcessEngine> getAutoDeploymentStrategy(final String mode) {
AutoDeploymentStrategy<ProcessEngine> result = new DefaultAutoDeploymentStrategy();
for (AutoDeploymentStrategy<ProcessEngine> strategy : deploymentStrategies) {
if (strategy.handlesMode(mode)) {
result = strategy;
break;
}
}
return result;
}
public Collection<AutoDeploymentStrategy<ProcessEngine>> getDeploymentStrategies() {
return deploymentStrategies;
}
public void setDeploymentStrategies(Collection<AutoDeploymentStrategy<ProcessEngine>> deploymentStrategies) {
this.deploymentStrategies = deploymentStrategies;
}
@Override
public void start() {
synchronized (lifeCycleMonitor) {
if (!isRunning()) {
enginesBuild.forEach(name -> {
ProcessEngine processEngine = ProcessEngines.getProcessEngine(name);
processEngine.startExecutors();
autoDeployResources(processEngine);
});
running = true;
}
} | }
@Override
public void stop() {
synchronized (lifeCycleMonitor) {
running = false;
}
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return SpringEngineConfiguration.super.getPhase() + SpringEngineConfiguration.PHASE_DELTA * 2;
}
} | repos\flowable-engine-main\modules\flowable-spring\src\main\java\org\flowable\spring\SpringProcessEngineConfiguration.java | 1 |
请完成以下Java代码 | protected TbelScriptExecutionTask doInvokeFunction(UUID scriptId, Object[] args) {
ExecutionContext executionContext = new ExecutionContext(this.parserConfig, maxMemoryLimitMb * 1024 * 1024);
return new TbelScriptExecutionTask(executionContext, executor.submit(() -> {
String scriptHash = scriptIdToHash.get(scriptId);
if (scriptHash == null) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.OTHER, null, new RuntimeException("Script not found!"));
}
TbelScript script = scriptMap.get(scriptHash);
Serializable compiledScript = compiledScriptsCache.get(scriptHash, k -> compileScript(script.getScriptBody()));
try {
return MVEL.executeTbExpression(compiledScript, executionContext, script.createVars(args));
} catch (ScriptMemoryOverflowException e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.OTHER, script.getScriptBody(), new RuntimeException("Script memory overflow!"));
} catch (Exception e) {
throw new TbScriptException(scriptId, TbScriptException.ErrorCode.RUNTIME, script.getScriptBody(), e);
}
}));
}
@Override
protected void doRelease(UUID scriptId) {
String scriptHash = scriptIdToHash.remove(scriptId);
if (scriptHash != null) {
lock.lock();
try {
if (!scriptIdToHash.containsValue(scriptHash)) {
scriptMap.remove(scriptHash);
compiledScriptsCache.invalidate(scriptHash);
}
} finally {
lock.unlock(); | }
}
}
private static Serializable compileScript(String scriptBody) throws CompileException {
return MVEL.compileExpression(scriptBody, new ParserContext());
}
@SuppressWarnings("UnstableApiUsage")
protected String hash(String scriptBody, String[] argNames) {
Hasher hasher = Hashing.murmur3_128().newHasher();
hasher.putUnencodedChars(scriptBody);
for (String argName : argNames) {
hasher.putString(argName, StandardCharsets.UTF_8);
}
return hasher.hash().toString();
}
@Override
protected long getMaxEvalRequestsTimeout() {
return maxInvokeRequestsTimeout * 2;
}
@Override
protected StatsType getStatsType() {
return StatsType.TBEL_INVOKE;
}
} | repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\tbel\DefaultTbelInvokeService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
private Long id;
private String username;
private String email;
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, mappedBy = "author", fetch = FetchType.EAGER)
protected List<Post> posts;
public User() {
}
public Long getId() {
return this.id;
}
public String getUsername() {
return this.username;
}
public String getEmail() {
return this.email;
}
public List<Post> getPosts() {
return this.posts;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
} | public void setPosts(List<Post> posts) {
this.posts = posts;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", posts=" + this.getPosts()
+ ")";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\eager\list\moderatedomain\User.java | 2 |
请完成以下Java代码 | public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getEngineVersion() {
return engineVersion;
}
public String getAuthorizationUserId() {
return authorizationUserId;
}
public String getProcDefId() {
return procDefId;
}
public String getEventSubscriptionName() { | return eventSubscriptionName;
}
public String getEventSubscriptionType() {
return eventSubscriptionType;
}
public boolean isIncludeAuthorization() {
return authorizationUserId != null || (authorizationGroups != null && !authorizationGroups.isEmpty());
}
public List<List<String>> getSafeAuthorizationGroups() {
return safeAuthorizationGroups;
}
public void setSafeAuthorizationGroups(List<List<String>> safeAuthorizationGroups) {
this.safeAuthorizationGroups = safeAuthorizationGroups;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | public void addOrderPackages(@NonNull final List<JpaOrderPackage> orderPackages)
{
orderPackages.forEach(orderPackage -> orderPackage.setOrder(this));
this.orderPackages.addAll(orderPackages);
}
public void visitItems(@NonNull final Consumer<JpaOrderPackageItem> consumer)
{
orderPackages.stream()
.flatMap(orderPackage -> orderPackage.getItems().stream())
.forEach(consumer);
}
public void markSyncSent()
{
syncSent = true; | syncSentTS = Instant.now();
}
public void markSyncAck()
{
mfSyncAck = true;
syncAckTS = Instant.now();
}
public void markSyncError(final String errorMsg)
{
mfSyncError = true;
mfSyncErrorMsg = errorMsg;
syncErrorTS = Instant.now();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\order\jpa\JpaOrder.java | 1 |
请完成以下Java代码 | public PublicKeyCredentialCreationOptionsBuilder authenticatorSelection(
AuthenticatorSelectionCriteria authenticatorSelection) {
this.authenticatorSelection = authenticatorSelection;
return this;
}
/**
* Sets the {@link #getAttestation()} property.
* @param attestation the attestation
* @return the PublicKeyCredentialCreationOptionsBuilder
*/
public PublicKeyCredentialCreationOptionsBuilder attestation(AttestationConveyancePreference attestation) {
this.attestation = attestation;
return this;
}
/**
* Sets the {@link #getExtensions()} property.
* @param extensions the extensions
* @return the PublicKeyCredentialCreationOptionsBuilder
*/
public PublicKeyCredentialCreationOptionsBuilder extensions(AuthenticationExtensionsClientInputs extensions) {
this.extensions = extensions;
return this;
}
/**
* Allows customizing the builder using the {@link Consumer} that is passed in.
* @param customizer the {@link Consumer} that can be used to customize the | * {@link PublicKeyCredentialCreationOptionsBuilder}
* @return the PublicKeyCredentialCreationOptionsBuilder
*/
public PublicKeyCredentialCreationOptionsBuilder customize(
Consumer<PublicKeyCredentialCreationOptionsBuilder> customizer) {
customizer.accept(this);
return this;
}
/**
* Builds a new {@link PublicKeyCredentialCreationOptions}
* @return the new {@link PublicKeyCredentialCreationOptions}
*/
public PublicKeyCredentialCreationOptions build() {
return new PublicKeyCredentialCreationOptions(this.rp, this.user, this.challenge, this.pubKeyCredParams,
this.timeout, this.excludeCredentials, this.authenticatorSelection, this.attestation,
this.extensions);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialCreationOptions.java | 1 |
请完成以下Java代码 | public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setVersionNo (final @Nullable java.lang.String VersionNo)
{
set_Value (COLUMNNAME_VersionNo, VersionNo);
}
@Override
public java.lang.String getVersionNo()
{
return get_ValueAsString(COLUMNNAME_VersionNo);
}
@Override
public void setVolume (final @Nullable BigDecimal Volume)
{
set_Value (COLUMNNAME_Volume, Volume);
}
@Override
public BigDecimal getVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWarehouse_temperature (final @Nullable java.lang.String Warehouse_temperature)
{
set_Value (COLUMNNAME_Warehouse_temperature, Warehouse_temperature);
}
@Override
public java.lang.String getWarehouse_temperature()
{
return get_ValueAsString(COLUMNNAME_Warehouse_temperature);
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeight_UOM_ID (final int Weight_UOM_ID)
{
if (Weight_UOM_ID < 1)
set_Value (COLUMNNAME_Weight_UOM_ID, null);
else
set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID);
}
@Override
public int getWeight_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID);
}
@Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product.java | 1 |
请完成以下Java代码 | public Flux<ReactiveSessionInformation> getAllSessions(Object principal) {
return Flux.fromIterable(this.sessionIdsByPrincipal.getOrDefault(principal, Collections.emptySet()))
.mapNotNull(this.sessionById::get);
}
@Override
public Mono<Void> saveSessionInformation(ReactiveSessionInformation information) {
this.sessionById.put(information.getSessionId(), information);
this.sessionIdsByPrincipal.computeIfAbsent(information.getPrincipal(), (key) -> new CopyOnWriteArraySet<>())
.add(information.getSessionId());
return Mono.empty();
}
@Override
public Mono<ReactiveSessionInformation> getSessionInformation(String sessionId) {
return Mono.justOrEmpty(this.sessionById.get(sessionId));
}
@Override
public Mono<ReactiveSessionInformation> removeSessionInformation(String sessionId) {
return getSessionInformation(sessionId).doOnNext((sessionInformation) -> {
this.sessionById.remove(sessionId);
Set<String> sessionsUsedByPrincipal = this.sessionIdsByPrincipal.get(sessionInformation.getPrincipal());
if (sessionsUsedByPrincipal != null) {
sessionsUsedByPrincipal.remove(sessionId);
if (sessionsUsedByPrincipal.isEmpty()) {
this.sessionIdsByPrincipal.remove(sessionInformation.getPrincipal()); | }
}
});
}
@Override
public Mono<ReactiveSessionInformation> updateLastAccessTime(String sessionId) {
ReactiveSessionInformation session = this.sessionById.get(sessionId);
if (session != null) {
return session.refreshLastRequest().thenReturn(session);
}
return Mono.empty();
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\session\InMemoryReactiveSessionRegistry.java | 1 |
请完成以下Java代码 | private static void processProperty(Object target, PropertyDescriptor property, Properties arguments)
{
Method writeMethod = property.getWriteMethod();
if (writeMethod != null)
{
Argument argument = writeMethod.getAnnotation(Argument.class);
if (argument != null)
{
String name = Args.getName(argument, property);
String alias = Args.getAlias(argument);
Object value = arguments.get(name);
if (value == null && alias != null)
{
value = arguments.get(alias);
}
if (value != null)
{
Class type = property.getPropertyType(); | if (type == Boolean.TYPE || type == Boolean.class)
{
value = true;
}
Args.setProperty(type, property, target, value, argument.delimiter());
}
else
{
if (argument.required())
{
throw new IllegalArgumentException("You must set argument " + name);
}
}
}
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\cli\PropertiesArgs.java | 1 |
请完成以下Java代码 | public void setC_BPartner_Department_ID (final int C_BPartner_Department_ID)
{
if (C_BPartner_Department_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Department_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Department_ID, C_BPartner_Department_ID);
}
@Override
public int getC_BPartner_Department_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Department_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description); | }
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Department.java | 1 |
请完成以下Java代码 | public class X_C_BPartner_QuickInput_Attributes2 extends org.compiere.model.PO implements I_C_BPartner_QuickInput_Attributes2, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -187167824L;
/** Standard Constructor */
public X_C_BPartner_QuickInput_Attributes2 (final Properties ctx, final int C_BPartner_QuickInput_Attributes2_ID, @Nullable final String trxName)
{
super (ctx, C_BPartner_QuickInput_Attributes2_ID, trxName);
}
/** Load Constructor */
public X_C_BPartner_QuickInput_Attributes2 (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* Attributes2 AD_Reference_ID=541333
* Reference name: Attributes2
*/
public static final int ATTRIBUTES2_AD_Reference_ID=541333;
/** Test(A2T1) = A2T1 */
public static final String ATTRIBUTES2_TestA2T1 = "A2T1";
/** Test(A2T2) = A2T2 */
public static final String ATTRIBUTES2_TestA2T2 = "A2T2";
@Override
public void setAttributes2 (final java.lang.String Attributes2)
{
set_Value (COLUMNNAME_Attributes2, Attributes2);
}
@Override
public java.lang.String getAttributes2()
{
return get_ValueAsString(COLUMNNAME_Attributes2);
}
@Override
public void setC_BPartner_QuickInput_Attributes2_ID (final int C_BPartner_QuickInput_Attributes2_ID)
{
if (C_BPartner_QuickInput_Attributes2_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID, C_BPartner_QuickInput_Attributes2_ID);
}
@Override
public int getC_BPartner_QuickInput_Attributes2_ID() | {
return get_ValueAsInt(COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID);
}
@Override
public org.compiere.model.I_C_BPartner_QuickInput getC_BPartner_QuickInput()
{
return get_ValueAsPO(COLUMNNAME_C_BPartner_QuickInput_ID, org.compiere.model.I_C_BPartner_QuickInput.class);
}
@Override
public void setC_BPartner_QuickInput(final org.compiere.model.I_C_BPartner_QuickInput C_BPartner_QuickInput)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_QuickInput_ID, org.compiere.model.I_C_BPartner_QuickInput.class, C_BPartner_QuickInput);
}
@Override
public void setC_BPartner_QuickInput_ID (final int C_BPartner_QuickInput_ID)
{
if (C_BPartner_QuickInput_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_ID, C_BPartner_QuickInput_ID);
}
@Override
public int getC_BPartner_QuickInput_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_QuickInput_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput_Attributes2.java | 1 |
请完成以下Java代码 | public void setRouteId(String routeId) {
this.routeId = routeId;
}
public @Nullable String getRouteId() {
return routeId;
}
public @Nullable URI getFallbackUri() {
return fallbackUri;
}
public Config setFallbackUri(URI fallbackUri) {
this.fallbackUri = fallbackUri;
return this;
}
public Config setFallbackUri(String fallbackUri) {
return setFallbackUri(URI.create(fallbackUri));
}
public @Nullable String getName() {
return name;
}
public Config setName(String name) {
this.name = name;
return this;
}
public @Nullable String getId() {
if (!StringUtils.hasText(name) && StringUtils.hasText(routeId)) {
return routeId;
}
return name;
}
public Set<String> getStatusCodes() {
return statusCodes;
} | public Config setStatusCodes(Set<String> statusCodes) {
this.statusCodes = statusCodes;
return this;
}
public Config addStatusCode(String statusCode) {
this.statusCodes.add(statusCode);
return this;
}
public boolean isResumeWithoutError() {
return resumeWithoutError;
}
public void setResumeWithoutError(boolean resumeWithoutError) {
this.resumeWithoutError = resumeWithoutError;
}
}
public class CircuitBreakerStatusCodeException extends HttpStatusCodeException {
public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) {
super(statusCode);
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SpringCloudCircuitBreakerFilterFactory.java | 1 |
请完成以下Java代码 | public Mono<ServerResponse> handleWithErrorResumeAndDynamicFallback(ServerRequest request) {
return sayHello(request)
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s))
.onErrorResume(e -> (Mono.just("Hi, I looked around for your name but found: " + e.getMessage()))
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s)));
}
public Mono<ServerResponse> handleWithErrorResumeAndFallbackMethod(ServerRequest request) {
return sayHello(request)
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s))
.onErrorResume(e -> sayHelloFallback()
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s)));
}
public Mono<ServerResponse> handleWithErrorResumeAndCustomException(ServerRequest request) {
return ServerResponse.ok()
.body(sayHello(request)
.onErrorResume(e -> Mono.error(new NameRequiredException(
HttpStatus.BAD_REQUEST,
"please provide a name", e))), String.class);
}
public Mono<ServerResponse> handleWithGlobalErrorHandler(ServerRequest request) {
return ServerResponse.ok() | .body(sayHello(request), String.class);
}
private Mono<String> sayHello(ServerRequest request) {
try {
return Mono.just("Hello, " + request.queryParam("name").get());
} catch (Exception e) {
return Mono.error(e);
}
}
private Mono<String> sayHelloFallback() {
return Mono.just("Hello, Stranger");
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\errorhandling\Handler.java | 1 |
请完成以下Java代码 | public String getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTp(String value) {
this.tp = value;
}
/**
* Gets the value of the ref property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getRef() {
return ref;
}
/**
* Sets the value of the ref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRef(String value) {
this.ref = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ProprietaryReference1.java | 1 |
请完成以下Java代码 | public class XtraDRGType {
@XmlAttribute(name = "cost_fraction")
@XmlJavaTypeAdapter(Adapter1 .class)
protected BigDecimal costFraction;
/**
* Gets the value of the costFraction property.
*
* @return
* possible object is
* {@link String }
*
*/
public BigDecimal getCostFraction() {
if (costFraction == null) {
return new Adapter1().unmarshal("1.0"); | } else {
return costFraction;
}
}
/**
* Sets the value of the costFraction property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCostFraction(BigDecimal value) {
this.costFraction = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\XtraDRGType.java | 1 |
请完成以下Java代码 | public long skip(long n) throws IOException {
return in().skip(n);
}
@Override
public int available() throws IOException {
return in().available();
}
@Override
public boolean markSupported() {
try {
return in().markSupported();
}
catch (IOException ex) {
return false;
}
}
@Override
public synchronized void mark(int readLimit) {
try {
in().mark(readLimit);
}
catch (IOException ex) {
// Ignore
}
}
@Override
public synchronized void reset() throws IOException {
in().reset();
}
private InputStream in() throws IOException {
InputStream in = this.in;
if (in == null) {
synchronized (this) {
in = this.in;
if (in == null) {
in = getDelegateInputStream(); | this.in = in;
}
}
}
return in;
}
@Override
public void close() throws IOException {
InputStream in = this.in;
if (in != null) {
synchronized (this) {
in = this.in;
if (in != null) {
in.close();
}
}
}
}
protected abstract InputStream getDelegateInputStream() throws IOException;
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\LazyDelegatingInputStream.java | 1 |
请完成以下Java代码 | public int getC_BPartner_From_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_From_ID);
}
@Override
public void setC_BPartner_To_ID (final int C_BPartner_To_ID)
{
if (C_BPartner_To_ID < 1)
set_Value (COLUMNNAME_C_BPartner_To_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_To_ID, C_BPartner_To_ID);
}
@Override
public int getC_BPartner_To_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_To_ID);
}
@Override
public void setDate_OrgChange (final java.sql.Timestamp Date_OrgChange)
{
set_Value (COLUMNNAME_Date_OrgChange, Date_OrgChange); | }
@Override
public java.sql.Timestamp getDate_OrgChange()
{
return get_ValueAsTimestamp(COLUMNNAME_Date_OrgChange);
}
@Override
public void setIsCloseInvoiceCandidate (final boolean IsCloseInvoiceCandidate)
{
set_Value (COLUMNNAME_IsCloseInvoiceCandidate, IsCloseInvoiceCandidate);
}
@Override
public boolean isCloseInvoiceCandidate()
{
return get_ValueAsBoolean(COLUMNNAME_IsCloseInvoiceCandidate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgChange_History.java | 1 |
请完成以下Java代码 | public class CmmnParser extends AbstractModelParser {
private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
public CmmnParser() {
this.schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
addSchema(CMMN10_NS, createSchema(CMMN_10_SCHEMA_LOCATION, CmmnParser.class.getClassLoader()));
addSchema(CMMN11_NS, createSchema(CMMN_11_SCHEMA_LOCATION, CmmnParser.class.getClassLoader()));
}
@Override
protected void configureFactory(DocumentBuilderFactory dbf) {
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
ClassLoader classLoader = CmmnParser.class.getClassLoader();
dbf.setAttribute(JAXP_SCHEMA_SOURCE, new String[] {
ReflectUtil.getResource(CMMN_10_SCHEMA_LOCATION, classLoader).toString(),
ReflectUtil.getResource(CMMN_11_SCHEMA_LOCATION, classLoader).toString() }
);
super.configureFactory(dbf);
}
@Override
protected CmmnModelInstanceImpl createModelInstance(DomDocument document) { | return new CmmnModelInstanceImpl((ModelImpl) Cmmn.INSTANCE.getCmmnModel(), Cmmn.INSTANCE.getCmmnModelBuilder(), document);
}
@Override
public CmmnModelInstanceImpl parseModelFromStream(InputStream inputStream) {
try {
return (CmmnModelInstanceImpl) super.parseModelFromStream(inputStream);
}
catch (ModelParseException e) {
throw new CmmnModelException("Unable to parse model", e);
}
}
@Override
public CmmnModelInstanceImpl getEmptyModel() {
return (CmmnModelInstanceImpl) super.getEmptyModel();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\CmmnParser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setC_POS_Order(final de.metas.pos.repository.model.I_C_POS_Order C_POS_Order)
{
set_ValueFromPO(COLUMNNAME_C_POS_Order_ID, de.metas.pos.repository.model.I_C_POS_Order.class, C_POS_Order);
}
@Override
public void setC_POS_Order_ID (final int C_POS_Order_ID)
{
if (C_POS_Order_ID < 1)
set_Value (COLUMNNAME_C_POS_Order_ID, null);
else
set_Value (COLUMNNAME_C_POS_Order_ID, C_POS_Order_ID);
}
@Override
public int getC_POS_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_Order_ID);
}
@Override
public de.metas.pos.repository.model.I_C_POS_Payment getC_POS_Payment()
{
return get_ValueAsPO(COLUMNNAME_C_POS_Payment_ID, de.metas.pos.repository.model.I_C_POS_Payment.class);
}
@Override
public void setC_POS_Payment(final de.metas.pos.repository.model.I_C_POS_Payment C_POS_Payment)
{
set_ValueFromPO(COLUMNNAME_C_POS_Payment_ID, de.metas.pos.repository.model.I_C_POS_Payment.class, C_POS_Payment);
}
@Override
public void setC_POS_Payment_ID (final int C_POS_Payment_ID)
{
if (C_POS_Payment_ID < 1)
set_Value (COLUMNNAME_C_POS_Payment_ID, null);
else
set_Value (COLUMNNAME_C_POS_Payment_ID, C_POS_Payment_ID);
}
@Override
public int getC_POS_Payment_ID()
{ | return get_ValueAsInt(COLUMNNAME_C_POS_Payment_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* Type AD_Reference_ID=541892
* Reference name: C_POS_JournalLine_Type
*/
public static final int TYPE_AD_Reference_ID=541892;
/** CashPayment = CASH_PAY */
public static final String TYPE_CashPayment = "CASH_PAY";
/** CardPayment = CARD_PAY */
public static final String TYPE_CardPayment = "CARD_PAY";
/** CashInOut = CASH_INOUT */
public static final String TYPE_CashInOut = "CASH_INOUT";
/** CashClosingDifference = CASH_DIFF */
public static final String TYPE_CashClosingDifference = "CASH_DIFF";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_JournalLine.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Result<SysComment> queryById(@RequestParam(name = "id", required = true) String id) {
SysComment sysComment = sysCommentService.getById(id);
if (sysComment == null) {
return Result.error("未找到对应数据");
}
return Result.OK(sysComment);
}
/**
* 导出excel
*
* @param request
* @param sysComment
*/
//@RequiresPermissions("org.jeecg.modules.demo:sys_comment:exportXls")
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysComment sysComment) { | return super.exportXls(request, sysComment, SysComment.class, "系统评论回复表");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
//@RequiresPermissions("sys_comment:importExcel")
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysComment.class);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysCommentController.java | 2 |
请完成以下Java代码 | public void setIsPrimary (boolean IsPrimary)
{
set_Value (COLUMNNAME_IsPrimary, Boolean.valueOf(IsPrimary));
}
/** Get Primary.
@return Indicates if this is the primary budget
*/
public boolean isPrimary ()
{
Object oo = get_Value(COLUMNNAME_IsPrimary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name); | }
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Budget.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RedisCodeService {
private final static String SMS_CODE_PREFIX = "SMS_CODE:";
private final static Integer TIME_OUT = 300;
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 保存验证码到 redis
*
* @param smsCode 短信验证码
* @param request ServletWebRequest
*/
public void save(SmsCode smsCode, ServletWebRequest request, String mobile) throws Exception {
redisTemplate.opsForValue().set(key(request, mobile), smsCode.getCode(), TIME_OUT, TimeUnit.SECONDS);
}
/**
* 获取验证码
*
* @param request ServletWebRequest
* @return 验证码
*/
public String get(ServletWebRequest request, String mobile) throws Exception {
return redisTemplate.opsForValue().get(key(request, mobile));
} | /**
* 移除验证码
*
* @param request ServletWebRequest
*/
public void remove(ServletWebRequest request, String mobile) throws Exception {
redisTemplate.delete(key(request, mobile));
}
private String key(ServletWebRequest request, String mobile) throws Exception {
String deviceId = request.getHeader("deviceId");
if (StringUtils.isBlank(deviceId)) {
throw new Exception("请在请求头中设置deviceId");
}
return SMS_CODE_PREFIX + deviceId + ":" + mobile;
}
} | repos\SpringAll-master\64.Spring-Security-OAuth2-Customize\src\main\java\cc\mrbird\security\service\RedisCodeService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable ShowSummaryOutput getShowSummaryOutput() {
return this.showSummaryOutput;
}
public void setShowSummaryOutput(@Nullable ShowSummaryOutput showSummaryOutput) {
this.showSummaryOutput = showSummaryOutput;
}
public @Nullable UiService getUiService() {
return this.uiService;
}
public void setUiService(@Nullable UiService uiService) {
this.uiService = uiService;
}
public @Nullable Boolean getAnalyticsEnabled() {
return this.analyticsEnabled;
}
public void setAnalyticsEnabled(@Nullable Boolean analyticsEnabled) {
this.analyticsEnabled = analyticsEnabled;
}
public @Nullable String getLicenseKey() {
return this.licenseKey;
}
public void setLicenseKey(@Nullable String licenseKey) {
this.licenseKey = licenseKey;
}
/**
* Enumeration of types of summary to show. Values are the same as those on
* {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum
* is not used directly.
*/
public enum ShowSummary {
/**
* Do not show a summary.
*/
OFF,
/**
* Show a summary.
*/
SUMMARY,
/**
* Show a verbose summary.
*/
VERBOSE
}
/**
* Enumeration of destinations to which the summary should be output. Values are the
* same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards | * compatibility, the Liquibase enum is not used directly.
*/
public enum ShowSummaryOutput {
/**
* Log the summary.
*/
LOG,
/**
* Output the summary to the console.
*/
CONSOLE,
/**
* Log the summary and output it to the console.
*/
ALL
}
/**
* Enumeration of types of UIService. Values are the same as those on
* {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is
* not used directly.
*/
public enum UiService {
/**
* Console-based UIService.
*/
CONSOLE,
/**
* Logging-based UIService.
*/
LOGGER
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BusinessRuleService
{
@NonNull private final BusinessRuleRepository ruleRepository;
@NonNull private final BusinessRuleEventRepository eventRepository;
@NonNull private final RecordWarningRepository recordWarningRepository;
@NonNull private final BusinessRuleLogger logger;
@NonNull private final BusinessRuleRecordMatcher recordMatcher;
public BusinessRulesCollection getRules()
{
return ruleRepository.getAll();
}
public void addRulesChangedListener(final BusinessRulesChangedListener listener)
{
ruleRepository.addCacheResetListener(listener);
}
public void fireTriggersForSourceModel(@NonNull final Object sourceModel, @NonNull final TriggerTiming timing)
{
BusinessRuleFireTriggersCommand.builder()
.eventRepository(eventRepository)
.logger(logger)
.recordMatcher(recordMatcher)
//
.rules(ruleRepository.getAll()) | .sourceModel(sourceModel)
.timing(timing)
//
.build().execute();
}
public void processEvents(@NonNull final QueryLimit limit)
{
BusinessRuleEventProcessorCommand.builder()
.ruleRepository(ruleRepository)
.eventRepository(eventRepository)
.recordWarningRepository(recordWarningRepository)
.logger(logger)
.recordMatcher(recordMatcher)
//
.limit(limit)
//
.build().execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\BusinessRuleService.java | 2 |
请完成以下Java代码 | public class DeleteCommentCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
protected String processInstanceId;
protected String commentId;
public DeleteCommentCmd(String taskId, String processInstanceId, String commentId) {
this.taskId = taskId;
this.processInstanceId = processInstanceId;
this.commentId = commentId;
}
public Void execute(CommandContext commandContext) {
CommentEntityManager commentManager = commandContext.getCommentEntityManager();
if (commentId != null) {
// Delete for an individual comment
Comment comment = commentManager.findComment(commentId);
if (comment == null) {
throw new ActivitiObjectNotFoundException(
"Comment with id '" + commentId + "' doesn't exists.",
Comment.class
);
} | commentManager.delete((CommentEntity) comment);
} else {
// Delete all comments on a task of process
ArrayList<Comment> comments = new ArrayList<Comment>();
if (processInstanceId != null) {
comments.addAll(commentManager.findCommentsByProcessInstanceId(processInstanceId));
}
if (taskId != null) {
comments.addAll(commentManager.findCommentsByTaskId(taskId));
}
for (Comment comment : comments) {
commentManager.delete((CommentEntity) comment);
}
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteCommentCmd.java | 1 |
请完成以下Spring Boot application配置 | spring.output.ansi.enabled=DETECT
server.port = 8000
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.datasource.url=jdbc:sqlite:info.db
spring.datasource.driver-class-name = org.sqlite.JDBC
spring.jpa.database-platform=com.boylegu.springboot_vue.config.SQLiteDialect
spring.jpa.show-sql= true
com.boylegu.paginatio.max-per-page=7
# Log Config
log4j.rootCategory=INFO, stdout, file, errorfile
log4j.category.com.didispace=DEBUG, didifile
log4j.logger.error=errorfile
# Log Console input
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=logs/all.log
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n
# error log input
log4j.appender.errorfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.errorfile.file=logs/error.log
log4j.appender.errorfile.DatePattern='.'yyyy-MM-dd
log4j.appender.er | rorfile.Threshold = ERROR
log4j.appender.errorfile.layout=org.apache.log4j.PatternLayout
log4j.appender.errorfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n
log4j.appender.didifile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.didifile.file=logs/gubaoer.log
log4j.appender.didifile.DatePattern='.'yyyy-MM-dd
log4j.appender.didifile.layout=org.apache.log4j.PatternLayout
log4j.appender.didifile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L ---- %m%n | repos\SpringBoot-vue-master\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public static AggregationParams none() {
return new AggregationParams(Aggregation.NONE, null, null, 0L);
}
public static AggregationParams milliseconds(Aggregation aggregationType, long aggregationIntervalMs) {
return new AggregationParams(aggregationType, IntervalType.MILLISECONDS, null, aggregationIntervalMs);
}
public static AggregationParams calendar(Aggregation aggregationType, IntervalType intervalType, String tzIdStr) {
return calendar(aggregationType, intervalType, getZoneId(tzIdStr));
}
public static AggregationParams calendar(Aggregation aggregationType, IntervalType intervalType, ZoneId tzId) {
return new AggregationParams(aggregationType, intervalType, tzId, 0L);
}
public static AggregationParams of(Aggregation aggregation, IntervalType intervalType, ZoneId tzId, long interval) {
return new AggregationParams(aggregation, intervalType, tzId, interval);
}
public long getInterval() {
if (intervalType == null) {
return 0L;
} else {
switch (intervalType) {
case WEEK:
case WEEK_ISO:
return TimeUnit.DAYS.toMillis(7);
case MONTH:
return TimeUnit.DAYS.toMillis(30);
case QUARTER:
return TimeUnit.DAYS.toMillis(90);
default:
return interval; | }
}
}
private static ZoneId getZoneId(String tzIdStr) {
if (StringUtils.isEmpty(tzIdStr)) {
return ZoneId.systemDefault();
}
try {
return ZoneId.of(tzIdStr, TZ_LINKS);
} catch (DateTimeException e) {
log.warn("[{}] Failed to convert the time zone. Fallback to default.", tzIdStr);
return ZoneId.systemDefault();
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\AggregationParams.java | 1 |
请完成以下Java代码 | public List<String> getStartEventFormTypes() {
return startEventFormTypes;
}
public void setStartEventFormTypes(List<String> startEventFormTypes) {
this.startEventFormTypes = startEventFormTypes;
}
@JsonIgnore
public Object getEventSupport() {
return eventSupport;
}
public void setEventSupport(Object eventSupport) {
this.eventSupport = eventSupport; | }
public String getExporter() {
return exporter;
}
public void setExporter(String exporter) {
this.exporter = exporter;
}
public String getExporterVersion() {
return exporterVersion;
}
public void setExporterVersion(String exporterVersion) {
this.exporterVersion = exporterVersion;
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\BpmnModel.java | 1 |
请完成以下Java代码 | public class LdapPluginLogger extends BaseLogger {
public static final String PROJECT_CODE = "LDAP";
public static final LdapPluginLogger INSTANCE = BaseLogger.createLogger(
LdapPluginLogger.class, PROJECT_CODE, "org.camunda.bpm.identity.impl.ldap", "00");
public void pluginActivated(String pluginClassName, String engineName) {
logInfo("001", "PLUGIN {} activated on process engine {}", pluginClassName, engineName);
}
public void acceptingUntrustedCertificates() {
logWarn("002", "Enabling accept of untrusted certificates. Use at own risk.");
}
public void exceptionWhenClosingLdapContext(Exception e) {
logDebug("003", "exception while closing LDAP DIR CTX", e); | }
public <E extends DbEntity> void invalidLdapEntityReturned(E entity, SearchResult searchResult) {
String entityType = entity instanceof UserEntity ? "user" : "group";
logError("004", "LDAP {} query returned a {} with id null. This {} will be ignored. "
+ "This indicates a misconfiguration of the LDAP plugin or a problem with the LDAP service."
+ " Enable DEBUG/FINE logging for details.", entityType, entityType, entityType);
// log sensitive data only on FINE
logDebug("004", "Invalid {}: {} based on search result {}", entityType, entity, searchResult);
}
public void queryResult(String summary) {
// log sensitive data only on FINE
logDebug("005", summary);
}
} | repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\util\LdapPluginLogger.java | 1 |
请完成以下Java代码 | public String getApplication() {
return application;
}
////// static helpers //////////////////////////////
public static Authorization granted(Authentication authentication) {
return new Authorization(authentication, true);
}
public static Authorization denied(Authentication authentication) {
return new Authorization(authentication, false);
}
public static Authorization grantedUnlessNull(Authentication authentication) {
return authentication != null ? granted(authentication) : denied(authentication);
} | private static String join(String delimiter, Collection<?> collection) {
StringBuilder builder = new StringBuilder();
for (Object o: collection) {
if (builder.length() > 0) {
builder.append(delimiter);
}
builder.append(o);
}
return builder.toString();
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\Authorization.java | 1 |
请完成以下Java代码 | private CreateSEPAExportFromPaySelectionCommand.InvoicePaySelectionLinesAggregationKey extractPaySelectionLinesKey(@NonNull final I_C_PaySelectionLine paySelectionLine)
{
final BankAccountId bankAccountId = BankAccountId.ofRepoId(paySelectionLine.getC_BP_BankAccount_ID());
final BankAccount bpBankAccount = bankAccountDAO.getById(bankAccountId);
return InvoicePaySelectionLinesAggregationKey.builder()
.orgId(OrgId.ofRepoId(paySelectionLine.getAD_Org_ID()))
.partnerId(BPartnerId.ofRepoId(paySelectionLine.getC_BPartner_ID()))
.bankAccountId(bankAccountId)
.currencyId(bpBankAccount.getCurrencyId())
.iban(extractIBAN(bpBankAccount))
.swiftCode(extractSwiftCode(bpBankAccount))
.build();
}
private @Nullable String extractSwiftCode(@NonNull final BankAccount bpBankAccount)
{
return Optional.ofNullable(bpBankAccount.getBankId())
.map(bankRepo::getById)
.map(bank -> toNullOrRemoveSpaces(bank.getSwiftCode())) | .orElse(null);
}
@Value
@Builder
private static class InvoicePaySelectionLinesAggregationKey
{
@NonNull OrgId orgId;
@NonNull BPartnerId partnerId;
@NonNull BankAccountId bankAccountId;
@NonNull CurrencyId currencyId;
@NonNull String iban;
@Nullable String swiftCode;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\CreateSEPAExportFromPaySelectionCommand.java | 1 |
请完成以下Java代码 | public void setNationalCode (String NationalCode)
{
set_Value (COLUMNNAME_NationalCode, NationalCode);
}
/** Get National Code.
@return National Code */
public String getNationalCode ()
{
return (String)get_Value(COLUMNNAME_NationalCode);
}
/** Set Social Security Code.
@param SSCode Social Security Code */
public void setSSCode (String SSCode)
{
set_Value (COLUMNNAME_SSCode, SSCode);
}
/** Get Social Security Code.
@return Social Security Code */ | public String getSSCode ()
{
return (String)get_Value(COLUMNNAME_SSCode);
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Employee.java | 1 |
请完成以下Java代码 | private void startTask(final int AD_Task_ID)
{
// Get Command
MTask task = null;
if (AD_Task_ID > 0)
{
task = new MTask(Env.getCtx(), AD_Task_ID, ITrx.TRXNAME_None);
}
if (task.getAD_Task_ID() != AD_Task_ID)
{
task = null;
}
if (task == null)
{
return;
} | m_menu.getWindowManager().add(new ATask(m_name, task));
// ATask.start(m_name, task);
} // startTask
/**
* Start Form
*
* @param AD_Form_ID form
*/
private void startForm(final int AD_Form_ID)
{
m_menu.startForm(AD_Form_ID);
} // startForm
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AMenuStartItem.java | 1 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dueDate == null) ? 0 : dueDate.hashCode());
result = prime * result + ((endDate == null) ? 0 : endDate.hashCode());
result = prime * result + ((exceptionMessage == null) ? 0 : exceptionMessage.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + maxIterations;
result = prime * result + ((repeat == null) ? 0 : repeat.hashCode());
result = prime * result + retries;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TimerPayload other = (TimerPayload) obj;
if (dueDate == null) {
if (other.dueDate != null) return false;
} else if (!dueDate.equals(other.dueDate)) return false; | if (endDate == null) {
if (other.endDate != null) return false;
} else if (!endDate.equals(other.endDate)) return false;
if (exceptionMessage == null) {
if (other.exceptionMessage != null) return false;
} else if (!exceptionMessage.equals(other.exceptionMessage)) return false;
if (id == null) {
if (other.id != null) return false;
} else if (!id.equals(other.id)) return false;
if (maxIterations != other.maxIterations) return false;
if (repeat == null) {
if (other.repeat != null) return false;
} else if (!repeat.equals(other.repeat)) return false;
if (retries != other.retries) return false;
return true;
}
} | repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\TimerPayload.java | 1 |
请完成以下Java代码 | public Builder putProperty(final String name, final ITableRecordReference value)
{
properties.put(name, value);
return this;
}
public Builder putProperty(final String name, final List<?> value)
{
properties.put(name, value);
return this;
}
/**
* @see #putProperty(String, ITableRecordReference)
* @see Event#PROPERTY_Record
*/
public Builder setRecord(final ITableRecordReference record)
{
putProperty(Event.PROPERTY_Record, record);
return this;
}
public Builder putPropertyFromObject(final String name, @Nullable final Object value)
{
if (value == null)
{
properties.remove(name);
return this;
}
else if (value instanceof Integer)
{
return putProperty(name, value);
}
else if (value instanceof Long)
{
return putProperty(name, value);
}
else if (value instanceof Double)
{
final double doubleValue = (Double)value;
final int intValue = (int)doubleValue;
if (doubleValue == intValue)
{
return putProperty(name, intValue);
}
else
{
return putProperty(name, BigDecimal.valueOf(doubleValue));
}
}
else if (value instanceof String)
{
return putProperty(name, (String)value);
}
else if (value instanceof Date) | {
return putProperty(name, (Date)value);
}
else if (value instanceof Boolean)
{
return putProperty(name, value);
}
else if (value instanceof ITableRecordReference)
{
return putProperty(name, (ITableRecordReference)value);
}
else if (value instanceof BigDecimal)
{
return putProperty(name, (BigDecimal)value);
}
else if (value instanceof List)
{
return putProperty(name, (List<?>)value);
}
else
{
throw new AdempiereException("Unknown value type " + name + " = " + value + " (type " + value.getClass() + ")");
}
}
public Builder setSuggestedWindowId(final int suggestedWindowId)
{
putProperty(PROPERTY_SuggestedWindowId, suggestedWindowId);
return this;
}
public Builder wasLogged()
{
this.loggingStatus = LoggingStatus.WAS_LOGGED;
return this;
}
public Builder shallBeLogged()
{
this.loggingStatus = LoggingStatus.SHALL_BE_LOGGED;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\Event.java | 1 |
请完成以下Java代码 | private HttpHeaders createHttpHeaders(@NonNull final JsonShipperConfig config)
{
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
httpHeaders.set("Authorization", getAuthorizationHeader(config));
return httpHeaders;
}
private String getAuthorizationHeader(@NonNull final JsonShipperConfig config)
{
final String auth = config.getUsername() + ":" + config.getPassword();
return "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
}
private <T_Req> void logRequestAsJson(@NonNull final T_Req requestBody)
{
if (!logger.isTraceEnabled())
{
return;
}
try
{
final String jsonRequest = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(requestBody);
logger.trace("---- Sending nShift JSON Request ----\n{}", jsonRequest);
} | catch (final JsonProcessingException ex)
{
logger.trace("Could not serialize nShift request to JSON for logging", ex);
}
}
private <T_Req> RuntimeException createApiException(
@NonNull final T_Req request, @NonNull final HttpStatus statusCode, @NonNull final String responseBody)
{
final StringBuilder sb = new StringBuilder();
sb.append("nShift API call failed with status code ").append(statusCode).append("\n");
sb.append("Additional information's:\n");
sb.append("Response body: ").append(responseBody).append("\n");
try
{
final String requestAsJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
sb.append("nShiftRequest: ").append(requestAsJson).append("\n");
return new RuntimeException(sb.toString());
}
catch (final JsonProcessingException ex)
{
logger.warn("Failed to serialize nShift request for exception details", ex);
return new RuntimeException(sb.toString(), ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftRestClient.java | 1 |
请完成以下Java代码 | public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (Iterator<String> names = beanFactory.getBeanNamesIterator(); names.hasNext(); ) {
Object proxy = this.getTargetObject(beanFactory.getBean(names.next()));
final Subscriber annotation = AnnotationUtils.getAnnotation(proxy.getClass(), Subscriber.class);
if (annotation == null)
continue;
this.logger.info("{}: processing bean of type {} during initialization", this.getClass().getSimpleName(),
proxy.getClass().getName());
final String annotationValue = annotation.value();
try {
final Expression expression = this.expressionParser.parseExpression(annotationValue);
final Object value = expression.getValue();
if (!(value instanceof EventBus)) {
this.logger.error("{}: expression {} did not evaluate to an instance of EventBus for bean of type {}",
this.getClass().getSimpleName(), annotationValue, proxy.getClass().getSimpleName());
return;
}
final EventBus eventBus = (EventBus)value;
eventBus.register(proxy);
} catch (ExpressionException ex) {
this.logger.error("{}: unable to parse/evaluate expression {} for bean of type {}", this.getClass().getSimpleName(), | annotationValue, proxy.getClass().getName());
}
}
}
private Object getTargetObject(Object proxy) throws BeansException {
if (AopUtils.isJdkDynamicProxy(proxy)) {
try {
return ((Advised)proxy).getTargetSource().getTarget();
} catch (Exception e) {
throw new FatalBeanException("Error getting target of JDK proxy", e);
}
}
return proxy;
}
} | repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\beanpostprocessor\GuavaEventBusBeanFactoryPostProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
private Logger log = LoggerFactory.getLogger(this.getClass());
@GetMapping("/{id:\\d+}")
public User get(@PathVariable Long id) {
log.info("获取用户id为 " + id + "的信息");
return new User(id, "mrbird", "123456");
}
@GetMapping
public List<User> get() {
List<User> list = new ArrayList<>();
list.add(new User(1L, "mrbird", "123456"));
list.add(new User(2L, "scott", "123456"));
log.info("获取用户信息 " + list);
return list; | }
@PostMapping
public void add(@RequestBody User user) {
log.info("新增用户成功 " + user);
}
@PutMapping
public void update(@RequestBody User user) {
log.info("更新用户成功 " + user);
}
@DeleteMapping("/{id:\\d+}")
public void delete(@PathVariable Long id) {
log.info("删除用户成功 " + id);
}
} | repos\SpringAll-master\29.Spring-Cloud-Ribbon-LoadBalance\Eureka-Client\src\main\java\com\example\demo\controller\UserController.java | 2 |
请完成以下Java代码 | public class ByteArrayEntityManagerImpl
extends AbstractEntityManager<ByteArrayEntity, ByteArrayDataManager>
implements ByteArrayEntityManager {
protected Supplier<FlowableEventDispatcher> eventDispatcherSupplier;
public ByteArrayEntityManagerImpl(ByteArrayDataManager byteArrayDataManager, String engineType, Supplier<FlowableEventDispatcher> eventDispatcherSupplier) {
super(byteArrayDataManager, engineType);
this.eventDispatcherSupplier = eventDispatcherSupplier;
}
@Override
public List<ByteArrayEntity> findAll() {
return dataManager.findAll();
}
@Override | public void deleteByteArrayById(String byteArrayEntityId) {
dataManager.deleteByteArrayNoRevisionCheck(byteArrayEntityId);
}
@Override
public void bulkDeleteByteArraysById(List<String> byteArrayEntityIds) {
dataManager.bulkDeleteByteArraysNoRevisionCheck(byteArrayEntityIds);
}
@Override
protected FlowableEventDispatcher getEventDispatcher() {
return eventDispatcherSupplier.get();
}
public void setEventDispatcherSupplier(Supplier<FlowableEventDispatcher> eventDispatcherSupplier) {
this.eventDispatcherSupplier = eventDispatcherSupplier;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\ByteArrayEntityManagerImpl.java | 1 |
请完成以下Java代码 | public Builder preferredUsername(String preferredUsername) {
return claim(StandardClaimNames.PREFERRED_USERNAME, preferredUsername);
}
/**
* Use this profile in the resulting {@link OidcUserInfo}
* @param profile The profile to use
* @return the {@link Builder} for further configurations
*/
public Builder profile(String profile) {
return claim(StandardClaimNames.PROFILE, profile);
}
/**
* Use this subject in the resulting {@link OidcUserInfo}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
return this.claim(StandardClaimNames.SUB, subject);
}
/**
* Use this updated-at {@link Instant} in the resulting {@link OidcUserInfo}
* @param updatedAt The updated-at {@link Instant} to use
* @return the {@link Builder} for further configurations
*/
public Builder updatedAt(String updatedAt) {
return this.claim(StandardClaimNames.UPDATED_AT, updatedAt);
}
/**
* Use this website in the resulting {@link OidcUserInfo}
* @param website The website to use
* @return the {@link Builder} for further configurations | */
public Builder website(String website) {
return this.claim(StandardClaimNames.WEBSITE, website);
}
/**
* Use this zoneinfo in the resulting {@link OidcUserInfo}
* @param zoneinfo The zoneinfo to use
* @return the {@link Builder} for further configurations
*/
public Builder zoneinfo(String zoneinfo) {
return this.claim(StandardClaimNames.ZONEINFO, zoneinfo);
}
/**
* Build the {@link OidcUserInfo}
* @return The constructed {@link OidcUserInfo}
*/
public OidcUserInfo build() {
return new OidcUserInfo(this.claims);
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\OidcUserInfo.java | 1 |
请完成以下Java代码 | public AdditionalRequiredFactorsBuilder<T> requireFactors(
Consumer<AllRequiredFactorsAuthorizationManager.Builder<T>> factors) {
factors.accept(this.factors);
return this;
}
public AdditionalRequiredFactorsBuilder<T> requireFactor(Consumer<RequiredFactor.Builder> factor) {
this.factors.requireFactor(factor);
return this;
}
/**
* Builds a {@link DefaultAuthorizationManagerFactory} that has the
* {@link DefaultAuthorizationManagerFactory#setAdditionalAuthorization(AuthorizationManager)}
* set. | * @return the {@link DefaultAuthorizationManagerFactory}.
*/
public DefaultAuthorizationManagerFactory<T> build() {
DefaultAuthorizationManagerFactory<T> result = new DefaultAuthorizationManagerFactory<>();
AllRequiredFactorsAuthorizationManager<T> additionalChecks = this.factors.build();
result.setAdditionalAuthorization(additionalChecks);
return result;
}
private AdditionalRequiredFactorsBuilder() {
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationManagerFactories.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int predict(MultipartFile file, boolean isNeedRevert) throws Exception {
log.info("start predict, file [{}], isNeedRevert [{}]", file.getOriginalFilename(), isNeedRevert);
// 先存文件
String rawFileName = ImageFileUtil.save(imageFilePath, file);
if (null==rawFileName) {
return RLT_INVALID;
}
// 反色处理后的文件名
String revertFileName = null;
// 调整大小后的文件名
String resizeFileName;
// 是否需要反色处理
if (isNeedRevert) {
// 把原始文件做反色处理,返回结果是反色处理后的新文件
revertFileName = ImageFileUtil.colorRevert(imageFilePath, rawFileName); | // 把反色处理后调整为28*28大小的文件
resizeFileName = ImageFileUtil.resize(imageFilePath, revertFileName);
} else {
// 直接把原始文件调整为28*28大小的文件
resizeFileName = ImageFileUtil.resize(imageFilePath, rawFileName);
}
// 现在已经得到了结果反色和调整大小处理过后的文件,
// 那么原始文件和反色处理过的文件就可以删除了
ImageFileUtil.clear(imageFilePath, rawFileName, revertFileName);
// 取出该黑白图片的特征
INDArray features = ImageFileUtil.getGrayImageFeatures(imageFilePath, resizeFileName);
// 将特征传给模型去识别
return net.predict(features)[0];
}
} | repos\springboot-demo-master\Deeplearning4j\src\main\java\com\et\dl4j\service\impl\PredictServiceImpl.java | 2 |
请完成以下Java代码 | public String toString() {
return "Using " + dependency1 + " and " + dependency2;
}
}
@Component
class Dependency1 {
}
@Component
class Dependency2 {
} | @Configuration
@ComponentScan
public class DepInjectionLauncherApplication {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(DepInjectionLauncherApplication.class)) {
Arrays.stream(context.getBeanDefinitionNames()).forEach(System.out::println);
System.out.println(context.getBean(YourBusinessClass.class));
}
}
} | repos\master-spring-and-spring-boot-main\01-spring\learn-spring-framework-02\src\main\java\com\in28minutes\learnspringframework\examples\a1\DepInjectionLauncherApplication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class PricingSummary {\n");
sb.append(" adjustment: ").append(toIndentedString(adjustment)).append("\n");
sb.append(" deliveryCost: ").append(toIndentedString(deliveryCost)).append("\n");
sb.append(" deliveryDiscount: ").append(toIndentedString(deliveryDiscount)).append("\n");
sb.append(" fee: ").append(toIndentedString(fee)).append("\n");
sb.append(" priceDiscountSubtotal: ").append(toIndentedString(priceDiscountSubtotal)).append("\n");
sb.append(" priceSubtotal: ").append(toIndentedString(priceSubtotal)).append("\n");
sb.append(" tax: ").append(toIndentedString(tax)).append("\n");
sb.append(" total: ").append(toIndentedString(total)).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(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\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PricingSummary.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int getConnectionPoolSize() {
return connectionPoolSize;
}
public void setConnectionPoolSize(int connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public boolean isDnsMonitoring() {
return dnsMonitoring;
}
public void setDnsMonitoring(boolean dnsMonitoring) { | this.dnsMonitoring = dnsMonitoring;
}
public int getDnsMonitoringInterval() {
return dnsMonitoringInterval;
}
public void setDnsMonitoringInterval(int dnsMonitoringInterval) {
this.dnsMonitoringInterval = dnsMonitoringInterval;
}
public String getCodec() {
return codec;
}
public void setCodec(String codec) {
this.codec = codec;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\config\RedissonConfig.java | 2 |
请完成以下Java代码 | public Builder registrationClientUrl(String registrationClientUrl) {
return claim(OidcClientMetadataClaimNames.REGISTRATION_CLIENT_URI, registrationClientUrl);
}
/**
* Validate the claims and build the {@link OidcClientRegistration}.
* <p>
* The following claims are REQUIRED: {@code client_id}, {@code redirect_uris}.
* @return the {@link OidcClientRegistration}
*/
@Override
public OidcClientRegistration build() {
validate();
return new OidcClientRegistration(getClaims());
}
@Override
protected void validate() {
super.validate();
Assert.notNull(getClaims().get(OidcClientMetadataClaimNames.REDIRECT_URIS), "redirect_uris cannot be null");
Assert.isInstanceOf(List.class, getClaims().get(OidcClientMetadataClaimNames.REDIRECT_URIS),
"redirect_uris must be of type List");
Assert.notEmpty((List<?>) getClaims().get(OidcClientMetadataClaimNames.REDIRECT_URIS),
"redirect_uris cannot be empty");
if (getClaims().get(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS) != null) {
Assert.isInstanceOf(List.class, getClaims().get(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS),
"post_logout_redirect_uris must be of type List");
Assert.notEmpty((List<?>) getClaims().get(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS),
"post_logout_redirect_uris cannot be empty");
}
}
@SuppressWarnings("unchecked") | private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
((List<String>) getClaims().get(name)).add(value);
}
@SuppressWarnings("unchecked")
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
List<String> values = (List<String>) getClaims().get(name);
valuesConsumer.accept(values);
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\OidcClientRegistration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Region region = (Region) o;
return Objects.equals(this._id, region._id) &&
Objects.equals(this.label, region.label) &&
Objects.equals(this.parent, region.parent) &&
Objects.equals(this.timestamp, region.timestamp);
}
@Override
public int hashCode() {
return Objects.hash(_id, label, parent, timestamp);
}
@Override
public String toString() { | StringBuilder sb = new StringBuilder();
sb.append("class Region {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" label: ").append(toIndentedString(label)).append("\n");
sb.append(" parent: ").append(toIndentedString(parent)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).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-patient-api\src\main\java\io\swagger\client\model\Region.java | 2 |
请完成以下Java代码 | public Collection<Decision> getInputDecisions() {
return inputDecisionRefCollection.getReferenceTargetElements(this);
}
public Collection<InputData> getInputData() {
return inputDataRefCollection.getReferenceTargetElements(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionService.class, DMN_ELEMENT_DECISION_SERVICE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(NamedElement.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionService>() {
public DecisionService newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionServiceImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
outputDecisionRefCollection = sequenceBuilder.elementCollection(OutputDecisionReference.class)
.required()
.uriElementReferenceCollection(Decision.class)
.build();
encapsulatedDecisionRefCollection = sequenceBuilder.elementCollection(EncapsulatedDecisionReference.class) | .uriElementReferenceCollection(Decision.class)
.build();
inputDecisionRefCollection = sequenceBuilder.elementCollection(InputDecisionReference.class)
.uriElementReferenceCollection(Decision.class)
.build();
inputDataRefCollection = sequenceBuilder.elementCollection(InputDataReference.class)
.uriElementReferenceCollection(InputData.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionServiceImpl.java | 1 |
请完成以下Java代码 | public static double withTwoDecimalPlaces(double value) {
DecimalFormat df = new DecimalFormat("#.00");
return Double.valueOf(df.format(value));
}
public static String withLargeIntegers(double value) {
DecimalFormat df = new DecimalFormat("###,###,###");
return df.format(value);
}
public static String forPercentages(double value, Locale localisation) {
NumberFormat nf = NumberFormat.getPercentInstance(localisation);
return nf.format(value);
}
public static String currencyWithChosenLocalisation(double value, Locale localisation) {
NumberFormat nf = NumberFormat.getCurrencyInstance(localisation);
return nf.format(value); | }
public static String currencyWithDefaultLocalisation(double value) {
NumberFormat nf = NumberFormat.getCurrencyInstance();
return nf.format(value);
}
public static String formatScientificNotation(double value, Locale localisation) {
return String.format(localisation, "%.3E", value);
}
public static String formatScientificNotationWithMinChars(double value, Locale localisation) {
return String.format(localisation, "%12.4E", value);
}
} | repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\formatNumber\FormatNumber.java | 1 |
请完成以下Java代码 | default void setQtyCUsPerTU(final BigDecimal qtyCUsPerTU) {}
default Optional<BigDecimal> getQtyCUsPerTU() {return Optional.empty();}
int getC_BPartner_ID();
/**
* Checks if this record is in dispute.
* <p>
* For records which are in dispute:
* <ul>
* <li>QtyPacks will be set to ZERO
* </ul>
*
* @return true if this record is in dispute
*/
boolean isInDispute();
void setInDispute(boolean inDispute); | default BigDecimal getQtyLU() {return BigDecimal.ZERO;}
/**
* @param qtyLU generally may not be null, but you are free to provide {@link BigDecimal#ZERO} instead.
*/
default void setQtyLU(@NonNull final BigDecimal qtyLU) {}
@Nullable
default HuPackingInstructionsId getLuId()
{
return null;
}
default void setLuId(@Nullable final HuPackingInstructionsId luId) {}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\IHUPackingAware.java | 1 |
请完成以下Java代码 | public class Role extends Model<Role> {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value="id", type= IdType.AUTO)
private Integer id;
/**
* 角色名称
*/
private String role;
/**
* 角色说明
*/
private String description;
/**
* 创建时间
*/
private Date createdTime;
/**
* 更新时间
*/
private Date updatedTime;
/**
* 获取 主键ID.
*
* @return 主键ID.
*/
public Integer getId() {
return id;
}
/**
* 设置 主键ID.
*
* @param id 主键ID.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取 角色名称.
*
* @return 角色名称.
*/
public String getRole() {
return role;
}
/**
* 设置 角色名称.
*
* @param role 角色名称.
*/
public void setRole(String role) {
this.role = role;
}
/**
* 获取 角色说明.
*
* @return 角色说明.
*/
public String getDescription() {
return description;
}
/**
* 设置 角色说明.
*
* @param description 角色说明.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 获取 创建时间.
* | * @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;
}
@Override
protected Serializable pkVal() {
return this.id;
}
} | repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\common\dao\entity\Role.java | 1 |
请完成以下Java代码 | public int getPort() {
return port;
}
public Builder setPort(int port) {
this.port = port;
return this;
}
public String getTopic() {
return topic;
}
public Builder setTopic(String topic) {
this.topic = topic;
return this;
}
public String getPartition() {
return partition;
}
public Builder setPartition(String partition) {
this.partition = partition;
return this;
}
@Override | public KafkaAppender build() {
return new KafkaAppender(getName(), getFilter(), getLayout(), true, new KafkaBroker(ipAddress, port, topic, partition));
}
}
private KafkaBroker broker;
private KafkaAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, KafkaBroker broker) {
super(name, filter, layout, ignoreExceptions);
this.broker = broker;
}
@Override
public void append(LogEvent event) {
connectAndSendToKafka(broker, event);
}
private void connectAndSendToKafka(KafkaBroker broker, LogEvent event) {
//send to Kafka
}
} | repos\tutorials-master\logging-modules\log4j2\src\main\java\com\baeldung\logging\log4j2\plugins\KafkaAppender.java | 1 |
请完成以下Java代码 | public int getCurrentNext ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CurrentNext);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Increment.
@param IncrementNo
The number to increment the last document number by
*/
public void setIncrementNo (int IncrementNo)
{
set_Value (COLUMNNAME_IncrementNo, Integer.valueOf(IncrementNo));
}
/** Get Increment.
@return The number to increment the last document number by
*/
public int getIncrementNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IncrementNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lot Control.
@param M_LotCtl_ID
Product Lot Control
*/
public void setM_LotCtl_ID (int M_LotCtl_ID)
{
if (M_LotCtl_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID));
}
/** Get Lot Control.
@return Product Lot Control
*/
public int getM_LotCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Prefix.
@param Prefix
Prefix before the sequence number
*/
public void setPrefix (String Prefix)
{
set_Value (COLUMNNAME_Prefix, Prefix);
} | /** Get Prefix.
@return Prefix before the sequence number
*/
public String getPrefix ()
{
return (String)get_Value(COLUMNNAME_Prefix);
}
/** Set Start No.
@param StartNo
Starting number/position
*/
public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suffix.
@param Suffix
Suffix after the number
*/
public void setSuffix (String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
/** Get Suffix.
@return Suffix after the number
*/
public String getSuffix ()
{
return (String)get_Value(COLUMNNAME_Suffix);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtl.java | 1 |
请完成以下Java代码 | public void run()
{
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
final Lookup lookup = gridField.getLookup();
final int windowNo = gridField.getWindowNo();
final VBPartner vbp = new VBPartner(Env.getWindow(windowNo), windowNo);
int BPartner_ID = 0;
// if update, get current value
if (!createNew)
{
final Object value = editor.getValue();
if (value instanceof Integer)
BPartner_ID = ((Integer)value).intValue();
else if (value != null)
BPartner_ID = Integer.parseInt(value.toString());
} | vbp.loadBPartner(BPartner_ID);
vbp.setVisible(true);
// get result
int result = vbp.getC_BPartner_ID();
if (result == 0 // 0 = not saved
&& result == BPartner_ID) // the same
return;
// Maybe new BPartner - put in cache
lookup.getDirect(IValidationContext.NULL, new Integer(result), false, true);
// actionCombo (new Integer(result)); // data binding
gridField.getGridTab().setValue(gridField, result);
} // actionBPartner
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\BPartnerNewUpdateContextEditorAction.java | 1 |
请完成以下Java代码 | public Boolean isValidDate(Date newTimer) {
return end == null || end.getTime().after(newTimer) || end.getTime().equals(newTimer);
}
public Date getDateAfter() {
Calendar date = getCalendarAfter();
return date == null ? null : date.getTime();
}
private Calendar getDateAfterRepeat(Calendar date) {
Calendar current = TimeZoneUtil.convertToTimeZone(start, date.getTimeZone());
if (repeatWithNoBounds) {
while (current.before(date) || current.equals(date)) {
// As long as current date is not past the engine date, we keep looping
Calendar newTime = add(current, period);
if (newTime.equals(current) || newTime.before(current)) {
break;
}
current = newTime;
}
} else {
int maxLoops = times;
if (maxIterations > 0) {
maxLoops = maxIterations - times;
}
for (int i = 0; i < maxLoops + 1 && !current.after(date); i++) {
current = add(current, period);
}
}
return current.before(date) ? date : TimeZoneUtil.convertToTimeZone(current, clockReader.getCurrentTimeZone());
}
protected Calendar add(Calendar date, Duration duration) {
Calendar calendar = (Calendar) date.clone();
// duration.addTo does not account for daylight saving time (xerces),
// reversing order of addition fixes the problem
calendar.add(Calendar.SECOND, duration.getSeconds() * duration.getSign()); | calendar.add(Calendar.MINUTE, duration.getMinutes() * duration.getSign());
calendar.add(Calendar.HOUR, duration.getHours() * duration.getSign());
calendar.add(Calendar.DAY_OF_MONTH, duration.getDays() * duration.getSign());
calendar.add(Calendar.MONTH, duration.getMonths() * duration.getSign());
calendar.add(Calendar.YEAR, duration.getYears() * duration.getSign());
return calendar;
}
protected Calendar parseDate(String date) throws Exception {
Calendar dateCalendar = null;
try {
dateCalendar = ISODateTimeFormat.dateTimeParser()
.withZone(DateTimeZone.forTimeZone(clockReader.getCurrentTimeZone()))
.parseDateTime(date)
.toCalendar(null);
} catch (IllegalArgumentException e) {
// try to parse a java.util.date to string back to a java.util.date
dateCalendar = new GregorianCalendar();
DateFormat DATE_FORMAT = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
dateCalendar.setTime(DATE_FORMAT.parse(date));
}
return dateCalendar;
}
protected Duration parsePeriod(String period) throws Exception {
return datatypeFactory.newDuration(period);
}
protected boolean isDuration(String time) {
return time.startsWith("P");
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\DurationHelper.java | 1 |
请完成以下Java代码 | public class StartProcessInstanceCmd implements Command<ProcessInstanceWithVariables>, Serializable {
private static final long serialVersionUID = 1L;
protected final ProcessInstantiationBuilderImpl instantiationBuilder;
public StartProcessInstanceCmd(ProcessInstantiationBuilderImpl instantiationBuilder) {
this.instantiationBuilder = instantiationBuilder;
}
public ProcessInstanceWithVariables execute(CommandContext commandContext) {
ProcessDefinitionEntity processDefinition = new GetDeployedProcessDefinitionCmd(instantiationBuilder, false).execute(commandContext);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkCreateProcessInstance(processDefinition);
}
// Start the process instance
ExecutionEntity processInstance = processDefinition.createProcessInstance(instantiationBuilder.getBusinessKey(),
instantiationBuilder.getCaseInstanceId()); | if (instantiationBuilder.getTenantId() != null) {
processInstance.setTenantId(instantiationBuilder.getTenantId());
}
final ExecutionVariableSnapshotObserver variablesListener = new ExecutionVariableSnapshotObserver(processInstance);
processInstance.start(instantiationBuilder.getVariables());
commandContext.getOperationLogManager().logProcessInstanceOperation(
UserOperationLogEntry.OPERATION_TYPE_CREATE,
processInstance.getId(),
processInstance.getProcessDefinitionId(),
processInstance.getProcessDefinition().getKey(),
Collections.singletonList(PropertyChange.EMPTY_CHANGE));
return new ProcessInstanceWithVariablesImpl(processInstance, variablesListener.getVariables());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\StartProcessInstanceCmd.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null) | {
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Convention.java | 1 |
请完成以下Java代码 | public boolean hasColumnName(final String columnName) {return po.getPOInfo().hasColumnName(columnName);}
@Override
public int getValueAsIntOrZero(final String columnName)
{
final int index = po.get_ColumnIndex(columnName);
if (index != -1)
{
final Integer ii = (Integer)po.get_Value(index);
if (ii != null)
{
return ii;
}
}
return 0;
}
@Override
@Nullable
public <T extends RepoIdAware> T getValueAsIdOrNull(final String columnName, final IntFunction<T> idOrNullMapper)
{
final int index = po.get_ColumnIndex(columnName);
if (index < 0)
{
return null;
}
final Object valueObj = po.get_Value(index);
final Integer valueInt = NumberUtils.asInteger(valueObj, null);
if (valueInt == null)
{
return null;
}
return idOrNullMapper.apply(valueInt);
}
@Override
@Nullable
public LocalDateAndOrgId getValueAsLocalDateOrNull(@NonNull final String columnName, @NonNull final Function<OrgId, ZoneId> timeZoneMapper)
{
final int index = po.get_ColumnIndex(columnName);
if (index != -1)
{
final Timestamp ts = po.get_ValueAsTimestamp(index);
if (ts != null)
{
final OrgId orgId = OrgId.ofRepoId(po.getAD_Org_ID());
return LocalDateAndOrgId.ofTimestamp(ts, orgId, timeZoneMapper);
} | }
return null;
}
@Override
@Nullable
public Boolean getValueAsBooleanOrNull(@NonNull final String columnName)
{
final int index = po.get_ColumnIndex(columnName);
if (index != -1)
{
final Object valueObj = po.get_Value(index);
return DisplayType.toBoolean(valueObj, null);
}
return null;
}
@Override
@Nullable
public String getValueAsString(@NonNull final String columnName)
{
final int index = po.get_ColumnIndex(columnName);
if (index != -1)
{
final Object valueObj = po.get_Value(index);
return valueObj != null ? valueObj.toString() : null;
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\POAcctDocModel.java | 1 |
请完成以下Java代码 | private GeocodingProvider createProvider(@NonNull final GeocodingConfig config)
{
final GeocodingProviderName providerName = config.getProviderName();
if (GeocodingProviderName.GOOGLE_MAPS.equals(providerName))
{
return createGoogleMapsProvider(config.getGoogleMapsConfig());
}
else if (GeocodingProviderName.OPEN_STREET_MAPS.equals(providerName))
{
return createOSMProvider(config.getOpenStreetMapsConfig());
}
else
{
throw new AdempiereException("Unknown provider: " + providerName);
}
}
@NonNull private GoogleMapsGeocodingProviderImpl createGoogleMapsProvider(@NonNull final GoogleMapsConfig config)
{ | final String apiKey = config.getApiKey();
final int cacheCapacity = config.getCacheCapacity();
final GeoApiContext context = new GeoApiContext.Builder()
.apiKey(apiKey)
.build();
return new GoogleMapsGeocodingProviderImpl(context, cacheCapacity);
}
@NonNull private NominatimOSMGeocodingProviderImpl createOSMProvider(@NonNull final OpenStreetMapsConfig config)
{
final String baseURL = config.getBaseURL();
final int cacheCapacity = config.getCacheCapacity();
final long millisBetweenRequests = config.getMillisBetweenRequests();
return new NominatimOSMGeocodingProviderImpl(baseURL, millisBetweenRequests, cacheCapacity);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\provider\GeocodingProviderFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void setEntityFields(Edge entity, Map<BulkImportColumnType, String> fields) {
ObjectNode additionalInfo = getOrCreateAdditionalInfoObj(entity);
fields.forEach((columnType, value) -> {
switch (columnType) {
case NAME:
entity.setName(value);
break;
case TYPE:
entity.setType(value);
break;
case LABEL:
entity.setLabel(value);
break;
case DESCRIPTION:
additionalInfo.set("description", new TextNode(value));
break;
case ROUTING_KEY:
entity.setRoutingKey(value);
break;
case SECRET:
entity.setSecret(value);
break;
}
});
entity.setAdditionalInfo(additionalInfo);
}
@SneakyThrows
@Override
protected Edge saveEntity(SecurityUser user, Edge entity, Map<BulkImportColumnType, String> fields) {
RuleChain edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(user.getTenantId());
return tbEdgeService.save(entity, edgeTemplateRootRuleChain, user);
} | @Override
protected Edge findOrCreateEntity(TenantId tenantId, String name) {
return Optional.ofNullable(edgeService.findEdgeByTenantIdAndName(tenantId, name))
.orElseGet(Edge::new);
}
@Override
protected void setOwners(Edge entity, SecurityUser user) {
entity.setTenantId(user.getTenantId());
entity.setCustomerId(user.getCustomerId());
}
@Override
protected EntityType getEntityType() {
return EntityType.EDGE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\EdgeBulkImportService.java | 2 |
请完成以下Java代码 | public static String getDockerHost() {
return DOCKER_HOST;
}
/**
* Retrieve docker port
*
* @return empty string if not a docker
*/
public static String getDockerPort() {
return DOCKER_PORT;
}
/**
* Whether a docker
*
* @return
*/
public static boolean isDocker() {
return IS_DOCKER;
}
/**
* Retrieve host & port from environment
*/
private static void retrieveFromEnv() {
// retrieve host & port from environment
DOCKER_HOST = System.getenv(ENV_KEY_HOST);
DOCKER_PORT = System.getenv(ENV_KEY_PORT);
// not found from 'JPAAS_HTTP_PORT', then try to find from 'JPAAS_HOST_PORT_8080'
if (StringUtils.isBlank(DOCKER_PORT)) { | DOCKER_PORT = System.getenv(ENV_KEY_PORT_ORIGINAL);
}
boolean hasEnvHost = StringUtils.isNotBlank(DOCKER_HOST);
boolean hasEnvPort = StringUtils.isNotBlank(DOCKER_PORT);
// docker can find both host & port from environment
if (hasEnvHost && hasEnvPort) {
IS_DOCKER = true;
// found nothing means not a docker, maybe an actual machine
} else if (!hasEnvHost && !hasEnvPort) {
IS_DOCKER = false;
} else {
LOGGER.error("Missing host or port from env for Docker. host:{}, port:{}", DOCKER_HOST, DOCKER_PORT);
throw new RuntimeException(
"Missing host or port from env for Docker. host:" + DOCKER_HOST + ", port:" + DOCKER_PORT);
}
}
} | repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\DockerUtils.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
if(args.length != 2) {
throw LOG.invokeSchemaResourceToolException(args.length);
}
final String configurationFileResourceName = args[0];
final String schemaFileResourceName = args[1];
ensureNotNull("Process engine configuration file name cannot be null", "configurationFileResourceName", configurationFileResourceName);
ensureNotNull("Schema resource file name cannot be null", "schemaFileResourceName", schemaFileResourceName);
ProcessEngineConfigurationImpl configuration = (ProcessEngineConfigurationImpl) ProcessEngineConfiguration.createProcessEngineConfigurationFromResource(configurationFileResourceName);
ProcessEngine processEngine = configuration.buildProcessEngine();
configuration.getCommandExecutorTxRequired().execute(new Command<Void>() { | public Void execute(CommandContext commandContext) {
commandContext.getDbSqlSession()
.executeSchemaResource(schemaFileResourceName);
return null;
}
});
processEngine.close();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\DbSchemaExecuteFile.java | 1 |
请完成以下Java代码 | public void destroy() throws Exception {
logger.info(ProcessScope.class.getName() + "#destroy() called ...");
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.processEngine, "the 'processEngine' must not be null!");
this.runtimeService = this.processEngine.getRuntimeService();
}
private Object createDirtyCheckingProxy(final String name, final Object scopedObject) throws Throwable {
ProxyFactory proxyFactoryBean = new ProxyFactory(scopedObject);
proxyFactoryBean.setProxyTargetClass(this.proxyTargetClass);
proxyFactoryBean.addAdvice(new MethodInterceptor() {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Object result = methodInvocation.proceed(); | persistVariable(name, scopedObject);
return result;
}
});
return proxyFactoryBean.getProxy(this.classLoader);
}
private void persistVariable(String variableName, Object scopedObject) {
ProcessInstance processInstance = Context.getExecutionContext().getProcessInstance();
ExecutionEntity executionEntity = (ExecutionEntity) processInstance;
Assert.isTrue(scopedObject instanceof Serializable, "the scopedObject is not " + Serializable.class.getName() + "!");
executionEntity.setVariable(variableName, scopedObject);
}
} | repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\scope\ProcessScope.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ObservableRejectAndDontRequeueRecoverer observableRecoverer() {
return new ObservableRejectAndDontRequeueRecoverer();
}
@Bean
public RetryOperationsInterceptor retryInterceptor() {
return RetryInterceptorBuilder.stateless()
.backOffOptions(1000, 3.0, 10000)
.maxAttempts(5)
.recoverer(observableRecoverer())
.build();
}
@Bean
public RetryQueuesInterceptor retryQueuesInterceptor(RabbitTemplate rabbitTemplate, RetryQueues retryQueues) {
return new RetryQueuesInterceptor(rabbitTemplate, retryQueues);
}
@Bean
public SimpleRabbitListenerContainerFactory defaultContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
return factory;
}
@Bean
public SimpleRabbitListenerContainerFactory retryContainerFactory(ConnectionFactory connectionFactory, RetryOperationsInterceptor retryInterceptor) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
Advice[] adviceChain = { retryInterceptor };
factory.setAdviceChain(adviceChain);
return factory;
}
@Bean
public SimpleRabbitListenerContainerFactory retryQueuesContainerFactory(ConnectionFactory connectionFactory, RetryQueuesInterceptor retryInterceptor) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
Advice[] adviceChain = { retryInterceptor };
factory.setAdviceChain(adviceChain);
return factory;
} | @RabbitListener(queues = "blocking-queue", containerFactory = "retryContainerFactory")
public void consumeBlocking(String payload) throws Exception {
logger.info("Processing message from blocking-queue: {}", payload);
throw new Exception("exception occured!");
}
@RabbitListener(queues = "non-blocking-queue", containerFactory = "retryQueuesContainerFactory", ackMode = "MANUAL")
public void consumeNonBlocking(String payload) throws Exception {
logger.info("Processing message from non-blocking-queue: {}", payload);
throw new Exception("Error occured!");
}
@RabbitListener(queues = "retry-wait-ended-queue", containerFactory = "defaultContainerFactory")
public void consumeRetryWaitEndedMessage(String payload, Message message, Channel channel) throws Exception {
MessageProperties props = message.getMessageProperties();
rabbitTemplate().convertAndSend(props.getHeader("x-original-exchange"), props.getHeader("x-original-routing-key"), message);
}
} | repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\exponentialbackoff\RabbitConfiguration.java | 2 |
请完成以下Java代码 | public void setEDI_cctop_invoic_v(final de.metas.esb.edi.model.I_EDI_cctop_invoic_v EDI_cctop_invoic_v)
{
set_ValueFromPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class, EDI_cctop_invoic_v);
}
@Override
public void setEDI_cctop_invoic_v_ID (final int EDI_cctop_invoic_v_ID)
{
if (EDI_cctop_invoic_v_ID < 1)
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null);
else
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, EDI_cctop_invoic_v_ID);
}
@Override
public int getEDI_cctop_invoic_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID);
}
@Override
public void setISO_Code (final @Nullable java.lang.String ISO_Code)
{
set_Value (COLUMNNAME_ISO_Code, ISO_Code);
}
@Override
public java.lang.String getISO_Code()
{
return get_ValueAsString(COLUMNNAME_ISO_Code);
}
@Override
public void setnetdate (final @Nullable java.sql.Timestamp netdate)
{
set_Value (COLUMNNAME_netdate, netdate);
}
@Override
public java.sql.Timestamp getnetdate()
{
return get_ValueAsTimestamp(COLUMNNAME_netdate);
}
@Override
public void setNetDays (final int NetDays)
{
set_Value (COLUMNNAME_NetDays, NetDays);
}
@Override
public int getNetDays()
{ | return get_ValueAsInt(COLUMNNAME_NetDays);
}
@Override
public void setsinglevat (final @Nullable BigDecimal singlevat)
{
set_Value (COLUMNNAME_singlevat, singlevat);
}
@Override
public BigDecimal getsinglevat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_singlevat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void settaxfree (final boolean taxfree)
{
set_Value (COLUMNNAME_taxfree, taxfree);
}
@Override
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_120_v.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UserVO get3(@RequestParam("id") Integer id) {
// 查询并返回用户
return new UserVO().setId(id).setUsername(UUID.randomUUID().toString());
}
/**
* 测试抛出 NullPointerException 异常
*/
@GetMapping("/exception-01")
public UserVO exception01() {
throw new NullPointerException("没有粗面鱼丸");
}
/**
* 测试抛出 ServiceException 异常
*/
@GetMapping("/exception-02")
public UserVO exception02() {
throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND);
}
@GetMapping("/do_something")
public void doSomething() {
logger.info("[doSomething]");
}
@GetMapping("/current_user")
public UserVO currentUser() {
logger.info("[currentUser]");
return new UserVO().setId(10).setUsername(UUID.randomUUID().toString());
}
@GetMapping("/exception-03") | public void exception03() {
logger.info("[exception03]");
throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND);
}
@PostMapping(value = "/add",
// ↓ 增加 "application/xml"、"application/json" ,针对 Content-Type 请求头
consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE},
// ↓ 增加 "application/xml"、"application/json" ,针对 Accept 请求头
produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}
)
public UserVO add(@RequestBody UserVO user) {
return user;
}
} | repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-02\src\main\java\cn\iocoder\springboot\lab23\springmvc\controller\UserController.java | 2 |
请完成以下Java代码 | public class MD_Candidate_Request_MaterialDocument extends JavaProcess implements IProcessPrecondition
{
private static final AdMessageKey MSG_MISSING_PRODUCTION_OR_DISTRIBUTRION_RECORDS = AdMessageKey.of("de.metas.material.dispo.MD_Candidate_Request_MaterialDocument_No_Matching_Records_Selected");
private final RequestMaterialOrderService service = SpringContextHolder.instance.getBean(RequestMaterialOrderService.class);
private final Predicate<I_MD_Candidate> hasSupportedBusinessCase = r -> {
final CandidateBusinessCase businessCase = CandidateBusinessCase.ofNullableCode(r.getMD_Candidate_BusinessCase());
return CandidateBusinessCase.PRODUCTION.equals(businessCase)
|| CandidateBusinessCase.DISTRIBUTION.equals(businessCase)
|| CandidateBusinessCase.PURCHASE.equals(businessCase)
|| CandidateBusinessCase.FORECAST.equals(businessCase);
};
private final Predicate<I_MD_Candidate> statusIsDocPlanned = r -> {
final String status = r.getMD_Candidate_Status();
return X_MD_Candidate.MD_CANDIDATE_STATUS_Doc_planned.equals(status)
|| X_MD_Candidate.MD_CANDIDATE_STATUS_Planned.equals(status);
};
@Override
protected String doIt() throws Exception
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final EventDescriptor eventDescriptor = EventDescriptor.ofClientAndOrg(Env.getClientAndOrgId());
queryBL.createQueryBuilder(I_MD_Candidate.class)
.addOnlyActiveRecordsFilter()
.filter(getProcessInfo().getQueryFilterOrElseFalse())
.create() | .iterateAndStream()
.filter(hasSupportedBusinessCase)
.filter(statusIsDocPlanned)
.map(r -> MaterialDispoGroupId.ofInt(r.getMD_Candidate_GroupId()))
.distinct()
.peek(groupId -> addLog("Calling {}.requestOrder() for groupId={}", RequestMaterialOrderService.class.getSimpleName(), groupId))
.forEach(groupId -> service.requestMaterialOrderForCandidates(groupId, eventDescriptor));
return MSG_OK;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final boolean atLeastOneProperCandidateSelected = context.streamSelectedModels(I_MD_Candidate.class)
.anyMatch(selectedRecord -> hasSupportedBusinessCase.test(selectedRecord)
&& statusIsDocPlanned.test(selectedRecord));
if (!atLeastOneProperCandidateSelected)
{
final ITranslatableString translatable = msgBL.getTranslatableMsgText(MSG_MISSING_PRODUCTION_OR_DISTRIBUTRION_RECORDS);
return ProcessPreconditionsResolution.reject(translatable);
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\process\MD_Candidate_Request_MaterialDocument.java | 1 |
请完成以下Java代码 | public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
@Override
public String toString() { | StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", newsId=").append(newsId);
sb.append(", newsTitle=").append(newsTitle);
sb.append(", newsCategoryId=").append(newsCategoryId);
sb.append(", newsCoverImage=").append(newsCoverImage);
sb.append(", newsStatus=").append(newsStatus);
sb.append(", newsViews=").append(newsViews);
sb.append(", isDeleted=").append(isDeleted);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append("]");
return sb.toString();
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\News.java | 1 |
请完成以下Java代码 | public void setHR_Expense_Acct (int HR_Expense_Acct)
{
set_Value (COLUMNNAME_HR_Expense_Acct, Integer.valueOf(HR_Expense_Acct));
}
/** Get Payroll Expense Account.
@return Payroll Expense Account */
public int getHR_Expense_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Expense_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getHR_Revenue_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getHR_Revenue_Acct(), get_TrxName()); }
/** Set Payroll Revenue Account.
@param HR_Revenue_Acct Payroll Revenue Account */
public void setHR_Revenue_Acct (int HR_Revenue_Acct)
{
set_Value (COLUMNNAME_HR_Revenue_Acct, Integer.valueOf(HR_Revenue_Acct));
}
/** Get Payroll Revenue Account.
@return Payroll Revenue Account */
public int getHR_Revenue_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Revenue_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Balancing.
@param IsBalancing
All transactions within an element value must balance (e.g. cost centers)
*/
public void setIsBalancing (boolean IsBalancing)
{
set_Value (COLUMNNAME_IsBalancing, Boolean.valueOf(IsBalancing));
}
/** Get Balancing.
@return All transactions within an element value must balance (e.g. cost centers)
*/
public boolean isBalancing ()
{
Object oo = get_Value(COLUMNNAME_IsBalancing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_C_ElementValue getUser1() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser1_ID(), get_TrxName()); }
/** Set User List 1.
@param User1_ID
User defined list element #1
*/
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1 | */
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getUser2() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getUser2_ID(), get_TrxName()); }
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CostDetailPreviousAmounts
{
@NonNull UomId uomId;
@NonNull CurrencyId currencyId;
@NonNull CostPrice costPrice;
@NonNull Quantity qty;
@NonNull CostAmount cumulatedAmt;
@NonNull Quantity cumulatedQty;
@Builder
private CostDetailPreviousAmounts(
@NonNull final CostPrice costPrice,
@NonNull final Quantity qty,
@NonNull final CostAmount cumulatedAmt,
@NonNull final Quantity cumulatedQty)
{
if (!CurrencyId.equals(costPrice.getCurrencyId(), cumulatedAmt.getCurrencyId()))
{
throw new AdempiereException("Currency not matching: costPrice=" + costPrice + ", cumulatedAmt=" + cumulatedAmt);
} | this.uomId = Quantity.getCommonUomIdOfAll(qty, cumulatedQty);
this.currencyId = costPrice.getCurrencyId();
this.costPrice = costPrice;
this.qty = qty;
this.cumulatedAmt = cumulatedAmt;
this.cumulatedQty = cumulatedQty;
}
public static CostDetailPreviousAmounts of(@NonNull final CurrentCost currentCost)
{
return builder()
.costPrice(currentCost.getCostPrice())
.qty(currentCost.getCurrentQty())
.cumulatedAmt(currentCost.getCumulatedAmt())
.cumulatedQty(currentCost.getCumulatedQty())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailPreviousAmounts.java | 2 |
请完成以下Java代码 | public void addEventHandler(FlowableEngineEventType eventType, Class<? extends EventLoggerEventHandler> eventHandlerClass) {
eventHandlers.put(eventType, eventHandlerClass);
}
public void addEventLoggerListener(EventLoggerListener listener) {
if (listeners == null) {
listeners = new ArrayList<>(1);
}
listeners.add(listener);
}
/**
* Subclasses that want something else than the database flusher should override this method
*/
protected EventFlusher createEventFlusher() {
return null;
}
public Clock getClock() {
return clock;
}
public void setClock(Clock clock) {
this.clock = clock;
} | public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public List<EventLoggerListener> getListeners() {
return listeners;
}
public void setListeners(List<EventLoggerListener> listeners) {
this.listeners = listeners;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\event\logger\EventLogger.java | 1 |
请完成以下Java代码 | final class CipherUtils {
private CipherUtils() {
}
/**
* Generates a SecretKey.
*/
static SecretKey newSecretKey(String algorithm, String password) {
return newSecretKey(algorithm, new PBEKeySpec(password.toCharArray()));
}
/**
* Generates a SecretKey.
*/
static SecretKey newSecretKey(String algorithm, PBEKeySpec keySpec) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
return factory.generateSecret(keySpec);
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalArgumentException("Not a valid encryption algorithm", ex);
}
catch (InvalidKeySpecException ex) {
throw new IllegalArgumentException("Not a valid secret key", ex);
}
}
/**
* Constructs a new Cipher.
*/
static Cipher newCipher(String algorithm) {
try {
return Cipher.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalArgumentException("Not a valid encryption algorithm", ex);
}
catch (NoSuchPaddingException ex) {
throw new IllegalStateException("Should not happen", ex);
}
}
/**
* Initializes the Cipher for use.
*/
static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) {
try {
return cipher.getParameters().getParameterSpec(parameterSpecClass);
}
catch (InvalidParameterSpecException ex) {
throw new IllegalArgumentException("Unable to access parameter", ex);
}
}
/**
* Initializes the Cipher for use.
*/
static void initCipher(Cipher cipher, int mode, SecretKey secretKey) { | initCipher(cipher, mode, secretKey, null);
}
/**
* Initializes the Cipher for use.
*/
static void initCipher(Cipher cipher, int mode, SecretKey secretKey, byte[] salt, int iterationCount) {
initCipher(cipher, mode, secretKey, new PBEParameterSpec(salt, iterationCount));
}
/**
* Initializes the Cipher for use.
*/
static void initCipher(Cipher cipher, int mode, SecretKey secretKey,
@Nullable AlgorithmParameterSpec parameterSpec) {
try {
if (parameterSpec != null) {
cipher.init(mode, secretKey, parameterSpec);
}
else {
cipher.init(mode, secretKey);
}
}
catch (InvalidKeyException ex) {
throw new IllegalArgumentException("Unable to initialize due to invalid secret key", ex);
}
catch (InvalidAlgorithmParameterException ex) {
throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec", ex);
}
}
/**
* Invokes the Cipher to perform encryption or decryption (depending on the
* initialized mode).
*/
static byte[] doFinal(Cipher cipher, byte[] input) {
try {
return cipher.doFinal(input);
}
catch (IllegalBlockSizeException ex) {
throw new IllegalStateException("Unable to invoke Cipher due to illegal block size", ex);
}
catch (BadPaddingException ex) {
throw new IllegalStateException("Unable to invoke Cipher due to bad padding", ex);
}
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\CipherUtils.java | 1 |
请完成以下Java代码 | public String[] getUserAttributes() {
return this.userAttributes;
}
/**
* Builds list of possible DNs for the user, worked out from the
* <tt>userDnPatterns</tt> property.
* @param username the user's login name
* @return the list of possible DN matches, empty if <tt>userDnPatterns</tt> wasn't
* set.
*/
protected List<String> getUserDns(String username) {
if (this.userDnFormat == null) {
return Collections.emptyList();
}
List<String> userDns = new ArrayList<>(this.userDnFormat.length);
String[] args = new String[] { LdapEncoder.nameEncode(username) };
synchronized (this.mutex) {
for (MessageFormat formatter : this.userDnFormat) {
userDns.add(formatter.format(args));
}
}
return userDns;
}
protected LdapUserSearch getUserSearch() {
return this.userSearch;
}
@Override
public void setMessageSource(@NonNull MessageSource messageSource) {
Assert.notNull(messageSource, "Message source must not be null");
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the user attributes which will be retrieved from the directory.
* @param userAttributes the set of user attributes to retrieve
*/
public void setUserAttributes(String[] userAttributes) {
Assert.notNull(userAttributes, "The userAttributes property cannot be set to null");
this.userAttributes = userAttributes;
}
/**
* Sets the pattern which will be used to supply a DN for the user. The pattern should | * be the name relative to the root DN. The pattern argument {0} will contain the
* username. An example would be "cn={0},ou=people".
* @param dnPattern the array of patterns which will be tried when converting a
* username to a DN.
*/
public void setUserDnPatterns(String[] dnPattern) {
Assert.notNull(dnPattern, "The array of DN patterns cannot be set to null");
// this.userDnPattern = dnPattern;
this.userDnFormat = new MessageFormat[dnPattern.length];
for (int i = 0; i < dnPattern.length; i++) {
this.userDnFormat[i] = new MessageFormat(dnPattern[i]);
}
}
public void setUserSearch(LdapUserSearch userSearch) {
Assert.notNull(userSearch, "The userSearch cannot be set to null");
this.userSearch = userSearch;
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\AbstractLdapAuthenticator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataEntrySubTab
{
DataEntrySubTabId id;
ITranslatableString caption;
ITranslatableString description;
String internalName;
ImmutableList<DataEntrySection> sections;
@Getter(AccessLevel.NONE)
@JsonIgnore
ImmutableMap<DataEntryFieldId, DataEntryField> fieldsById;
@Builder
private DataEntrySubTab(
@NonNull final DataEntrySubTabId id,
@NonNull final ITranslatableString caption,
@NonNull final ITranslatableString description,
@NonNull final String internalName,
@Singular final List<DataEntrySection> sections)
{
this.id = id;
this.caption = caption;
this.description = description;
this.internalName = internalName; | this.sections = ImmutableList.copyOf(sections);
fieldsById = this.sections.stream()
.flatMap(section -> section.getLines().stream())
.flatMap(line -> line.getFields().stream())
.collect(GuavaCollectors.toImmutableMapByKey(DataEntryField::getId));
}
public DataEntryField getFieldById(@NonNull final DataEntryFieldId fieldId)
{
final DataEntryField field = fieldsById.get(fieldId);
if (field == null)
{
throw new AdempiereException("@NotFound@ " + fieldId + " in " + this);
}
return field;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\layout\DataEntrySubTab.java | 2 |
请完成以下Java代码 | public void addSourceHUMarkerIfCarringComponents(@NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId)
{
addSourceHUMarkerIfCarringComponents(ImmutableSet.of(huId), productId, warehouseId);
}
/**
* Creates an M_Source_HU record for the given HU, if it carries component products and the target warehouse has
* the org.compiere.model.I_M_Warehouse#isReceiveAsSourceHU() flag.
*/
public void addSourceHUMarkerIfCarringComponents(@NonNull final Set<HuId> huIds, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId)
{
if (huIds.isEmpty()) {return;}
final I_M_Warehouse warehouse = warehousesRepo.getById(warehouseId);
if (!warehouse.isReceiveAsSourceHU())
{
return;
}
final boolean referencedInComponentOrVariant = productBOMDAO.isComponent(productId);
if (!referencedInComponentOrVariant)
{
return;
}
huIds.forEach(this::addSourceHuMarker);
}
/**
* Specifies which source HUs (products and warehouse) to retrieve in particular
*/
@lombok.Value
@lombok.Builder
@Immutable
public static class MatchingSourceHusQuery
{ | /**
* Query for HUs that have any of the given product IDs. Empty means that no HUs will be found.
*/
@Singular
ImmutableSet<ProductId> productIds;
@Singular
ImmutableSet<WarehouseId> warehouseIds;
public static MatchingSourceHusQuery fromHuId(final HuId huId)
{
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
final IHUStorage storage = storageFactory.getStorage(hu);
final ImmutableSet<ProductId> productIds = storage.getProductStorages().stream()
.filter(productStorage -> !productStorage.isEmpty())
.map(IProductStorage::getProductId)
.collect(ImmutableSet.toImmutableSet());
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseId(hu);
return new MatchingSourceHusQuery(productIds, ImmutableSet.of(warehouseId));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\SourceHUsService.java | 1 |
请完成以下Java代码 | public synchronized void send()
{
// Do nothing if there is nothing to send
if (syncConfirmations.isEmpty())
{
return;
}
final PutConfirmationToProcurementWebRequest syncConfirmationRequest = PutConfirmationToProcurementWebRequest.of(syncConfirmations);
senderToProcurementWebUI.send(syncConfirmationRequest);
syncConfirmations.clear();
}
/**
* Generates a {@link SyncConfirmation} instance to be send either directly after the next commit.
*/
public void confirm(final IConfirmableDTO syncModel, final String serverEventId)
{
if (syncModel.getSyncConfirmationId() <= 0) | {
return; // nothing to do
}
final SyncConfirmation syncConfirmation = SyncConfirmation.forConfirmId(syncModel.getSyncConfirmationId());
syncConfirmation.setDateConfirmed(SystemTime.asDate());
syncConfirmation.setServerEventId(serverEventId);
syncConfirmations.add(syncConfirmation);
if (autoSendAfterEachConfirm)
{
send();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\SyncConfirmationsSender.java | 1 |
请完成以下Java代码 | private static class PluginObjectTypeMarshaller extends DefaultAttributeMarshaller {
@Override
public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException {
if (attribute instanceof ObjectListAttributeDefinition) {
attribute = getValueType(attribute, ObjectListAttributeDefinition.class);
}
if (!(attribute instanceof ObjectTypeAttributeDefinition)) {
throw new XMLStreamException(
String.format("Attribute of class %s is expected, but %s received", "ObjectTypeAttributeDefinition", attribute.getClass().getSimpleName())
);
}
AttributeDefinition[] valueTypes;
valueTypes = CustomMarshaller.getValueTypes(attribute, ObjectTypeAttributeDefinition.class);
writer.writeStartElement(attribute.getXmlName());
for (AttributeDefinition valueType : valueTypes) {
valueType.marshallAsElement(resourceModel, marshallDefault, writer);
}
writer.writeEndElement();
}
@Override
public boolean isMarshallableAsElement() {
return true;
}
}
/**
* Marshall a list of objects.
*/
private static class ObjectListMarshaller extends AttributeMarshaller {
private ObjectListMarshaller() {}
@Override
public boolean isMarshallableAsElement() {
return true;
}
@Override
public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException {
assert attribute instanceof ObjectListAttributeDefinition; | ObjectListAttributeDefinition list = ((ObjectListAttributeDefinition) attribute);
ObjectTypeAttributeDefinition objectType = (ObjectTypeAttributeDefinition) CustomMarshaller.getValueType(list, ObjectListAttributeDefinition.class);
AttributeDefinition[] valueTypes = CustomMarshaller.getValueTypes(list, ObjectTypeAttributeDefinition.class);
if (resourceModel.hasDefined(attribute.getName())) {
writer.writeStartElement(attribute.getXmlName());
for (ModelNode element: resourceModel.get(attribute.getName()).asList()) {
writer.writeStartElement(objectType.getXmlName());
for (AttributeDefinition valueType : valueTypes) {
valueType.getMarshaller().marshallAsElement(valueType, element, false, writer);
}
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
public static final AttributeAsElementMarshaller ATTRIBUTE_AS_ELEMENT = new AttributeAsElementMarshaller();
public static final PluginObjectTypeMarshaller OBJECT_AS_ELEMENT = new PluginObjectTypeMarshaller();
public static final ObjectListMarshaller OBJECT_LIST = new ObjectListMarshaller();
public static final PropertiesAttributeMarshaller PROPERTIES_MARSHALLER = new PropertiesAttributeMarshaller();
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\util\CustomMarshaller.java | 1 |
请完成以下Java代码 | public class ProcessInstanceStartEventSubscriptionBuilderImpl implements ProcessInstanceStartEventSubscriptionBuilder {
protected final RuntimeServiceImpl runtimeService;
protected String processDefinitionKey;
protected String tenantId;
protected final Map<String, Object> correlationParameterValues = new HashMap<>();
protected boolean doNotUpdateToLatestVersionAutomatically;
public ProcessInstanceStartEventSubscriptionBuilderImpl(RuntimeServiceImpl runtimeService) {
this.runtimeService = runtimeService;
}
@Override
public ProcessInstanceStartEventSubscriptionBuilder processDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
return this;
}
@Override
public ProcessInstanceStartEventSubscriptionBuilder doNotUpdateToLatestVersionAutomatically() {
this.doNotUpdateToLatestVersionAutomatically = true;
return this;
}
@Override
public ProcessInstanceStartEventSubscriptionBuilder addCorrelationParameterValue(String parameterName, Object parameterValue) {
correlationParameterValues.put(parameterName, parameterValue);
return this;
}
@Override
public ProcessInstanceStartEventSubscriptionBuilder addCorrelationParameterValues(Map<String, Object> parameters) {
correlationParameterValues.putAll(parameters);
return this;
}
@Override
public ProcessInstanceStartEventSubscriptionBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public Map<String, Object> getCorrelationParameterValues() {
return correlationParameterValues;
} | public boolean isDoNotUpdateToLatestVersionAutomatically() {
return doNotUpdateToLatestVersionAutomatically;
}
public String getTenantId() {
return tenantId;
}
@Override
public EventSubscription subscribe() {
checkValidInformation();
return runtimeService.registerProcessInstanceStartEventSubscription(this);
}
protected void checkValidInformation() {
if (StringUtils.isEmpty(processDefinitionKey)) {
throw new FlowableIllegalArgumentException("The process definition must be provided using the key for the subscription to be registered.");
}
if (correlationParameterValues.isEmpty()) {
throw new FlowableIllegalArgumentException(
"At least one correlation parameter value must be provided for a dynamic process start event subscription, "
+ "otherwise the process would get started on all events, regardless their correlation parameter values.");
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceStartEventSubscriptionBuilderImpl.java | 1 |
请完成以下Java代码 | public RestartProcessInstanceBuilder initialSetOfVariables() {
this.initialVariables = true;
return this;
}
public boolean isInitialVariables() {
return initialVariables;
}
@Override
public RestartProcessInstanceBuilder skipCustomListeners() {
this.skipCustomListeners = true;
return this;
}
@Override
public RestartProcessInstanceBuilder skipIoMappings() {
this.skipIoMappings = true;
return this;
}
public boolean isSkipCustomListeners() { | return skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
@Override
public RestartProcessInstanceBuilder withoutBusinessKey() {
withoutBusinessKey = true;
return this;
}
public boolean isWithoutBusinessKey() {
return withoutBusinessKey;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstanceBuilderImpl.java | 1 |
请完成以下Java代码 | private String getSingleCurrencySymbolOrNull()
{
final boolean singleCurrencySymbol = currencySymbols.size() == 1;
return singleCurrencySymbol ? currencySymbols.iterator().next() : null;
}
private ITranslatableString toTranslatableString(final BigDecimal amt)
{
final TranslatableStringBuilder builder = TranslatableStrings.builder();
builder.append(amt, DisplayType.Amount);
final String singleCurrencySymbol = getSingleCurrencySymbolOrNull();
if (singleCurrencySymbol != null)
{
builder.append(" ").append(singleCurrencySymbol);
}
return builder.build();
}
/**
* Builder
*/
public static class Builder
{
private BigDecimal totalNetAmtApproved = BigDecimal.ZERO;
private BigDecimal huNetAmtApproved = BigDecimal.ZERO;
private BigDecimal cuNetAmtApproved = BigDecimal.ZERO;
private BigDecimal totalNetAmtNotApproved = BigDecimal.ZERO;
private BigDecimal huNetAmtNotApproved = BigDecimal.ZERO;
private BigDecimal cuNetAmtNotApproved = BigDecimal.ZERO;
private int countTotalToRecompute = 0;
private final ImmutableSet.Builder<String> currencySymbols = ImmutableSet.builder();
private Builder()
{
}
public InvoiceCandidatesAmtSelectionSummary build()
{
return new InvoiceCandidatesAmtSelectionSummary(this);
}
public Builder addTotalNetAmt(final BigDecimal amtToAdd, final boolean approved, final boolean isPackingMaterial)
{
if (approved)
{
totalNetAmtApproved = totalNetAmtApproved.add(amtToAdd);
if (isPackingMaterial)
{
huNetAmtApproved = huNetAmtApproved.add(amtToAdd);
}
else
{
cuNetAmtApproved = cuNetAmtApproved.add(amtToAdd);
}
}
else
{
totalNetAmtNotApproved = totalNetAmtNotApproved.add(amtToAdd);
if (isPackingMaterial)
{
huNetAmtNotApproved = huNetAmtNotApproved.add(amtToAdd); | }
else
{
cuNetAmtNotApproved = cuNetAmtNotApproved.add(amtToAdd);
}
}
return this;
}
@SuppressWarnings("UnusedReturnValue")
public Builder addCurrencySymbol(final String currencySymbol)
{
if (Check.isEmpty(currencySymbol, true))
{
// NOTE: prevent adding null values because ImmutableSet.Builder will fail in this case
currencySymbols.add("?");
}
else
{
currencySymbols.add(currencySymbol);
}
return this;
}
public void addCountToRecompute(final int countToRecomputeToAdd)
{
Check.assume(countToRecomputeToAdd > 0, "countToRecomputeToAdd > 0");
countTotalToRecompute += countToRecomputeToAdd;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidatesAmtSelectionSummary.java | 1 |
请完成以下Java代码 | protected ObjectNode mapDependencyGroup(DependencyGroup group) {
ObjectNode result = nodeFactory.objectNode();
result.put("name", group.getName());
if ((group instanceof Describable) && ((Describable) group).getDescription() != null) {
result.put("description", ((Describable) group).getDescription());
}
ArrayNode items = nodeFactory.arrayNode();
group.getContent().forEach((it) -> {
JsonNode dependency = mapDependency(it);
if (dependency != null) {
items.add(dependency);
}
});
result.set("values", items);
return result;
}
protected ObjectNode mapDependency(Dependency dependency) {
if (dependency.getCompatibilityRange() == null) {
// only map the dependency if no compatibilityRange is set
return mapValue(dependency);
}
return null;
}
protected ObjectNode mapType(Type type) {
ObjectNode result = mapValue(type);
result.put("action", type.getAction());
ObjectNode tags = nodeFactory.objectNode();
type.getTags().forEach(tags::put);
result.set("tags", tags);
return result;
} | private ObjectNode mapVersionMetadata(MetadataElement value) {
ObjectNode result = nodeFactory.objectNode();
result.put("id", formatVersion(value.getId()));
result.put("name", value.getName());
return result;
}
protected String formatVersion(String versionId) {
Version version = VersionParser.DEFAULT.safeParse(versionId);
return (version != null) ? version.format(Format.V1).toString() : versionId;
}
protected ObjectNode mapValue(MetadataElement value) {
ObjectNode result = nodeFactory.objectNode();
result.put("id", value.getId());
result.put("name", value.getName());
if ((value instanceof Describable) && ((Describable) value).getDescription() != null) {
result.put("description", ((Describable) value).getDescription());
}
return result;
}
} | repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\mapper\InitializrMetadataV2JsonMapper.java | 1 |
请完成以下Java代码 | public class Authentication {
@XmlElement(required = true)
protected String delisId;
@XmlElement(required = true)
protected String authToken;
@XmlElement(required = true)
protected String messageLanguage;
/**
* Gets the value of the delisId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDelisId() {
return delisId;
}
/**
* Sets the value of the delisId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDelisId(String value) {
this.delisId = value;
}
/**
* Gets the value of the authToken property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthToken() {
return authToken;
}
/**
* Sets the value of the authToken property.
* | * @param value
* allowed object is
* {@link String }
*
*/
public void setAuthToken(String value) {
this.authToken = value;
}
/**
* Gets the value of the messageLanguage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageLanguage() {
return messageLanguage;
}
/**
* Sets the value of the messageLanguage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageLanguage(String value) {
this.messageLanguage = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\authentication\v2_0\types\Authentication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AppDeploymentBuilder addZipInputStream(ZipInputStream zipInputStream) {
try {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
if (!entry.isDirectory()) {
String entryName = entry.getName();
byte[] bytes = IoUtil.readInputStream(zipInputStream, entryName);
AppResourceEntity resource = resourceEntityManager.create();
resource.setName(entryName);
resource.setBytes(bytes);
deployment.addResource(resource);
}
entry = zipInputStream.getNextEntry();
}
} catch (Exception e) {
throw new FlowableException("problem reading zip input stream", e);
}
return this;
}
@Override
public AppDeploymentBuilder name(String name) {
deployment.setName(name);
return this;
}
@Override
public AppDeploymentBuilder category(String category) {
deployment.setCategory(category);
return this;
}
@Override
public AppDeploymentBuilder key(String key) {
deployment.setKey(key);
return this;
}
@Override
public AppDeploymentBuilder disableSchemaValidation() {
this.isXsdValidationEnabled = false;
return this;
}
@Override | public AppDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public AppDeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
@Override
public AppDeployment deploy() {
return repositoryService.deploy(this);
}
public AppDeploymentEntity getDeployment() {
return deployment;
}
public boolean isXsdValidationEnabled() {
return isXsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public Object authenticate(Properties credentials) throws AuthenticationFailedException {
String username = credentials.getProperty(GeodeConstants.USERNAME);
String password = credentials.getProperty(GeodeConstants.PASSWORD);
if (!String.valueOf(username).equals(password)) {
throw new AuthenticationFailedException(String.format("User [%s] could not be authenticated", username));
}
return User.create(username);
}
public static class User implements Comparable<User>, Principal, Serializable {
public static User create(String name) {
return new User(name);
}
private final String name;
public User(String name) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Username is required");
}
this.name = name;
}
public String getName() {
return this.name;
}
@Override
public int compareTo(User user) {
return this.getName().compareTo(user.getName());
}
@Override
public boolean equals(Object obj) { | if (this == obj) {
return true;
}
if (!(obj instanceof User)) {
return false;
}
User that = (User) obj;
return this.getName().equals(that.getName());
}
@Override
public int hashCode() {
int hashValue = 17;
hashValue = 37 * hashValue + getName().hashCode();
return hashValue;
}
@Override
public String toString() {
return getName();
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\security\TestSecurityManager.java | 1 |
请完成以下Java代码 | public Object getParameter() {
return parameter;
}
public void setParameter(Object parameter) {
this.parameter = parameter;
}
public String getStatement() {
return statement;
}
public void setStatement(String statement) {
this.statement = statement;
}
public String toString() {
return operationType + " "+ statement +" " +parameter;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((parameter == null) ? 0 : parameter.hashCode());
result = prime * result + ((statement == null) ? 0 : statement.hashCode());
return result;
}
@Override | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DbBulkOperation other = (DbBulkOperation) obj;
if (parameter == null) {
if (other.parameter != null)
return false;
} else if (!parameter.equals(other.parameter))
return false;
if (statement == null) {
if (other.statement != null)
return false;
} else if (!statement.equals(other.statement))
return false;
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\operation\DbBulkOperation.java | 1 |
请完成以下Java代码 | public static LookupValue retrieveLookupValue(
@NonNull final ResultSet rs,
final boolean isNumericKey,
final boolean isTranslatable,
@Nullable final String adLanguage) throws SQLException
{
final Array sqlArray = rs.getArray(1);
return toLookupValue(sqlArray, isNumericKey, isTranslatable, adLanguage);
}
@Nullable
private static LookupValue toLookupValue(
@Nullable final Array sqlArray,
final boolean isNumericKey,
final boolean isTranslatable,
@Nullable final String adLanguage) throws SQLException
{
if (sqlArray == null)
{
return null;
}
final String[] array = (String[])sqlArray.getArray();
if (array == null || array.length == 0)
{
return null;
}
final String idString = StringUtils.trimBlankToNull(array[0]);
if (idString == null)
{
return null;
}
final String displayName = StringUtils.trimBlankToOptional(array[1]).orElse("");
final String description = StringUtils.trimBlankToNull(array[2]);
final boolean active = StringUtils.toBoolean(array[3]);
final ITranslatableString displayNameTrl;
final ITranslatableString descriptionTrl;
if (isTranslatable)
{
displayNameTrl = TranslatableStrings.singleLanguage(adLanguage, displayName);
descriptionTrl = TranslatableStrings.singleLanguage(adLanguage, description);
}
else
{
displayNameTrl = TranslatableStrings.anyLanguage(displayName);
descriptionTrl = TranslatableStrings.anyLanguage(description);
}
if (isNumericKey)
{
final int idInt = Integer.parseInt(idString);
return LookupValue.IntegerLookupValue.builder()
.id(idInt)
.displayName(displayNameTrl) | .description(descriptionTrl)
.active(active)
.build();
}
else
{
final ValueNamePairValidationInformation validationInformation = StringUtils.trimBlankToOptional(array[4])
.map(questionMsg -> ValueNamePairValidationInformation.builder()
.question(AdMessageKey.of(questionMsg))
.build())
.orElse(null);
return LookupValue.StringLookupValue.builder()
.id(idString)
.displayName(displayNameTrl)
.description(descriptionTrl)
.active(active)
.validationInformation(validationInformation)
.build();
}
}
@Nullable
public static LookupValue.IntegerLookupValue retrieveIntegerLookupValue(
@NonNull final ResultSet rs,
@NonNull final String columnName,
@Nullable final String adLanguage) throws SQLException
{
final Array sqlArray = rs.getArray(columnName);
return (LookupValue.IntegerLookupValue)toLookupValue(sqlArray, true, true, adLanguage);
}
@Nullable
public static LookupValue.StringLookupValue retrieveStringLookupValue(
@NonNull final ResultSet rs,
@NonNull final String columnName,
@Nullable final String adLanguage) throws SQLException
{
final Array sqlArray = rs.getArray(columnName);
return (LookupValue.StringLookupValue)toLookupValue(sqlArray, false, true, adLanguage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlForFetchingLookupById.java | 1 |
请完成以下Java代码 | public PageData<AssetProfile> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAssetProfiles(TenantId.fromUUID(tenantId), pageLink);
}
@Override
public AssetProfileId getExternalIdByInternal(AssetProfileId internalId) {
return Optional.ofNullable(assetProfileRepository.getExternalIdById(internalId.getId()))
.map(AssetProfileId::new).orElse(null);
}
@Override
public AssetProfile findDefaultEntityByTenantId(UUID tenantId) {
return findDefaultAssetProfile(TenantId.fromUUID(tenantId));
}
@Override
public List<AssetProfileInfo> findByTenantAndImageLink(TenantId tenantId, String imageLink, int limit) {
return assetProfileRepository.findByTenantAndImageLink(tenantId.getId(), imageLink, PageRequest.of(0, limit));
}
@Override
public List<AssetProfileInfo> findByImageLink(String imageLink, int limit) {
return assetProfileRepository.findByImageLink(imageLink, PageRequest.of(0, limit));
} | @Override
public PageData<AssetProfile> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<AssetProfileFields> findNextBatch(UUID id, int batchSize) {
return assetProfileRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET_PROFILE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\asset\JpaAssetProfileDao.java | 1 |
请完成以下Java代码 | public void setModulo(double modulo) {
this.modulo = modulo;
}
public double getModuloAlphabetic() {
return moduloAlphabetic;
}
public void setModuloAlphabetic(double moduloAlphabetic) {
this.moduloAlphabetic = moduloAlphabetic;
}
public double getPowerOf() {
return powerOf;
}
public void setPowerOf(double powerOf) {
this.powerOf = powerOf;
}
public double getBrackets() {
return brackets;
}
public void setBrackets(double brackets) {
this.brackets = brackets;
} | @Override
public String toString() {
return "SpelArithmetic{" +
"add=" + add +
", addString='" + addString + '\'' +
", subtract=" + subtract +
", multiply=" + multiply +
", divide=" + divide +
", divideAlphabetic=" + divideAlphabetic +
", modulo=" + modulo +
", moduloAlphabetic=" + moduloAlphabetic +
", powerOf=" + powerOf +
", brackets=" + brackets +
'}';
}
} | repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelArithmetic.java | 1 |
请完成以下Java代码 | public void initData() {
Country spain = new Country();
spain.setName("Spain");
spain.setCapital("Madrid");
spain.setCurrency(Currency.EUR);
spain.setPopulation(46704314);
countries.put(spain.getName(), spain);
Country poland = new Country();
poland.setName("Poland");
poland.setCapital("Warsaw");
poland.setCurrency(Currency.PLN);
poland.setPopulation(38186860); | countries.put(poland.getName(), poland);
Country uk = new Country();
uk.setName("United Kingdom");
uk.setCapital("London");
uk.setCurrency(Currency.GBP);
uk.setPopulation(63705000);
countries.put(uk.getName(), uk);
}
public Country findCountry(String name) {
Assert.notNull(name, "The country's name must not be null");
return countries.get(name);
}
} | repos\tutorials-master\spring-web-modules\spring-soap\src\main\java\com\baeldung\springsoap\CountryRepository.java | 1 |
请完成以下Spring Boot application配置 | logging.level.org.springframework=INFO
logging.level.com.mkyong=INFO
logging.level.com.zaxxer=ERROR
logging.level.root=ERROR
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5
# logging.pattern.console=%-5level %logger{36} - %msg%n
## MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=mkyong
spring.datasource.password=password
# hibernate_sequence' do | esn't exist
# spring.jpa.hibernate.use-new-id-generator-mappings=false
# drop n create table again, good for testing, comment this in production
spring.jpa.hibernate.ddl-auto=create-drop | repos\spring-boot-master\spring-data-jpa-mysql\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName; | }
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\repositoryvsdaopattern\User.java | 2 |
请完成以下Java代码 | public void setStorageAttributesKey (java.lang.String StorageAttributesKey)
{
set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey);
}
/** Get StorageAttributesKey (technical).
@return StorageAttributesKey (technical) */
@Override
public java.lang.String getStorageAttributesKey ()
{
return (java.lang.String)get_Value(COLUMNNAME_StorageAttributesKey);
}
/** Set Transfert Time.
@param TransfertTime Transfert Time */
@Override
public void setTransfertTime (java.math.BigDecimal TransfertTime)
{
set_Value (COLUMNNAME_TransfertTime, TransfertTime);
}
/** Get Transfert Time.
@return Transfert Time */
@Override
public java.math.BigDecimal getTransfertTime ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TransfertTime);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Working Time.
@param WorkingTime
Workflow Simulation Execution Time
*/
@Override
public void setWorkingTime (java.math.BigDecimal WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
/** Get Working Time.
@return Workflow Simulation Execution Time
*/
@Override
public java.math.BigDecimal getWorkingTime ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WorkingTime);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Yield %.
@param Yield
The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent
*/
@Override
public void setYield (int Yield)
{
set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield));
} | /** Get Yield %.
@return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent
*/
@Override
public int getYield ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Yield);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID)
{
if (C_Manufacturing_Aggregation_ID < 1)
set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null);
else
set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID);
}
@Override
public int getC_Manufacturing_Aggregation_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\product\model\X_M_Product_PlanningSchema.java | 1 |
请完成以下Java代码 | public CompletableFuture<Void> shipUnconfirmedOrder() {
String orderId = UUID.randomUUID()
.toString();
return commandGateway.send(new CreateOrderCommand(orderId))
.thenCompose(result -> commandGateway.send(new AddProductCommand(orderId, "Deluxe Chair")))
// This throws an exception, as an Order cannot be shipped if it has not been confirmed yet.
.thenCompose(result -> commandGateway.send(new ShipOrderCommand(orderId)));
}
@PostMapping("/order")
public CompletableFuture<String> createOrder() {
return createOrder(UUID.randomUUID()
.toString());
}
@PostMapping("/order/{order-id}")
public CompletableFuture<String> createOrder(@PathVariable("order-id") String orderId) {
return commandGateway.send(new CreateOrderCommand(orderId));
}
@PostMapping("/order/{order-id}/product/{product-id}")
public CompletableFuture<Void> addProduct(@PathVariable("order-id") String orderId, @PathVariable("product-id") String productId) {
return commandGateway.send(new AddProductCommand(orderId, productId));
}
@PostMapping("/order/{order-id}/product/{product-id}/increment")
public CompletableFuture<Void> incrementProduct(@PathVariable("order-id") String orderId, @PathVariable("product-id") String productId) {
return commandGateway.send(new IncrementProductCountCommand(orderId, productId));
}
@PostMapping("/order/{order-id}/product/{product-id}/decrement")
public CompletableFuture<Void> decrementProduct(@PathVariable("order-id") String orderId, @PathVariable("product-id") String productId) { | return commandGateway.send(new DecrementProductCountCommand(orderId, productId));
}
@PostMapping("/order/{order-id}/confirm")
public CompletableFuture<Void> confirmOrder(@PathVariable("order-id") String orderId) {
return commandGateway.send(new ConfirmOrderCommand(orderId));
}
@PostMapping("/order/{order-id}/ship")
public CompletableFuture<Void> shipOrder(@PathVariable("order-id") String orderId) {
return commandGateway.send(new ShipOrderCommand(orderId));
}
@GetMapping("/all-orders")
public CompletableFuture<List<OrderResponse>> findAllOrders() {
return orderQueryService.findAllOrders();
}
@GetMapping(path = "/all-orders-streaming", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<OrderResponse> allOrdersStreaming() {
return orderQueryService.allOrdersStreaming();
}
@GetMapping("/total-shipped/{product-id}")
public Integer totalShipped(@PathVariable("product-id") String productId) {
return orderQueryService.totalShipped(productId);
}
@GetMapping(path = "/order-updates/{order-id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<OrderResponse> orderUpdates(@PathVariable("order-id") String orderId) {
return orderQueryService.orderUpdates(orderId);
}
} | repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\gui\OrderRestEndpoint.java | 1 |
请完成以下Java代码 | public void updateBPartnerReminderDate(final I_R_Request request)
{
final Timestamp reminderDate = request.getReminderDate();
if (reminderDate == null)
{
return;
}
final UserId adUserId = UserId.ofRepoIdOrNull(request.getSalesRep_ID());
if (adUserId == null || !adUserId.isRegularUser())
{
return;
}
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(request.getC_BPartner_ID());
if (bpartnerId == null)
{
// nothing to do
return;
}
final I_C_BPartner bpartner = bpartnerDAO.getByIdInTrx(bpartnerId);
if (bpartner == null)
{
// nothing to do
return; | }
if (bpartner.getSalesRepIntern_ID() == adUserId.getRepoId())
{
bpartner.setReminderDateIntern(reminderDate);
}
else if (bpartner.getSalesRep_ID() == adUserId.getRepoId())
{
bpartner.setReminderDateExtern(reminderDate);
}
else
{
// nothing to do
return;
}
bpartnerDAO.save(bpartner);
documentsCollection.invalidateDocumentByRecordId(I_C_BPartner.Table_Name, bpartner.getC_BPartner_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\crm\interceptor\R_Request.java | 1 |
请完成以下Java代码 | public class JsonObjectVariableType extends VariableType {
private static final Logger logger = LoggerFactory.getLogger(JsonObjectVariableType.class);
private ObjectMapper objectMapper;
public JsonObjectVariableType(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void validate(Object var, List<ActivitiException> errors) {
//we can consider var json so long as it can be stored as json
//this doesn't guarantee a string body to be valid json as jackson will wrap a string to make it valid
//also doesn't guarantee it will be persisted as json | //could be a pojo and then could be persisted as serializable if user sets serializePOJOsInVariablesToJson to false - see JsonType.java
if (!objectMapper.canSerialize(var.getClass())) {
String message = var.getClass() + " is not serializable as json";
errors.add(new ActivitiException(message));
logger.error(message);
}
if (!objectMapper.canDeserialize(objectMapper.constructType(var.getClass()))) {
String message = var.getClass() + " is not deserializable as json";
errors.add(new ActivitiException(message));
logger.error(message);
}
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\variable\types\JsonObjectVariableType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getSubCategEntityID() {
return subCategEntityID;
}
public void setSubCategEntityID(String subCategEntityID) {
this.subCategEntityID = subCategEntityID;
}
public String getBrandEntityID() {
return brandEntityID;
}
public void setBrandEntityID(String brandEntityID) {
this.brandEntityID = brandEntityID;
}
public Integer getProdState() {
return prodState;
}
public void setProdState(Integer prodState) {
this.prodState = prodState;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content; | }
public String getCompanyEntityID() {
return companyEntityID;
}
public void setCompanyEntityID(String companyEntityID) {
this.companyEntityID = companyEntityID;
}
@Override
public String toString() {
return "ProdInsertReq{" +
"id='" + id + '\'' +
", prodName='" + prodName + '\'' +
", marketPrice='" + marketPrice + '\'' +
", shopPrice='" + shopPrice + '\'' +
", stock=" + stock +
", sales=" + sales +
", weight='" + weight + '\'' +
", topCateEntityID='" + topCateEntityID + '\'' +
", subCategEntityID='" + subCategEntityID + '\'' +
", brandEntityID='" + brandEntityID + '\'' +
", prodState=" + prodState +
", content='" + content + '\'' +
", companyEntityID='" + companyEntityID + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\ProdInsertReq.java | 2 |
请完成以下Java代码 | public String toString() {
StringBuilder sb = new StringBuilder();
if (hostApplicationId == null) {
sb.append(getNamespace()).append("/").append(getGroupId()).append("/").append(getType()).append("/")
.append(getEdgeNodeId());
if (getDeviceId() != null) {
sb.append("/").append(getDeviceId());
}
} else {
sb.append(getNamespace()).append("/").append(getType()).append("/").append(hostApplicationId);
}
return sb.toString();
}
/**
* @param type the type to check
* @return true if this topic's type matches the passes in type, false otherwise
*/
public boolean isType(SparkplugMessageType type) {
return this.type != null && this.type.equals(type);
}
public boolean isNode() {
return this.deviceId == null; | }
public String getNodeDeviceName() {
return isNode() ? edgeNodeId : deviceId;
}
public static boolean isValidIdElementToUTF8(String deviceIdElement) {
if (deviceIdElement == null) {
return false;
}
String regex = "^(?!.*//)[^+#]*$";
return deviceIdElement.matches(regex);
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugTopic.java | 1 |
请完成以下Java代码 | class JWTAuthenticationProvider implements AuthenticationProvider {
private final JWTDeserializer jwtDeserializer;
JWTAuthenticationProvider(JWTDeserializer jwtDeserializer) {
this.jwtDeserializer = jwtDeserializer;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return of(authentication).map(JWTAuthenticationFilter.JWT.class::cast)
.map(JWTAuthenticationFilter.JWT::getPrincipal)
.map(Object::toString)
.map(token -> new JWTAuthentication(token, jwtDeserializer.jwtPayloadFromJWT(token)))
.orElseThrow(IllegalStateException::new);
}
@Override
public boolean supports(Class<?> authentication) {
return JWTAuthenticationFilter.JWT.class.isAssignableFrom(authentication);
}
@SuppressWarnings("java:S2160")
private static class JWTAuthentication extends AbstractAuthenticationToken {
private final JWTPayload jwtPayload;
private final String token;
private JWTAuthentication(String token, JWTPayload jwtPayload) {
super(singleton(new SimpleGrantedAuthority("USER"))); | super.setAuthenticated(true);
this.jwtPayload = jwtPayload;
this.token = token;
}
@Override
public Object getPrincipal() {
return jwtPayload;
}
@Override
public Object getCredentials() {
return token;
}
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\security\JWTAuthenticationProvider.java | 1 |
请完成以下Java代码 | public int size()
{
if (Check.isEmpty(sqlCount, true))
{
throw new IllegalStateException("Counting is not supported");
}
if (rowsCount == null)
{
logger.info("SQL: {}", sqlCount);
logger.info("SQL Params: {}", sqlParams);
rowsCount = DB.getSQLValueEx(Trx.TRXNAME_None, sqlCount, sqlParams);
logger.info("Rows Count: {}" + rowsCount);
}
return rowsCount;
}
public String getSqlSelect()
{
return sqlSelect; | }
public List<Object> getSqlParams()
{
if (sqlParams == null)
{
return Collections.emptyList();
}
return sqlParams;
}
public String getSqlWhereClause()
{
return sqlWhereClause;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExportDataSource.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.