instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) { this.authorities = authorities; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCnname() { return cnname; } public void setCnname(String cnname) { this.cnname = cnname; } public String getUsername() { return username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; }
public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public String getRePassword() { return rePassword; } public void setRePassword(String rePassword) { this.rePassword = rePassword; } public String getHistoryPassword() { return historyPassword; } public void setHistoryPassword(String historyPassword) { this.historyPassword = historyPassword; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } @Override public String toString() { return "User{" + "id=" + id + ", cnname=" + cnname + ", username=" + username + ", password=" + password + ", email=" + email + ", telephone=" + telephone + ", mobilePhone=" + mobilePhone + '}'; } }
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\bean\User.java
1
请完成以下Java代码
protected List<ClientRequestInterceptor> getInterceptors() { return interceptors; } protected int getMaxTasks() { return maxTasks; } protected Long getAsyncResponseTimeout() { return asyncResponseTimeout; } protected long getLockDuration() { return lockDuration; } protected boolean isAutoFetchingEnabled() { return isAutoFetchingEnabled; } protected BackoffStrategy getBackoffStrategy() { return backoffStrategy; } public String getDefaultSerializationFormat() { return defaultSerializationFormat; } public String getDateFormat() { return dateFormat; }
public ObjectMapper getObjectMapper() { return objectMapper; } public ValueMappers getValueMappers() { return valueMappers; } public TypedValues getTypedValues() { return typedValues; } public EngineClient getEngineClient() { return engineClient; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String delete(@PathVariable(value = "id")int id) { boolean b = employeeService.removeById( id ); if(b) { return "delete success"; }else { return "delete fail"; } } @PostMapping(value = "") public String postEmployee(@RequestParam(value = "lastName", required = true) String lastName, @RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "dId", required = true) int dId) { Employee employee = new Employee(); employee.setLastName( lastName );
employee.setEmail( email ); employee.setGender( gender ); employee.setDId( dId ); boolean b = employeeService.save( employee ); if(b) { return "sava success"; }else { return "sava fail"; } } }
repos\SpringBootLearning-master (1)\springboot-cache\src\main\java\com\gf\controller\EmployeeController.java
2
请在Spring Boot框架中完成以下Java代码
public Result semaphore(String arg) { Person person = new Person(); person.setAge(18); person.setId(2L); person.setName("名称semaphore"); person.setAddress("地址semaphore"); logger.info(JSON.toJSONString(person)); return Result.success(person); } @Override public Result thread(String arg) { // 资源的唯一标识 String resourceName = "testSentinel"; int time = random.nextInt(700); Entry entry = null; String retVal; try { entry = SphU.entry(resourceName, EntryType.IN); Thread.sleep(time); if (time > 690) {
throw new RuntimeException("耗时太长啦"); } retVal = "passed"; } catch (BlockException e) { // logger.error("请求拒绝 {}", e.getMessage(), e); retVal = "blocked"; } catch (Exception e) { // logger.error("异常 {}", e.getMessage(), e); // 异常数统计埋点 Tracer.trace(e); throw new RuntimeException(e); } finally { if (entry != null) { entry.exit(); } } return Result.success(retVal + "::" + time); } }
repos\spring-boot-student-master\spring-boot-student-sentinel\src\main\java\com\xiaolyuh\service\impl\PersonServiceImpl.java
2
请完成以下Java代码
public class BestellungSubstitution { @XmlElement(name = "Substitutionsgrund", required = true) @XmlSchemaType(name = "string") protected Substitutionsgrund substitutionsgrund; @XmlElement(name = "Grund", required = true) @XmlSchemaType(name = "string") protected BestellungDefektgrund grund; @XmlElement(name = "LieferPzn") protected long lieferPzn; /** * Gets the value of the substitutionsgrund property. * * @return * possible object is * {@link Substitutionsgrund } * */ public Substitutionsgrund getSubstitutionsgrund() { return substitutionsgrund; } /** * Sets the value of the substitutionsgrund property. * * @param value * allowed object is * {@link Substitutionsgrund } * */ public void setSubstitutionsgrund(Substitutionsgrund value) { this.substitutionsgrund = value; } /** * Gets the value of the grund property. * * @return * possible object is * {@link BestellungDefektgrund } * */
public BestellungDefektgrund getGrund() { return grund; } /** * Sets the value of the grund property. * * @param value * allowed object is * {@link BestellungDefektgrund } * */ public void setGrund(BestellungDefektgrund value) { this.grund = value; } /** * Gets the value of the lieferPzn property. * */ public long getLieferPzn() { return lieferPzn; } /** * Sets the value of the lieferPzn property. * */ public void setLieferPzn(long value) { this.lieferPzn = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungSubstitution.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Task.class, BPMN_ELEMENT_TASK) .namespaceUri(BPMN20_NS) .extendsType(Activity.class) .instanceProvider(new ModelTypeInstanceProvider<Task>() { public Task newInstance(ModelTypeInstanceContext instanceContext) { return new TaskImpl(instanceContext); } }); /** camunda extensions */ camundaAsyncAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_ASYNC) .namespace(CAMUNDA_NS) .defaultValue(false) .build(); typeBuilder.build(); } public TaskImpl(ModelTypeInstanceContext context) { super(context); } @SuppressWarnings("rawtypes") public AbstractTaskBuilder builder() { throw new ModelTypeException("No builder implemented."); }
/** camunda extensions */ /** * @deprecated use isCamundaAsyncBefore() instead. */ @Deprecated public boolean isCamundaAsync() { return camundaAsyncAttribute.getValue(this); } /** * @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead. */ @Deprecated public void setCamundaAsync(boolean isCamundaAsync) { camundaAsyncAttribute.setValue(this, isCamundaAsync); } public BpmnShape getDiagramElement() { return (BpmnShape) super.getDiagramElement(); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\TaskImpl.java
1
请完成以下Java代码
public void setUserID (java.lang.String UserID) { set_Value (COLUMNNAME_UserID, UserID); } /** Get Nutzerkennung. @return Nutzerkennung */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); } /** * Version AD_Reference_ID=540904 * Reference name: MSV3_Version */ public static final int VERSION_AD_Reference_ID=540904; /** 1 = 1 */ public static final String VERSION_1 = "1"; /** 2 = 2 */ public static final String VERSION_2 = "2"; /** Set Version. @param Version
Version of the table definition */ @Override public void setVersion (java.lang.String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Vendor_Config.java
1
请完成以下Java代码
public void setDefaultCtxProvider(final IRecordTextProvider defaultCtxProvider) { Check.assumeNotNull(defaultCtxProvider, "defaultCtxProvider not null"); this.defaultCtxProvider = defaultCtxProvider; } @Override public Optional<String> getTextMessageIfApplies(final ITableRecordReference referencedRecord) { // take the providers one by one and see if any of them applies to the given referenced record for (final IRecordTextProvider ctxProvider : ctxProviders) { final Optional<String> textMessage = ctxProvider.getTextMessageIfApplies(referencedRecord); if (textMessage != null && textMessage.isPresent()) {
return textMessage; } } // Fallback to default provider final Optional<String> textMessage = defaultCtxProvider.getTextMessageIfApplies(referencedRecord); // guard against development issues (usually the text message shall never be null) if (textMessage == null) { new AdempiereException("Possible development issue. " + defaultCtxProvider + " returned null for " + referencedRecord) .throwIfDeveloperModeOrLogWarningElse(logger); return Optional.absent(); } return textMessage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\spi\impl\CompositeRecordTextProvider.java
1
请完成以下Java代码
protected SparkplugDeviceSessionContext newDeviceSessionCtx(GetOrCreateDeviceFromGatewayResponse msg) { return new SparkplugDeviceSessionContext(this, msg.getDeviceInfo(), msg.getDeviceProfile(), mqttQoSMap, transportService); } protected void sendToDeviceRpcRequest(MqttMessage payload, TransportProtos.ToDeviceRpcRequestMsg rpcRequest, TransportProtos.SessionInfoProto sessionInfo) { parent.sendToDeviceRpcRequest(payload, rpcRequest, sessionInfo); } protected void sendErrorRpcResponse(TransportProtos.SessionInfoProto sessionInfo, int requestId, ThingsboardErrorCode result, String errorMsg) { parent.sendErrorRpcResponse(sessionInfo, requestId, result, errorMsg); } /** * Subscribe: spBv1.0/G1/DDATA/E1 * Subscribe: spBv1.0/G1/DDATA/E1/# * Subscribe: spBv1.0/G1/DDATA/E1/+ * Subscribe: spBv1.0/G1/DDATA/E1/D1 * Subscribe: spBv1.0/G1/DDATA/E1/D1/# * Subscribe: spBv1.0/G1/DDATA/E1/D1/+
* Parses a Sparkplug MQTT message topic string and returns a {@link SparkplugTopic} instance. * @param topic a topic UTF-8 * @return a {@link SparkplugTopic} instance * @throws ThingsboardException if an error occurs while parsing */ public boolean validateTopicDataSubscribe(String topic) throws ThingsboardException { String[] splitTopic = topic.split(TOPIC_SPLIT_REGEXP); if (splitTopic.length >= 4 && splitTopic.length <= 5 && splitTopic[0].equals(this.sparkplugTopicNode.getNamespace()) && splitTopic[1].equals(this.sparkplugTopicNode.getGroupId()) && splitTopic[3].equals(this.sparkplugTopicNode.getEdgeNodeId())) { SparkplugMessageType messageType = parseMessageType(splitTopic[2]); return messageType.isData(); } return false; } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\session\SparkplugNodeSessionHandler.java
1
请完成以下Java代码
public class SpinLock { private static final Unsafe unsafe; static { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); unsafe = (Unsafe) f.get(null); } catch(NoSuchFieldException | IllegalAccessException ex) { throw new RuntimeException(ex); } } private final long addr; public SpinLock(long addr) { this.addr = addr; }
public boolean tryLock(long maxWait) { long deadline = System.currentTimeMillis() + maxWait; while(System.currentTimeMillis() < deadline ) { if ( unsafe.compareAndSwapInt(null,addr,0,1)) { return true; } } return false; } public void unlock() { unsafe.putInt(addr,0); } }
repos\tutorials-master\core-java-modules\core-java-sun\src\main\java\com\baeldung\sharedmem\SpinLock.java
1
请完成以下Java代码
public class blink extends MultiPartElement implements Printable { /** * */ private static final long serialVersionUID = 1262496922875046287L; /** Private initialization routine. */ { setElementType("blink"); setCase(LOWERCASE); setAttributeQuote(true); } /** Basic constructor. */ public blink() { } /** Basic constructor. @param element Adds an Element to the element. */ public blink(Element element) { addElement(element); } /** Basic constructor. @param element Adds an Element to the element. */ public blink(String element) { addElement(element); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element.
@param hashcode name of element for hash table @param element Adds an Element to the element. */ public blink addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public blink addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public blink addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public blink addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public blink removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\blink.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_B_TopicCategory[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Topic Category. @param B_TopicCategory_ID Auction Topic Category */ public void setB_TopicCategory_ID (int B_TopicCategory_ID) { if (B_TopicCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_B_TopicCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_B_TopicCategory_ID, Integer.valueOf(B_TopicCategory_ID)); } /** Get Topic Category. @return Auction Topic Category */ public int getB_TopicCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicCategory_ID); if (ii == null) return 0; return ii.intValue(); } public I_B_TopicType getB_TopicType() throws RuntimeException { return (I_B_TopicType)MTable.get(getCtx(), I_B_TopicType.Table_Name) .getPO(getB_TopicType_ID(), get_TrxName()); } /** Set Topic Type. @param B_TopicType_ID Auction Topic Type */ public void setB_TopicType_ID (int B_TopicType_ID) { if (B_TopicType_ID < 1) set_ValueNoCheck (COLUMNNAME_B_TopicType_ID, null); else set_ValueNoCheck (COLUMNNAME_B_TopicType_ID, Integer.valueOf(B_TopicType_ID)); } /** Get Topic Type. @return Auction Topic Type */ public int getB_TopicType_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicType_ID); 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 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_B_TopicCategory.java
1
请完成以下Java代码
public PasswordEncoder getPasswordEncoder() { return passwordEncoder; } public IdmEngineConfiguration setPasswordEncoder(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; return this; } public PasswordSalt getPasswordSalt() { return passwordSalt; } public IdmEngineConfiguration setPasswordSalt(PasswordSalt passwordSalt) { this.passwordSalt = passwordSalt; return this; } @Override public IdmEngineConfiguration setSessionFactories(Map<Class<?>, SessionFactory> sessionFactories) { this.sessionFactories = sessionFactories; return this; } @Override public IdmEngineConfiguration setDatabaseSchemaUpdate(String databaseSchemaUpdate) { this.databaseSchemaUpdate = databaseSchemaUpdate; return this; } @Override public IdmEngineConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) { this.enableEventDispatcher = enableEventDispatcher; return this; } @Override public IdmEngineConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) { this.eventDispatcher = eventDispatcher; return this; }
@Override public IdmEngineConfiguration setEventListeners(List<FlowableEventListener> eventListeners) { this.eventListeners = eventListeners; return this; } @Override public IdmEngineConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) { this.typedEventListeners = typedEventListeners; return this; } @Override public IdmEngineConfiguration setClock(Clock clock) { this.clock = clock; return this; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\IdmEngineConfiguration.java
1
请完成以下Java代码
public Object eval(Bindings bindings, ELContext context) { return child.eval(bindings, context); } @Override public String toString() { return (deferred ? "#" : "$") + "{...}"; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { b.append(deferred ? "#{" : "${"); child.appendStructure(b, bindings); b.append("}"); } public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) { return child.getMethodInfo(bindings, context, returnType, paramTypes); } public Object invoke( Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues ) { return child.invoke(bindings, context, returnType, paramTypes, paramValues); }
public Class<?> getType(Bindings bindings, ELContext context) { return child.getType(bindings, context); } public boolean isLiteralText() { return child.isLiteralText(); } public boolean isReadOnly(Bindings bindings, ELContext context) { return child.isReadOnly(bindings, context); } public void setValue(Bindings bindings, ELContext context, Object value) { child.setValue(bindings, context, value); } public int getCardinality() { return 1; } public AstNode getChild(int i) { return i == 0 ? child : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstEval.java
1
请完成以下Java代码
public String toString() { return "News{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + ", language=" + language + '}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Article article = (Article) o; if (!Objects.equals(id, article.id)) { return false; } if (!Objects.equals(title, article.title)) { return false;
} if (!Objects.equals(content, article.content)) { return false; } return Objects.equals(language, article.language); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (content != null ? content.hashCode() : 0); result = 31 * result + (language != null ? language.hashCode() : 0); return result; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query-3\src\main\java\com\baeldung\spring\data\jpa\spel\entity\Article.java
1
请完成以下Java代码
public Response getUser(Message message) { return Response.ok(message).build(); } @POST @Path("/user") @RolesAllowed({"CREATE_USER"}) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response postUser(@Valid final UserDto userDto) { final var user = userService.createUser(userDto); final var roles = user.getRoles().stream().map(Role::getName).collect(Collectors.toSet()); return Response.ok(new UserResponse(user.getUsername(), roles)).build(); }
@POST @Path("/login") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @PermitAll public Response login(@Valid final LoginDto loginDto) { if (userService.checkUserCredentials(loginDto.username(), loginDto.password())) { final var user = userService.findByUsername(loginDto.username()); final var token = userService.generateJwtToken(user); return Response.ok().entity(new TokenResponse("Bearer " + token,"3600")).build(); } else { return Response.status(Response.Status.UNAUTHORIZED).entity(new Message("Invalid credentials")).build(); } } }
repos\tutorials-master\quarkus-modules\quarkus-rbac\src\main\java\com\baeldung\quarkus\rbac\api\SecureResourceController.java
1
请完成以下Java代码
public class StartEventValidator extends ProcessLevelValidator { @Override protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) { List<StartEvent> startEvents = process.findFlowElementsOfType(StartEvent.class, false); validateEventDefinitionTypes(startEvents, process, errors); validateMultipleStartEvents(startEvents, process, errors); } protected void validateEventDefinitionTypes( List<StartEvent> startEvents, Process process, List<ValidationError> errors ) { for (StartEvent startEvent : startEvents) { if (startEvent.getEventDefinitions() != null && !startEvent.getEventDefinitions().isEmpty()) { EventDefinition eventDefinition = startEvent.getEventDefinitions().get(0); if ( !(eventDefinition instanceof MessageEventDefinition) && !(eventDefinition instanceof TimerEventDefinition) && !(eventDefinition instanceof SignalEventDefinition) ) { addError(errors, Problems.START_EVENT_INVALID_EVENT_DEFINITION, process, startEvent); } } } } protected void validateMultipleStartEvents( List<StartEvent> startEvents, Process process, List<ValidationError> errors ) {
// Multiple none events are not supported List<StartEvent> noneStartEvents = new ArrayList<StartEvent>(); for (StartEvent startEvent : startEvents) { if (startEvent.getEventDefinitions() == null || startEvent.getEventDefinitions().isEmpty()) { noneStartEvents.add(startEvent); } } if (noneStartEvents.size() > 1) { for (StartEvent startEvent : noneStartEvents) { addError(errors, Problems.START_EVENT_MULTIPLE_FOUND, process, startEvent); } } } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\StartEventValidator.java
1
请在Spring Boot框架中完成以下Java代码
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException { ImageCode imageCode = createImageCode(); sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, imageCode); ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream()); } @GetMapping("/code/sms") public void createSmsCode(HttpServletRequest request, HttpServletResponse response, String mobile) { SmsCode smsCode = createSMSCode(); sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_SMS_CODE + mobile, smsCode); // 输出验证码到控制台代替短信发送服务 System.out.println("您的登录验证码为:" + smsCode.getCode() + ",有效时间为60秒"); } private SmsCode createSMSCode() { String code = RandomStringUtils.randomNumeric(6); return new SmsCode(code, 60); } private ImageCode createImageCode() { int width = 100; // 验证码图片宽度 int height = 36; // 验证码图片长度 int length = 4; // 验证码位数 int expireIn = 60; // 验证码有效时间 60s BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.ITALIC, 20)); g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl);
} StringBuilder sRand = new StringBuilder(); for (int i = 0; i < length; i++) { String rand = String.valueOf(random.nextInt(10)); sRand.append(rand); g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); g.drawString(rand, 13 * i + 6, 16); } g.dispose(); return new ImageCode(image, sRand.toString(), expireIn); } private Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } }
repos\SpringAll-master\38.Spring-Security-SmsCode\src\main\java\cc\mrbird\web\controller\ValidateController.java
2
请完成以下Java代码
final class Label { public static Label ofString(final String name) { return new Label(name); } public static ImmutableSet<Label> ofCommaSeparatedString(final String labelsStr) { if (labelsStr == null || labelsStr.isEmpty()) { return ImmutableSet.of(); } final List<String> labels = Splitter.on(",") .trimResults() .omitEmptyStrings() .splitToList(labelsStr); return labels.stream() .distinct() .map(Label::ofString) .collect(ImmutableSet.toImmutableSet());
} private final String name; private Label(@NonNull final String name) { this.name = name.trim(); } @Override public String toString() { return name; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\Label.java
1
请在Spring Boot框架中完成以下Java代码
public String getSession(String version, String openId, String type) { return get(generateKey(version, openId, type)); } public void delSession(String version, String openId, String type) { del(version, openId, type); } private String get(String key) { return stringRedisTemplate.opsForValue().get(key); } private void set(String key, String value) { stringRedisTemplate.opsForValue().set(key, value, EXPIRE_TIME, TimeUnit.SECONDS); } private void del(String version, String openId, String type) { stringRedisTemplate.delete(generateKey(version, openId, type)); } private String generateKey(String version, String openId, String type) { // if (V1.equals(version)) { // if (DIALOG_VOICE_TYPE.equals(type)) { // return VOICE_OPENID_V1_SESSION + openId; // } else { // return TEXT_OPENID_V1_SESSION + openId; // } // } else
if (V2.equals(version)) { if (DIALOG_VOICE_TYPE.equals(type)) { return VOICE_OPENID_V2_SESSION + openId; } else { return TEXT_OPENID_V2_SESSION + openId; } } else { if (DIALOG_VOICE_TYPE.equals(type)) { return VOICE_OPENID_V3_SESSION + openId; } else { return TEXT_OPENID_V3_SESSION + openId; } } } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\config\SessionCache.java
2
请在Spring Boot框架中完成以下Java代码
public HttpPortMapping http(int httpPort) { return new HttpPortMapping(httpPort); } @Override public void init(H http) { http.setSharedObject(PortMapper.class, getPortMapper()); } /** * Gets the {@link PortMapper} to use. If {@link #portMapper(PortMapper)} was not * invoked, builds a {@link PortMapperImpl} using the port mappings specified with * {@link #http(int)}. * @return the {@link PortMapper} to use */ private PortMapper getPortMapper() { if (this.portMapper == null) { PortMapperImpl portMapper = new PortMapperImpl(); portMapper.setPortMappings(this.httpsPortMappings); this.portMapper = portMapper; } return this.portMapper; } /** * Allows specifying the HTTPS port for a given HTTP port when redirecting between * HTTP and HTTPS. * * @author Rob Winch * @since 3.2 */ public final class HttpPortMapping { private final int httpPort; /** * Creates a new instance * @param httpPort * @see PortMapperConfigurer#http(int)
*/ private HttpPortMapping(int httpPort) { this.httpPort = httpPort; } /** * Maps the given HTTP port to the provided HTTPS port and vice versa. * @param httpsPort the HTTPS port to map to * @return the {@link PortMapperConfigurer} for further customization */ public PortMapperConfigurer<H> mapsTo(int httpsPort) { PortMapperConfigurer.this.httpsPortMappings.put(String.valueOf(this.httpPort), String.valueOf(httpsPort)); return PortMapperConfigurer.this; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\PortMapperConfigurer.java
2
请完成以下Java代码
public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public java.math.BigDecimal getQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); }
@Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStorageAttributesKey (java.lang.String StorageAttributesKey) { set_ValueNoCheck (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return (java.lang.String)get_Value(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_ATP_QueryResult.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ConfigurationProperty other = (ConfigurationProperty) obj; boolean result = true; result = result && ObjectUtils.nullSafeEquals(this.name, other.name); result = result && ObjectUtils.nullSafeEquals(this.value, other.value); return result; } @Override public int hashCode() { int result = ObjectUtils.nullSafeHashCode(this.name); result = 31 * result + ObjectUtils.nullSafeHashCode(this.value); return result; } @Override public String toString() { return new ToStringCreator(this).append("name", this.name) .append("value", this.value) .append("origin", this.origin) .toString(); }
@Override public int compareTo(ConfigurationProperty other) { return this.name.compareTo(other.name); } @Contract("_, !null -> !null") static @Nullable ConfigurationProperty of(ConfigurationPropertyName name, @Nullable OriginTrackedValue value) { if (value == null) { return null; } return new ConfigurationProperty(name, value.getValue(), value.getOrigin()); } @Contract("_, _, !null, _ -> !null") static @Nullable ConfigurationProperty of(@Nullable ConfigurationPropertySource source, ConfigurationPropertyName name, @Nullable Object value, @Nullable Origin origin) { if (value == null) { return null; } return new ConfigurationProperty(source, name, value, origin); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationProperty.java
1
请完成以下Java代码
public String getFillValue() { return "#585858"; } @Override public String getStrokeValue() { return "none"; } @Override public String getDValue() { return "M 10 0 C 4.4771525 0 0 4.4771525 0 10 C 0 15.522847 4.4771525 20 10 20 C 15.522847 20 20 15.522847 20 10 C 20 4.4771525 15.522847 1.1842379e-15 10 0 z M 9.09375 1.03125 C 9.2292164 1.0174926 9.362825 1.0389311 9.5 1.03125 L 9.5 3.5 L 10.5 3.5 L 10.5 1.03125 C 15.063526 1.2867831 18.713217 4.9364738 18.96875 9.5 L 16.5 9.5 L 16.5 10.5 L 18.96875 10.5 C 18.713217 15.063526 15.063526 18.713217 10.5 18.96875 L 10.5 16.5 L 9.5 16.5 L 9.5 18.96875 C 4.9364738 18.713217 1.2867831 15.063526 1.03125 10.5 L 3.5 10.5 L 3.5 9.5 L 1.03125 9.5 C 1.279102 5.0736488 4.7225326 1.4751713 9.09375 1.03125 z M 9.5 5 L 9.5 8.0625 C 8.6373007 8.2844627 8 9.0680195 8 10 C 8 11.104569 8.8954305 12 10 12 C 10.931981 12 11.715537 11.362699 11.9375 10.5 L 14 10.5 L 14 9.5 L 11.9375 9.5 C 11.756642 8.7970599 11.20294 8.2433585 10.5 8.0625 L 10.5 5 L 9.5 5 z "; } public void drawIcon( final int imageX, final int imageYo, final int iconPadding, final ProcessDiagramSVGGraphics2D svgGenerator ) { Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG); gTag.setAttributeNS(null, "transform", "translate(" + (imageX) + "," + (imageYo) + ")"); Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG); pathTag.setAttributeNS(null, "d", this.getDValue()); pathTag.setAttributeNS(null, "fill", this.getFillValue()); pathTag.setAttributeNS(null, "stroke", this.getStrokeValue()); gTag.appendChild(pathTag); svgGenerator.getExtendDOMGroupManager().addElement(gTag); } @Override public String getAnchorValue() { return null; } @Override
public String getStyleValue() { return null; } @Override public Integer getWidth() { return 20; } @Override public Integer getHeight() { return 20; } @Override public String getStrokeWidth() { return null; } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\TimerIconType.java
1
请完成以下Java代码
public List<DurationReportResult> executeDurationReport(CommandContext commandContext) { doAuthCheck(commandContext); if(areNotInAscendingOrder(startedAfter, startedBefore)) { return Collections.emptyList(); } return commandContext .getHistoricReportManager() .selectHistoricProcessInstanceDurationReport(this); } protected void doAuthCheck(CommandContext commandContext) { // since a report does only make sense in context of historic // data, the authorization check will be performed here for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { if (processDefinitionIdIn == null && processDefinitionKeyIn == null) { checker.checkReadHistoryAnyProcessDefinition(); } else { List<String> processDefinitionKeys = new ArrayList<String>(); if (processDefinitionKeyIn != null) { processDefinitionKeys.addAll(Arrays.asList(processDefinitionKeyIn)); } if (processDefinitionIdIn != null) { for (String processDefinitionId : processDefinitionIdIn) { ProcessDefinition processDefinition = commandContext.getProcessDefinitionManager() .findLatestProcessDefinitionById(processDefinitionId); if (processDefinition != null && processDefinition.getKey() != null) { processDefinitionKeys.add(processDefinition.getKey()); } } } if (!processDefinitionKeys.isEmpty()) { for (String processDefinitionKey : processDefinitionKeys) { checker.checkReadHistoryProcessDefinition(processDefinitionKey); } } } } } // getter ////////////////////////////////////////////////////// public Date getStartedAfter() { return startedAfter; }
public Date getStartedBefore() { return startedBefore; } public String[] getProcessDefinitionIdIn() { return processDefinitionIdIn; } public String[] getProcessDefinitionKeyIn() { return processDefinitionKeyIn; } public TenantCheck getTenantCheck() { return tenantCheck; } public String getReportPeriodUnitName() { return durationPeriodUnit.name(); } protected class ExecuteDurationReportCmd implements Command<List<DurationReportResult>> { @Override public List<DurationReportResult> execute(CommandContext commandContext) { return executeDurationReport(commandContext); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricProcessInstanceReportImpl.java
1
请完成以下Java代码
private static IRangeAwareParams createSource(final ICalloutField calloutField) { final String parameterName = calloutField.getColumnName(); final Object fieldValue = calloutField.getValue(); if (fieldValue instanceof LookupValue) { final Object idObj = ((LookupValue)fieldValue).getId(); return ProcessParams.ofValueObject(parameterName, idObj); } else if (fieldValue instanceof DateRangeValue) { final DateRangeValue dateRange = (DateRangeValue)fieldValue; return ProcessParams.of( parameterName, TimeUtil.asDate(dateRange.getFrom()), TimeUtil.asDate(dateRange.getTo())); } else {
return ProcessParams.ofValueObject(parameterName, fieldValue); } } } private static final class ProcessParametersDataBindingDescriptorBuilder implements DocumentEntityDataBindingDescriptorBuilder { public static final ProcessParametersDataBindingDescriptorBuilder instance = new ProcessParametersDataBindingDescriptorBuilder(); private static final DocumentEntityDataBindingDescriptor dataBinding = () -> ADProcessParametersRepository.instance; @Override public DocumentEntityDataBindingDescriptor getOrBuild() { return dataBinding; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessDescriptorsFactory.java
1
请完成以下Java代码
public Boolean getConfigurationFileFormat() { return this.configurationFileFormat; } public void setConfigurationFileFormat(Boolean configurationFileFormat) { this.configurationFileFormat = configurationFileFormat; } public Boolean getPackaging() { return this.packaging; } public void setPackaging(Boolean packaging) { this.packaging = packaging; } public Boolean getType() { return this.type; } public void setType(Boolean type) { this.type = type; } public InvalidDependencyInformation getDependencies() { return this.dependencies; } public void triggerInvalidDependencies(List<String> dependencies) { this.dependencies = new InvalidDependencyInformation(dependencies); } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid) .add("javaVersion=" + this.javaVersion) .add("language=" + this.language) .add("configurationFileFormat=" + this.configurationFileFormat) .add("packaging=" + this.packaging) .add("type=" + this.type) .add("dependencies=" + this.dependencies) .add("message='" + this.message + "'") .toString(); } } /** * Invalid dependencies information. */
public static class InvalidDependencyInformation { private boolean invalid = true; private final List<String> values; public InvalidDependencyInformation(List<String> values) { this.values = values; } public boolean isInvalid() { return this.invalid; } public List<String> getValues() { return this.values; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString(); } } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectRequestDocument.java
1
请完成以下Java代码
public class NonResponsiveConsumerEvent extends KafkaEvent { private static final long serialVersionUID = 1L; private final long timeSinceLastPoll; private final String listenerId; private final transient @Nullable List<TopicPartition> topicPartitions; private transient final Consumer<?, ?> consumer; /** * Construct an instance with the provided properties. * @param source the container instance that generated the event. * @param container the container or the parent container if the container is a child. * @param timeSinceLastPoll the time since the last poll. * @param id the container id. * @param topicPartitions the topic partitions. * @param consumer the consumer. * @since 2.2.1 */ public NonResponsiveConsumerEvent(Object source, Object container, long timeSinceLastPoll, String id, @Nullable Collection<TopicPartition> topicPartitions, Consumer<?, ?> consumer) { super(source, container); this.timeSinceLastPoll = timeSinceLastPoll; this.listenerId = id; this.topicPartitions = topicPartitions == null ? null : new ArrayList<>(topicPartitions); this.consumer = consumer; } /** * How long since the last poll. * @return the time in milliseconds. */
public long getTimeSinceLastPoll() { return this.timeSinceLastPoll; } /** * The TopicPartitions the container is listening to. * @return the TopicPartition list. */ public @Nullable Collection<TopicPartition> getTopicPartitions() { return this.topicPartitions == null ? null : Collections.unmodifiableList(this.topicPartitions); } /** * The id of the listener (if {@code @KafkaListener}) or the container bean name. * @return the id. */ public String getListenerId() { return this.listenerId; } /** * Retrieve the consumer. Only populated if the listener is consumer-aware. * Allows the listener to resume a paused consumer. * @return the consumer. */ public Consumer<?, ?> getConsumer() { return this.consumer; } @Override public String toString() { return "NonResponsiveConsumerEvent [timeSinceLastPoll=" + ((float) this.timeSinceLastPoll / 1000) + "s, listenerId=" + this.listenerId // NOSONAR magic # + ", container=" + getSource() + ", topicPartitions=" + this.topicPartitions + "]"; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\NonResponsiveConsumerEvent.java
1
请完成以下Java代码
protected final void register(String description, ServletContext servletContext) { D registration = addRegistration(description, servletContext); if (registration == null) { if (this.ignoreRegistrationFailure) { logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)"); return; } throw new IllegalStateException( "Failed to register '%s' on the servlet context. Possibly already registered?" .formatted(description)); } configure(registration); } /** * Sets whether registration failures should be ignored. If set to true, a failure * will be logged. If set to false, an {@link IllegalStateException} will be thrown. * @param ignoreRegistrationFailure whether to ignore registration failures * @since 3.1.0 */ public void setIgnoreRegistrationFailure(boolean ignoreRegistrationFailure) { this.ignoreRegistrationFailure = ignoreRegistrationFailure; } @Override public void setBeanName(String name) { this.beanName = name; } protected abstract @Nullable D addRegistration(String description, ServletContext servletContext); protected void configure(D registration) { registration.setAsyncSupported(this.asyncSupported); if (!this.initParameters.isEmpty()) { registration.setInitParameters(this.initParameters); } }
/** * Deduces the name for this registration. Will return user specified name or fallback * to the bean name. If the bean name is not available, convention based naming is * used. * @param value the object used for convention based names * @return the deduced name */ protected final String getOrDeduceName(@Nullable Object value) { if (this.name != null) { return this.name; } if (this.beanName != null) { return this.beanName; } if (value == null) { return "null"; } return Conventions.getVariableName(value); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\DynamicRegistrationBean.java
1
请在Spring Boot框架中完成以下Java代码
public class ESRBPBankAccountBL implements IESRBPBankAccountBL { private final BankRepository bankRepo; public ESRBPBankAccountBL( @NonNull final BankRepository bankRepo) { this.bankRepo = bankRepo; } @Override public String retrieveBankAccountNo(@NonNull final I_C_BP_BankAccount bankAccount) { if (isPostBank(bankAccount)) { return "000000"; } else { return bankAccount.getAccountNo(); } } private boolean isPostBank(@NonNull final I_C_BP_BankAccount bankAccount) { final BankId bankId = BankId.ofRepoIdOrNull(bankAccount.getC_Bank_ID()); if (bankId == null) { return false; } final Bank bank = bankRepo.getById(bankId); return bank.isEsrPostBank(); } @Override public String retrieveESRAccountNo(final I_C_BP_BankAccount bankAccount) { Check.assume(bankAccount.isEsrAccount(), bankAccount + " has IsEsrAccount=Y");
final String renderedNo = bankAccount.getESR_RenderedAccountNo(); Check.assume(!Check.isEmpty(renderedNo, true), bankAccount + " has a ESR_RenderedAccountNo"); if (!renderedNo.contains("-")) { // task 07789: the rendered number is not "rendered" to start with. This happens e.g. if the number was parsed from an ESR payment string. return renderedNo; } final String[] renderenNoComponents = renderedNo.split("-"); Check.assume(renderenNoComponents.length == 3, renderedNo + " contains three '-' separated parts"); final StringBuilder sb = new StringBuilder(); sb.append(renderenNoComponents[0]); sb.append(StringUtils.lpadZero(renderenNoComponents[1], 6, "middle section of " + renderedNo)); sb.append(renderenNoComponents[2]); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRBPBankAccountBL.java
2
请完成以下Java代码
public class DiscoverBpmPlatformPluginsStep extends DeploymentOperationStep { @Override public String getName() { return "Discover BPM Platform Plugins"; } @Override public void performOperationStep(DeploymentOperation operationContext) { PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); BpmPlatformPlugins plugins = BpmPlatformPlugins.load(getPluginsClassloader()); JmxManagedBpmPlatformPlugins jmxManagedPlugins = new JmxManagedBpmPlatformPlugins(plugins); serviceContainer.startService(ServiceTypes.BPM_PLATFORM, RuntimeContainerDelegateImpl.SERVICE_NAME_PLATFORM_PLUGINS, jmxManagedPlugins);
} protected ClassLoader getPluginsClassloader() { ClassLoader pluginsClassLoader = ClassLoaderUtil.getContextClassloader(); if(pluginsClassLoader == null) { // if context classloader is null, use classloader which loaded the camunda-engine jar. pluginsClassLoader = BpmPlatform.class.getClassLoader(); } return pluginsClassLoader; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\DiscoverBpmPlatformPluginsStep.java
1
请完成以下Java代码
public void mergeThreeStreams() { Stream<String> streamA = Stream.of("A", "B", "C"); Stream<String> streamB = Stream.of("apple", "banana", "carrot", "date"); Stream<String> streamC = Stream.of("fritter", "split", "cake", "roll", "pastry"); Stream<List<String>> merged = StreamUtils.mergeToList(streamA, streamB, streamC); } public void interleavingStreamsUsingRoundRobin() { Stream<String> streamA = Stream.of("Peter", "Paul", "Mary"); Stream<String> streamB = Stream.of("A", "B", "C", "D", "E"); Stream<String> streamC = Stream.of("foo", "bar", "baz", "xyzzy"); Stream<String> interleaved = StreamUtils.interleave(Selectors.roundRobin(), streamA, streamB, streamC); } public void takeWhileAndTakeUntilStream() { Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1); Stream<Integer> finiteIntsWhileLessThan10 = StreamUtils.takeWhile(infiniteInts, i -> i < 10); Stream<Integer> finiteIntsUntilGreaterThan10 = StreamUtils.takeUntil(infiniteInts, i -> i > 10); } public void skipWhileAndSkipUntilStream() { Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Stream<Integer> skippedWhileConditionMet = StreamUtils.skipWhile(ints, i -> i < 4); Stream<Integer> skippedUntilConditionMet = StreamUtils.skipWhile(ints, i -> i > 4);
} public void unfoldStream() { Stream<Integer> unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty()); } public void windowedStream() { Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5); List<List<Integer>> windows = StreamUtils.windowed(integerStream, 2).collect(toList()); List<List<Integer>> windowsWithSkipIndex = StreamUtils.windowed(integerStream, 3, 2).collect(toList()); List<List<Integer>> windowsWithSkipIndexAndAllowLowerSize = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList()); } public void groupRunsStreams() { Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5); List<List<Integer>> runs = StreamUtils.groupRuns(integerStream).collect(toList()); } public void aggreagateOnBiElementPredicate() { Stream<String> stream = Stream.of("a1", "b1", "b2", "c1"); Stream<List<String>> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0)); } }
repos\tutorials-master\libraries\src\main\java\com\baeldung\protonpack\StreamUtilsExample.java
1
请完成以下Java代码
public Dimension getPreferredSize() { Dimension d_check = this.checkBox.getPreferredSize(); Dimension d_label = this.label.getPreferredSize(); return new Dimension(d_check.width + d_label.width, (d_check.height < d_label.height ? d_label.height : d_check.height)); } /** * Decorates this renderer based on the passed in components. */ public Component getTreeCellRendererComponent(JTree tree, Object object, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { /* * most of the rendering is delegated to the wrapped * DefaultTreeCellRenderer, the rest depends on the TreeCheckingModel */ this.label.getTreeCellRendererComponent(tree, object, selected, expanded, leaf, row, hasFocus); if (tree instanceof CheckboxTree) { TreeCheckingModel checkingModel = ((CheckboxTree) tree).getCheckingModel(); TreePath path = tree.getPathForRow(row); this.checkBox.setEnabled(checkingModel.isPathEnabled(path)); boolean checked = checkingModel.isPathChecked(path); boolean greyed = checkingModel.isPathGreyed(path); if (checked && !greyed) { this.checkBox.setState(State.CHECKED); } if (!checked && greyed) { this.checkBox.setState(State.GREY_UNCHECKED); } if (checked && greyed) { this.checkBox.setState(State.GREY_CHECKED); } if (!checked && !greyed) { this.checkBox.setState(State.UNCHECKED); } } return this; } /** * Checks if the (x,y) coordinates are on the Checkbox. * * @return boolean * @param x * @param y */ public boolean isOnHotspot(int x, int y) { // TODO: alternativa (ma funge???) //return this.checkBox.contains(x, y); return (this.checkBox.getBounds().contains(x, y)); } /** * Loads an ImageIcon from the file iconFile, searching it in the * classpath.Guarda un po' */ protected static ImageIcon loadIcon(String iconFile) {
try { return new ImageIcon(DefaultCheckboxTreeCellRenderer.class.getClassLoader().getResource(iconFile)); } catch (NullPointerException npe) { // did not find the resource return null; } } @Override public void setBackground(Color color) { if (color instanceof ColorUIResource) { color = null; } super.setBackground(color); } /** * Sets the icon used to represent non-leaf nodes that are expanded. */ public void setOpenIcon(Icon newIcon) { this.label.setOpenIcon(newIcon); } /** * Sets the icon used to represent non-leaf nodes that are not expanded. */ public void setClosedIcon(Icon newIcon) { this.label.setClosedIcon(newIcon); } /** * Sets the icon used to represent leaf nodes. */ public void setLeafIcon(Icon newIcon) { this.label.setLeafIcon(newIcon); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\DefaultCheckboxTreeCellRenderer.java
1
请完成以下Java代码
public String execute() { String cmd = Msg.parseTranslation(Env.getCtx(), getOS_Command()).trim(); if (cmd == null || cmd.equals("")) return "Cannot execute '" + getOS_Command() + "'"; // if (isServerProcess()) return executeRemote(cmd); return executeLocal(cmd); } // execute /** * Execute Task locally and wait * @param cmd command * @return execution info */ public String executeLocal(String cmd) { log.info(cmd); if (m_task != null && m_task.isAlive()) m_task.interrupt(); m_task = new Task(cmd); m_task.start(); StringBuffer sb = new StringBuffer(); while (true) { // Give it a bit of time try { Thread.sleep(500); } catch (InterruptedException ioe) { log.error(cmd, ioe); } // Info to user //metas: c.ghita@metas.ro : start sb.append(m_task.getOut()); if (m_task.getOut().length() > 0) sb.append("\n-----------\n"); sb.append(m_task.getErr()); if (m_task.getErr().length() > 0) sb.append("\n-----------"); //metas: c.ghita@metas.ro : end // Are we done?
if (!m_task.isAlive()) break; } log.info("done"); return sb.toString(); } // executeLocal /** * Execute Task locally and wait * @param cmd command * @return execution info */ public String executeRemote(String cmd) { log.info(cmd); return "Remote:\n"; } // executeRemote /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MTask["); sb.append(get_ID()) .append("-").append(getName()) .append(";Server=").append(isServerProcess()) .append(";").append(getOS_Command()) .append ("]"); return sb.toString (); } // toString /* * metas: c.ghita@metas.ro * get Task */ public Task getTask() { return m_task; } } // MTask
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTask.java
1
请完成以下Java代码
public class CCacheStatsPredicate implements Predicate<CCacheStats> { @Nullable private final String cacheNameContainsLC; private final int minSize; @NonNull private final ImmutableSet<CacheLabel> labels; @Builder private CCacheStatsPredicate( @Nullable final String cacheNameContains, @Nullable final Integer minSize, @Nullable final String labels) { this.cacheNameContainsLC = StringUtils.trimBlankToOptional(cacheNameContains) .map(String::toLowerCase) .orElse(null); this.minSize = minSize != null ? Math.max(minSize, 0) : 0; this.labels = parseLabels(labels); } private static ImmutableSet<CacheLabel> parseLabels(final String labels) { final String labelsNorm = StringUtils.trimBlankToNull(labels); if (labelsNorm == null) { return ImmutableSet.of(); } return Splitter.on(",") .trimResults() .omitEmptyStrings() .splitToStream(labelsNorm) .map(CacheLabel::ofTableName) .collect(ImmutableSet.toImmutableSet()); }
@Override public boolean test(@NonNull final CCacheStats stats) { if (cacheNameContainsLC != null && !stats.getName().toLowerCase().contains(cacheNameContainsLC)) { return false; } if (minSize > 0 && stats.getSize() < minSize) { return false; } if (!labels.isEmpty() && !stats.getLabels().containsAll(labels)) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCacheStatsPredicate.java
1
请在Spring Boot框架中完成以下Java代码
public String launchcFluxFromSSEWebClient() { consumeFlux(); return "LAUNCHED EVENT CLIENT!!! Check the logs..."; } @GetMapping("/launch-sse-from-flux-endpoint-client") public String launchFluxFromFluxWebClient() { consumeSSEFromFluxEndpoint(); return "LAUNCHED EVENT CLIENT!!! Check the logs..."; } @Async public void consumeSSE() { ParameterizedTypeReference<ServerSentEvent<String>> type = new ParameterizedTypeReference<ServerSentEvent<String>>() { }; Flux<ServerSentEvent<String>> eventStream = client.get() .uri("/stream-sse") .retrieve() .bodyToFlux(type); eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), () -> logger.info("Completed!!!")); } @Async public void consumeFlux() { Flux<String> stringStream = client.get() .uri("/stream-flux") .accept(MediaType.TEXT_EVENT_STREAM) .retrieve() .bodyToFlux(String.class);
stringStream.subscribe(content -> logger.info("Current time: {} - Received content: {} ", LocalTime.now(), content), error -> logger.error("Error retrieving content: {}", error), () -> logger.info("Completed!!!")); } @Async public void consumeSSEFromFluxEndpoint() { ParameterizedTypeReference<ServerSentEvent<String>> type = new ParameterizedTypeReference<ServerSentEvent<String>>() { }; Flux<ServerSentEvent<String>> eventStream = client.get() .uri("/stream-flux") .accept(MediaType.TEXT_EVENT_STREAM) .retrieve() .bodyToFlux(type); eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error), () -> logger.info("Completed!!!")); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-2\src\main\java\com\baeldung\reactive\serversentevents\consumer\controller\ClientController.java
2
请在Spring Boot框架中完成以下Java代码
public static String createLinkString(Map<String, String> params) { List<String> keys = new ArrayList<String>(params.keySet()); Collections.sort(keys); String prestr = ""; for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value = params.get(key); if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符 prestr = prestr + key + "=" + value; } else { prestr = prestr + key + "=" + value + "&"; } } return prestr; } /** * 生成文件摘要 * @param strFilePath 文件路径 * @param file_digest_type 摘要算法
* @return 文件摘要结果 */ public static String getAbstract(String strFilePath, String file_digest_type) throws IOException { PartSource file = new FilePartSource(new File(strFilePath)); if("MD5".equals(file_digest_type)){ return DigestUtils.md5Hex(file.createInputStream()); } else if("SHA".equals(file_digest_type)) { return DigestUtils.sha256Hex(file.createInputStream()); } else { return ""; } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\alipay\util\AlipayCore.java
2
请在Spring Boot框架中完成以下Java代码
public class ExternalSystemShopware6ConfigId implements IExternalSystemChildConfigId { int repoId; @JsonCreator @NonNull public static ExternalSystemShopware6ConfigId ofRepoId(final int repoId) { return new ExternalSystemShopware6ConfigId(repoId); } @Nullable public static ExternalSystemShopware6ConfigId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new ExternalSystemShopware6ConfigId(repoId) : null; } public static ExternalSystemShopware6ConfigId cast(@NonNull final IExternalSystemChildConfigId id) { return (ExternalSystemShopware6ConfigId)id; }
@JsonValue public int toJson() { return getRepoId(); } private ExternalSystemShopware6ConfigId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "ExternalSystem_Config_Shopware6_ID"); } @Override public ExternalSystemType getType() { return ExternalSystemType.Shopware6; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\shopware6\ExternalSystemShopware6ConfigId.java
2
请完成以下Java代码
public void setContactDetails(final I_C_Order order) { if (order.getC_BPartner_Location_ID() <= 0) { return; } final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(order.getC_BPartner_ID(), order.getC_BPartner_Location_ID()); final I_C_BPartner_Location bPartnerLocationRecord = bpartnerDAO.getBPartnerLocationByIdEvenInactive(bPartnerLocationId); Check.assumeNotNull(bPartnerLocationRecord, "C_BPartner_Location cannot be missing for webui selection! Id: {}", bPartnerLocationId); final Optional<I_AD_User> userRecord = Optional.ofNullable(UserId.ofRepoIdOrNull(order.getAD_User_ID())) .map(userDAO::getById); if (userRecord.isPresent()) { final I_AD_User user = userRecord.get(); order.setBPartnerName(firstNotBlank(user.getName(), bPartnerLocationRecord.getBPartnerName())); order.setEMail(firstNotBlank(user.getEMail(), bPartnerLocationRecord.getEMail())); order.setPhone(firstNotBlank(user.getPhone(), bPartnerLocationRecord.getPhone())); } else
{ order.setBPartnerName(bPartnerLocationRecord.getBPartnerName()); order.setEMail(bPartnerLocationRecord.getEMail()); order.setPhone(bPartnerLocationRecord.getPhone()); } } @CalloutMethod(columnNames = { I_C_Order.COLUMNNAME_M_Shipper_ID }, skipIfCopying = true) public void updateDeliveryViaRule(final I_C_Order order) { final ShipperId shipperId = ShipperId.ofRepoIdOrNull(order.getM_Shipper_ID()); if (shipperId != null) { order.setDeliveryViaRule(X_C_Order.DELIVERYVIARULE_Shipper); } else { order.setDeliveryViaRule(X_C_Order.DELIVERYVIARULE_Pickup); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\callout\C_Order.java
1
请完成以下Java代码
private InputStreamReader newInputStreamReaderForSource(String encoding) throws UnsupportedEncodingException { if (encoding != null) { return new InputStreamReader(streamSource.getInputStream(), encoding); } else { return new InputStreamReader(streamSource.getInputStream()); } } public ChannelDefinitionParse name(String name) { this.name = name; return this; } public ChannelDefinitionParse sourceInputStream(InputStream inputStream) { if (name == null) { name("inputStream"); } setStreamSource(new InputStreamSource(inputStream)); return this; } public String getSourceSystemId() { return sourceSystemId; } public ChannelDefinitionParse setSourceSystemId(String sourceSystemId) { this.sourceSystemId = sourceSystemId; return this; } public ChannelDefinitionParse sourceUrl(URL url) { if (name == null) { name(url.toString()); } setStreamSource(new UrlStreamSource(url)); return this; } public ChannelDefinitionParse sourceUrl(String url) { try { return sourceUrl(new URL(url)); } catch (MalformedURLException e) { throw new FlowableException("malformed url: " + url, e); } } public ChannelDefinitionParse sourceResource(String resource) { if (name == null) { name(resource); } setStreamSource(new ResourceStreamSource(resource)); return this; } public ChannelDefinitionParse sourceString(String string) { if (name == null) { name("string"); } setStreamSource(new StringStreamSource(string)); return this;
} protected void setStreamSource(StreamSource streamSource) { if (this.streamSource != null) { throw new FlowableException("invalid: multiple sources " + this.streamSource + " and " + streamSource); } this.streamSource = streamSource; } /* * ------------------- GETTERS AND SETTERS ------------------- */ public List<ChannelDefinitionEntity> getChannelDefinitions() { return channelDefinitions; } public EventDeploymentEntity getDeployment() { return deployment; } public void setDeployment(EventDeploymentEntity deployment) { this.deployment = deployment; } public ChannelModel getChannelModel() { return channelModel; } public void setChannelModel(ChannelModel channelModel) { this.channelModel = channelModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\parser\ChannelDefinitionParse.java
1
请完成以下Java代码
protected boolean isCmmnResource(Resource resourceEntity) { return StringUtil.hasAnySuffix(resourceEntity.getName(), CmmnDeployer.CMMN_RESOURCE_SUFFIXES); } // ensures protected void ensureDeploymentsWithIdsExists(Set<String> expected, List<DeploymentEntity> actual) { Map<String, DeploymentEntity> deploymentMap = new HashMap<>(); for (DeploymentEntity deployment : actual) { deploymentMap.put(deployment.getId(), deployment); } List<String> missingDeployments = getMissingElements(expected, deploymentMap); if (!missingDeployments.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("The following deployments are not found by id: "); builder.append(StringUtil.join(missingDeployments.iterator())); throw new NotFoundException(builder.toString()); } } protected void ensureResourcesWithIdsExist(String deploymentId, Set<String> expectedIds, List<ResourceEntity> actual) { Map<String, ResourceEntity> resources = new HashMap<>(); for (ResourceEntity resource : actual) { resources.put(resource.getId(), resource); } ensureResourcesWithKeysExist(deploymentId, expectedIds, resources, "id"); } protected void ensureResourcesWithNamesExist(String deploymentId, Set<String> expectedNames, List<ResourceEntity> actual) { Map<String, ResourceEntity> resources = new HashMap<>(); for (ResourceEntity resource : actual) { resources.put(resource.getName(), resource); } ensureResourcesWithKeysExist(deploymentId, expectedNames, resources, "name");
} protected void ensureResourcesWithKeysExist(String deploymentId, Set<String> expectedKeys, Map<String, ResourceEntity> actual, String valueProperty) { List<String> missingResources = getMissingElements(expectedKeys, actual); if (!missingResources.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("The deployment with id '"); builder.append(deploymentId); builder.append("' does not contain the following resources with "); builder.append(valueProperty); builder.append(": "); builder.append(StringUtil.join(missingResources.iterator())); throw new NotFoundException(builder.toString()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeployCmd.java
1
请完成以下Java代码
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContentId() { return contentId; } public void setContentId(String contentId) { this.contentId = contentId; } public ByteArrayEntity getContent() { return content; }
public void setContent(ByteArrayEntity content) { this.content = content; } public void setUserId(String userId) { this.userId = userId; } public String getUserId() { return userId; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityImpl.java
1
请完成以下Java代码
public int compare(Integer ol1, Integer ol2) { return index.get(ol1).getPriceActual().compareTo(index.get(ol2).getPriceActual()); } } // metas: begin static class OrderLinePromotionCandidate { BigDecimal qty; MOrderLine orderLine; I_M_PromotionReward promotionReward; } private static void addDiscountLine(MOrder order, List<OrderLinePromotionCandidate> candidates) throws Exception { for (OrderLinePromotionCandidate candidate : candidates) { final String rewardMode = candidate.promotionReward.getRewardMode(); if (MPromotionReward.REWARDMODE_Charge.equals(rewardMode)) { BigDecimal discount = candidate.orderLine.getPriceActual().multiply(candidate.qty); discount = discount.subtract(candidate.promotionReward.getAmount()); BigDecimal qty = Env.ONE; int C_Charge_ID = candidate.promotionReward.getC_Charge_ID(); I_M_Promotion promotion = candidate.promotionReward.getM_Promotion(); addDiscountLine(order, null, discount, qty, C_Charge_ID, promotion); } else if (MPromotionReward.REWARDMODE_SplitQuantity.equals(rewardMode)) { if (candidate.promotionReward.getAmount().signum() != 0) { throw new AdempiereException("@NotSupported@ @M_PromotionReward@ @Amount@ (@RewardMode@:"+rewardMode+"@)"); } MOrderLine nol = new MOrderLine(order); MOrderLine.copyValues(candidate.orderLine, nol); // task 09358: get rid of this; instead, update qtyReserved at one central place // nol.setQtyReserved(Env.ZERO); nol.setQtyDelivered(Env.ZERO); nol.setQtyInvoiced(Env.ZERO); nol.setQtyLostSales(Env.ZERO); nol.setQty(candidate.qty); nol.setPrice(Env.ZERO); nol.setDiscount(Env.ONEHUNDRED); setPromotion(nol, candidate.promotionReward.getM_Promotion()); setNextLineNo(nol); nol.saveEx(); } else { throw new AdempiereException("@NotSupported@ @RewardMode@ "+rewardMode); } } } private static void setPromotion(MOrderLine nol, I_M_Promotion promotion) {
nol.addDescription(promotion.getName()); nol.set_ValueOfColumn("M_Promotion_ID", promotion.getM_Promotion_ID()); if (promotion.getC_Campaign_ID() > 0) { nol.setC_Campaign_ID(promotion.getC_Campaign_ID()); } } private static void setNextLineNo(MOrderLine ol) { if (ol != null && Integer.toString(ol.getLine()).endsWith("0")) { for(int i = 0; i < 9; i++) { int line = ol.getLine() + i + 1; int r = DB.getSQLValue(ol.get_TrxName(), "SELECT C_OrderLine_ID FROM C_OrderLine WHERE C_Order_ID = ? AND Line = ?", ol.getC_Order_ID(), line); if (r <= 0) { ol.setLine(line); return; } } } ol.setLine(0); } // metas: end }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\model\PromotionRule.java
1
请完成以下Java代码
public class AdIssueFactory { public I_AD_Issue prepareNewIssueRecord(@NonNull final Properties ctx) { final I_AD_Issue issue = newInstance(I_AD_Issue.class); return prepareNewIssueRecord(ctx, issue); } public I_AD_Issue prepareNewIssueRecord(@NonNull final Properties ctx, @NonNull final I_AD_Issue issue) { final ISystemBL systemBL = Services.get(ISystemBL.class); final ADSystemInfo system = systemBL.get(); issue.setName("-"); issue.setUserName("?"); issue.setDBAddress("-"); issue.setSystemStatus(system.getSystemStatus()); issue.setReleaseNo("-"); issue.setVersion(system.getDbVersion()); issue.setDatabaseInfo(DB.getDatabaseInfo()); issue.setOperatingSystemInfo(Adempiere.getOSInfo()); issue.setJavaInfo(Adempiere.getJavaInfo()); issue.setReleaseTag(Adempiere.getImplementationVersion());
issue.setLocal_Host(NetUtils.getLocalHost().toString()); final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes instanceof ServletRequestAttributes) { final ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes; final HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest(); issue.setRemote_Addr(httpServletRequest.getRemoteAddr()); issue.setRemote_Host(httpServletRequest.getRemoteHost()); final String userAgent = httpServletRequest.getHeader("User-Agent"); issue.setUserAgent(userAgent); } return issue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\AdIssueFactory.java
1
请完成以下Java代码
public AnnotatedTableFactory setColumnControlVisible(final boolean columnControlVisible) { this.columnControlVisible = columnControlVisible; return this; } public AnnotatedTableFactory setModel(final TableModel model) { this.model = model; return this; } /** * @param selectionMode * @see ListSelectionModel#setSelectionMode(int) */ public AnnotatedTableFactory setSelectionMode(final int selectionMode) { this.selectionMode = selectionMode; return this; } public AnnotatedTableFactory addListSelectionListener(final ListSelectionListener listener) { Check.assumeNotNull(listener, "listener not null"); selectionListeners.add(listener); return this; } public AnnotatedTableFactory setCreateStandardSelectActions(final boolean createStandardSelectActions) { this.createStandardSelectActions = createStandardSelectActions; return this; } /**
* Adds an popup action. * * NOTE to developer: you can easily implement table popup actions by extending {@link AnnotatedTableAction}. * * @param action * @return this */ public AnnotatedTableFactory addPopupAction(final Action action) { Check.assumeNotNull(action, "action not null"); if (!popupActions.contains(action)) { popupActions.add(action); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableFactory.java
1
请完成以下Java代码
public static void main(String[] args) { String result = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\r\n" + " <cas:authenticationSuccess>\r\n" + " <cas:user>admin</cas:user>\r\n" + " <cas:attributes>\r\n" + " <cas:credentialType>UsernamePasswordCredential</cas:credentialType>\r\n" + " <cas:isFromNewLogin>true</cas:isFromNewLogin>\r\n" + " <cas:authenticationDate>2019-08-01T19:33:21.527+08:00[Asia/Shanghai]</cas:authenticationDate>\r\n" + " <cas:authenticationMethod>RestAuthenticationHandler</cas:authenticationMethod>\r\n" + " <cas:successfulAuthenticationHandlers>RestAuthenticationHandler</cas:successfulAuthenticationHandlers>\r\n" + " <cas:longTermAuthenticationRequestTokenUsed>false</cas:longTermAuthenticationRequestTokenUsed>\r\n" + " </cas:attributes>\r\n" + " </cas:authenticationSuccess>\r\n" + "</cas:serviceResponse>";
String errorRes = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\r\n" + " <cas:authenticationFailure code=\"INVALID_TICKET\">未能够识别出目标 &#39;ST-5-1g-9cNES6KXNRwq-GuRET103sm0-DESKTOP-VKLS8B3&#39;票根</cas:authenticationFailure>\r\n" + "</cas:serviceResponse>"; String error = XmlUtils.getTextForElement(errorRes, "authenticationFailure"); //System.out.println("------"+error); String error2 = XmlUtils.getTextForElement(result, "authenticationFailure"); //System.out.println("------"+error2); String principal = XmlUtils.getTextForElement(result, "user"); //System.out.println("---principal---"+principal); Map<String, Object> attributes = XmlUtils.extractCustomAttributes(result); System.out.println("---attributes---"+attributes); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\cas\util\XmlUtils.java
1
请完成以下Java代码
public I_M_Inventory getM_Inventory() throws RuntimeException { return (I_M_Inventory)MTable.get(getCtx(), I_M_Inventory.Table_Name) .getPO(getM_Inventory_ID(), get_TrxName()); } /** Set Phys.Inventory. @param M_Inventory_ID Parameters for a Physical Inventory */ public void setM_Inventory_ID (int M_Inventory_ID) { if (M_Inventory_ID < 1) set_Value (COLUMNNAME_M_Inventory_ID, null); else set_Value (COLUMNNAME_M_Inventory_ID, Integer.valueOf(M_Inventory_ID)); } /** Get Phys.Inventory. @return Parameters for a Physical Inventory */ public int getM_Inventory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Move Confirm. @param M_MovementConfirm_ID Inventory Move Confirmation */ public void setM_MovementConfirm_ID (int M_MovementConfirm_ID) { if (M_MovementConfirm_ID < 1) set_ValueNoCheck (COLUMNNAME_M_MovementConfirm_ID, null); else set_ValueNoCheck (COLUMNNAME_M_MovementConfirm_ID, Integer.valueOf(M_MovementConfirm_ID)); } /** Get Move Confirm. @return Inventory Move Confirmation */ public int getM_MovementConfirm_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementConfirm_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Movement getM_Movement() throws RuntimeException { return (I_M_Movement)MTable.get(getCtx(), I_M_Movement.Table_Name) .getPO(getM_Movement_ID(), get_TrxName()); } /** Set Inventory Move. @param M_Movement_ID Movement of Inventory */ public void setM_Movement_ID (int M_Movement_ID) { if (M_Movement_ID < 1) set_Value (COLUMNNAME_M_Movement_ID, null); else set_Value (COLUMNNAME_M_Movement_ID, Integer.valueOf(M_Movement_ID)); } /** Get Inventory Move. @return Movement of Inventory */ public int getM_Movement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Movement_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementConfirm.java
1
请在Spring Boot框架中完成以下Java代码
public class UserServiceController { private final UserService userService; public UserServiceController(UserService userService) { this.userService = userService; } @PostMapping("/users") public ResponseEntity<UserId> createUser(@RequestBody CreateUserRequest request) { String id = userService.createUser(request.getName(), request.getEmail()); return ResponseEntity.ok(new UserId(id)); } @GetMapping("/users") public ResponseEntity<Collection<UserData>> getAll() {
Collection<UserEntity> entities = userService.getAll(); Collection<UserData> users = entities.stream().map(UserServiceController::transform).collect(Collectors.toList()); return ResponseEntity.ok(users); } @DeleteMapping("/users/{id}") public ResponseEntity<Void> delete(@PathVariable("id") String id) { userService.deleteUser(id); return ResponseEntity.ok().build(); } private static UserData transform(UserEntity entity) { return new UserData(entity.getId(), entity.getName(), entity.getEmail(), entity.getEnabled()); } }
repos\spring-examples-java-17\spring-data\src\main\java\itx\examples\springdata\controller\UserServiceController.java
2
请在Spring Boot框架中完成以下Java代码
void setAuthenticationRequestRepository( Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null"); this.authenticationRequests = authenticationRequestRepository; } /** * Use the given {@link RequestMatcher} to match the request. * @param requestMatcher the {@link RequestMatcher} to use */ void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } void setShouldConvertGetRequests(boolean shouldConvertGetRequests) { this.shouldConvertGetRequests = shouldConvertGetRequests; }
private String decode(HttpServletRequest request) { String encoded = request.getParameter(Saml2ParameterNames.SAML_RESPONSE); boolean isGet = HttpMethod.GET.matches(request.getMethod()); if (!this.shouldConvertGetRequests && isGet) { return null; } Saml2Utils.DecodingConfigurer decoding = Saml2Utils.withEncoded(encoded).requireBase64(true).inflate(isGet); try { return decoding.decode(); } catch (Exception ex) { throw new Saml2AuthenticationException(Saml2Error.invalidResponse(ex.getMessage()), ex); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\BaseOpenSamlAuthenticationTokenConverter.java
2
请完成以下Java代码
public ResponseEntity<Void> postBook(@RequestBody Book book, UriComponentsBuilder ucBuilder) { LOG.info("creating new book: {}", book); if (book.getName().equals("conflict")){ LOG.info("a book with name " + book.getName() + " already exists"); return new ResponseEntity<>(HttpStatus.CONFLICT); } bookService.insertByBook(book); HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/book/{id}").buildAndExpand(book.getId()).toUri()); return new ResponseEntity<>(headers, HttpStatus.CREATED); } /** * 更新 Book
* 处理 "/update" 的 PUT 请求,用来更新 Book 信息 */ @RequestMapping(value = "/update", method = RequestMethod.PUT) public Book putBook(@RequestBody Book book) { return bookService.update(book); } /** * 删除 Book * 处理 "/book/{id}" 的 GET 请求,用来删除 Book 信息 */ @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE) public Book deleteBook(@PathVariable Long id) { return bookService.delete(id); } }
repos\springboot-learning-example-master\chapter-3-spring-boot-web\src\main\java\demo\springboot\web\BookController.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipperTransportationId implements RepoIdAware { int repoId; @NonNull @JsonCreator public static ShipperTransportationId ofRepoId(final int repoId) { return new ShipperTransportationId(repoId); } @Nullable public static ShipperTransportationId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final ShipperTransportationId shipperTransportationId) {
return shipperTransportationId != null ? shipperTransportationId.getRepoId() : -1; } private ShipperTransportationId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_ShipperTransportation_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\ShipperTransportationId.java
2
请完成以下Java代码
public void setOnClick (String script) { addAttribute ("onclick", script); } /** * The ondblclick event occurs when the pointing device button is double * clicked over an element. This attribute may be used with most elements. * * @param script script */ public void setOnDblClick (String script) { addAttribute ("ondblclick", script); } /** * The onmousedown event occurs when the pointing device button is pressed * over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseDown (String script) { addAttribute ("onmousedown", script); } /** * The onmouseup event occurs when the pointing device button is released * over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseUp (String script) { addAttribute ("onmouseup", script); } /** * The onmouseover event occurs when the pointing device is moved onto an * element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOver (String script) { addAttribute ("onmouseover", script); } /** * The onmousemove event occurs when the pointing device is moved while it * is over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseMove (String script) {
addAttribute ("onmousemove", script); } /** * The onmouseout event occurs when the pointing device is moved away from * an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOut (String script) { addAttribute ("onmouseout", script); } /** * The onkeypress event occurs when a key is pressed and released over an * element. This attribute may be used with most elements. * * @param script script */ public void setOnKeyPress (String script) { addAttribute ("onkeypress", script); } /** * The onkeydown event occurs when a key is pressed down over an element. * This attribute may be used with most elements. * * @param script script */ public void setOnKeyDown (String script) { addAttribute ("onkeydown", script); } /** * The onkeyup event occurs when a key is released over an element. This * attribute may be used with most elements. * * @param script script */ public void setOnKeyUp (String script) { addAttribute ("onkeyup", script); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\acronym.java
1
请完成以下Java代码
public NShortSegment enableJapaneseNameRecognize(boolean enable) { config.japaneseNameRecognize = enable; config.updateNerConfig(); return this; } /** * 是否启用偏移量计算(开启后Term.offset才会被计算) * @param enable * @return */ public NShortSegment enableOffset(boolean enable) { config.offset = enable;
return this; } public NShortSegment enableAllNamedEntityRecognize(boolean enable) { config.nameRecognize = enable; config.japaneseNameRecognize = enable; config.translatedNameRecognize = enable; config.placeRecognize = enable; config.organizationRecognize = enable; config.updateNerConfig(); return this; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\NShort\NShortSegment.java
1
请完成以下Java代码
public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public Integer getAppType() { return appType; } public void setAppType(Integer appType) { this.appType = appType; } public String getActiveConsole() { return activeConsole; } public Date getLastFetch() { return lastFetch; } public void setLastFetch(Date lastFetch) { this.lastFetch = lastFetch; }
public void setActiveConsole(String activeConsole) { this.activeConsole = activeConsole; } public AppInfo toAppInfo() { return new AppInfo(app, appType); } @Override public String toString() { return "ApplicationEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", activeConsole='" + activeConsole + '\'' + ", lastFetch=" + lastFetch + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\ApplicationEntity.java
1
请完成以下Java代码
public abstract class IoParameter { /** * The name of the parameter. The name of the parameter is the * variable name in the target {@link VariableScope}. */ protected String name; /** * The provider of the parameter value. */ protected ParameterValueProvider valueProvider; public IoParameter(String name, ParameterValueProvider valueProvider) { this.name = name; this.valueProvider = valueProvider; } /** * Execute the parameter in a given variable scope. */ public void execute(AbstractVariableScope scope) { execute(scope, scope.getParentVariableScope()); } /** * @param innerScope
* @param outerScope */ protected abstract void execute(AbstractVariableScope innerScope, AbstractVariableScope outerScope); // getters / setters /////////////////////////// public String getName() { return name; } public void setName(String name) { this.name = name; } public ParameterValueProvider getValueProvider() { return valueProvider; } public void setValueProvider(ParameterValueProvider valueProvider) { this.valueProvider = valueProvider; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\mapping\IoParameter.java
1
请完成以下Java代码
public class MongoBsonExample { public static void main(String[] args) { // // 4.1 Connect to cluster (default is localhost:27017) // MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("myDB"); MongoCollection<Document> collection = database.getCollection("employees"); // // 4.2 Insert new document // Document employee = new Document() .append("first_name", "Joe") .append("last_name", "Smith") .append("title", "Java Developer") .append("years_of_service", 3) .append("skills", Arrays.asList("java", "spring", "mongodb")) .append("manager", new Document() .append("first_name", "Sally") .append("last_name", "Johanson")); collection.insertOne(employee); // // 4.3 Find documents // Document query = new Document("last_name", "Smith"); List results = new ArrayList<>(); collection.find(query).into(results); query = new Document("$or", Arrays.asList( new Document("last_name", "Smith"), new Document("first_name", "Joe"))); results = new ArrayList<>(); collection.find(query).into(results); // // 4.4 Update document //
query = new Document( "skills", new Document( "$elemMatch", new Document("$eq", "spring"))); Document update = new Document( "$push", new Document("skills", "security")); collection.updateMany(query, update); // // 4.5 Delete documents // query = new Document( "years_of_service", new Document("$lt", 0)); collection.deleteMany(query); } }
repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\MongoBsonExample.java
1
请完成以下Java代码
public void setRequestOptionsRepository(PublicKeyCredentialRequestOptionsRepository requestOptionsRepository) { Assert.notNull(requestOptionsRepository, "requestOptionsRepository cannot be null"); this.requestOptionsRepository = requestOptionsRepository; } /** * Adapts a {@link GenericHttpMessageConverter} to a * {@link SmartHttpMessageConverter}. * * @param <T> The type * @author Rob Winch * @since 7.0 */ private static final class GenericHttpMessageConverterAdapter<T> extends AbstractSmartHttpMessageConverter<T> { private final GenericHttpMessageConverter<T> delegate; private GenericHttpMessageConverterAdapter(GenericHttpMessageConverter<T> delegate) { Assert.notNull(delegate, "delegate cannot be null"); this.delegate = delegate; } @Override public boolean canRead(ResolvableType type, @Nullable MediaType mediaType) { Class<?> clazz = type.resolve(); return (clazz != null) ? canRead(clazz, mediaType) : canRead(mediaType); } @Override public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) { return this.delegate.canRead(clazz, mediaType); } @Override public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) { return this.delegate.canWrite(clazz, mediaType); } @Override public List<MediaType> getSupportedMediaTypes() {
return this.delegate.getSupportedMediaTypes(); } @Override public List<MediaType> getSupportedMediaTypes(Class<?> clazz) { return this.delegate.getSupportedMediaTypes(clazz); } @Override protected void writeInternal(T t, ResolvableType type, HttpOutputMessage outputMessage, @Nullable Map<String, Object> hints) throws IOException, HttpMessageNotWritableException { this.delegate.write(t, null, outputMessage); } @Override public T read(ResolvableType type, HttpInputMessage inputMessage, @Nullable Map<String, Object> hints) throws IOException, HttpMessageNotReadableException { return this.delegate.read(type.getType(), null, inputMessage); } @Override public boolean canWrite(ResolvableType targetType, Class<?> valueClass, @Nullable MediaType mediaType) { return this.delegate.canWrite(targetType.getType(), valueClass, mediaType); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\WebAuthnAuthenticationFilter.java
1
请在Spring Boot框架中完成以下Java代码
public boolean removeByTenantIdAndKey(UUID tenantId, String key) { if (adminSettingsRepository.existsByTenantIdAndKey(tenantId, key)) { adminSettingsRepository.deleteByTenantIdAndKey(tenantId, key); return true; } return false; } @Override @Transactional public void removeByTenantId(UUID tenantId) { adminSettingsRepository.deleteByTenantId(tenantId); } @Override public PageData<AdminSettings> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(adminSettingsRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); }
@Override protected Class<AdminSettingsEntity> getEntityClass() { return AdminSettingsEntity.class; } @Override protected JpaRepository<AdminSettingsEntity, UUID> getRepository() { return adminSettingsRepository; } @Override public EntityType getEntityType() { return EntityType.ADMIN_SETTINGS; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\settings\JpaAdminSettingsDao.java
2
请完成以下Java代码
public static DistributionDetail castOrNull(@Nullable final BusinessCaseDetail businessCaseDetail) { final boolean canBeCast = businessCaseDetail instanceof DistributionDetail; if (canBeCast) { return cast(businessCaseDetail); } return null; } public static DistributionDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail) { return (DistributionDetail)businessCaseDetail; } @Override public CandidateBusinessCase getCandidateBusinessCase() { return CandidateBusinessCase.DISTRIBUTION; } public BusinessCaseDetail withPPOrderId(@Nullable final PPOrderId newPPOrderId) { final PPOrderRef ppOrderRefNew = PPOrderRef.withPPOrderId(forwardPPOrderRef, newPPOrderId); if (Objects.equals(this.forwardPPOrderRef, ppOrderRefNew)) {
return this; } return toBuilder().forwardPPOrderRef(ppOrderRefNew).build(); } public DistributionDetail withDdOrderCandidateId(final int ddOrderCandidateIdNew) { return withDDOrderRef(DDOrderRef.withDdOrderCandidateId(ddOrderRef, ddOrderCandidateIdNew)); } private DistributionDetail withDDOrderRef(final DDOrderRef ddOrderRefNew) { return Objects.equals(this.ddOrderRef, ddOrderRefNew) ? this : toBuilder().ddOrderRef(ddOrderRefNew).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\DistributionDetail.java
1
请完成以下Java代码
public class InterestType1Choice { @XmlElement(name = "Cd") @XmlSchemaType(name = "string") protected InterestType1Code cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link InterestType1Code } * */ public InterestType1Code getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link InterestType1Code } * */ public void setCd(InterestType1Code value) { this.cd = value; } /**
* Gets the value of the prtry property. * * @return * possible object is * {@link String } * */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = 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\InterestType1Choice.java
1
请完成以下Java代码
public String getReleaseNo () { return (String)get_Value(COLUMNNAME_ReleaseNo); } /** Set Script. @param Script Dynamic Java Language Script to calculate result */ public void setScript (byte[] Script) { set_ValueNoCheck (COLUMNNAME_Script, Script); } /** Get Script. @return Dynamic Java Language Script to calculate result */ public byte[] getScript () { return (byte[])get_Value(COLUMNNAME_Script); } /** Set Roll the Script. @param ScriptRoll Roll the Script */ public void setScriptRoll (String ScriptRoll) { set_Value (COLUMNNAME_ScriptRoll, ScriptRoll); } /** Get Roll the Script. @return Roll the Script */ public String getScriptRoll () { return (String)get_Value(COLUMNNAME_ScriptRoll); } /** Status AD_Reference_ID=53239 */ public static final int STATUS_AD_Reference_ID=53239; /** In Progress = IP */ public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; /** Error = ER */ public static final String STATUS_Error = "ER";
/** Set Status. @param Status Status of the currently running check */ public void setStatus (String Status) { set_ValueNoCheck (COLUMNNAME_Status, Status); } /** Get Status. @return Status of the currently running check */ public String getStatus () { return (String)get_Value(COLUMNNAME_Status); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationScript.java
1
请完成以下Java代码
public boolean hasAtLeastOneValidICS() { return _hasAtLeastOneValidICS; } /** * Checks if given invoice candidate is amount based invoicing (i.e. NOT quantity based invoicing). * <p> * TODO: find a better way to track this. Consider having a field in C_Invoice_Candidate. * <p> * To track where it's used, search also for {@link InvalidQtyForPartialAmtToInvoiceException}. */ private boolean isAmountBasedInvoicing(final I_C_Invoice_Candidate cand) { // We can consider manual invoices as amount based invoices if (cand.isManual())
{ return true; } // We can consider those candidates which have a SplitAmt set to be amount based invoices final BigDecimal splitAmt = cand.getSplitAmt(); if (splitAmt.signum() != 0) { return true; } // More ideas to check: // * UOM shall be stuck?! return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\InvoiceCandidateWithInOutLineAggregator.java
1
请在Spring Boot框架中完成以下Java代码
public JdbcTokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Bean protected AuthorizationCodeServices authorizationCodeServices() { return new JdbcAuthorizationCodeServices(dataSource); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.passwordEncoder(passwordEncoder); } /** * We set our authorization storage feature specifying that we would use the * JDBC store for token and authorization code storage.<br> * <br> * * We also attach the {@link AuthenticationManager} so that password grants * can be processed. */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authorizationCodeServices(authorizationCodeServices()) .authenticationManager(auth).tokenStore(tokenStore()) .approvalStoreDisabled(); } /** * Setup the client application which attempts to get access to user's * account after user permission. */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource) .passwordEncoder(passwordEncoder) .withClient("client") .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token","password", "implicit") .authorities("ROLE_CLIENT") .resourceIds("apis") .scopes("read")
.secret("secret") .accessTokenValiditySeconds(300); } /** * Configure the {@link AuthenticationManagerBuilder} with initial * configuration to setup users. * * @author anilallewar * */ @Configuration @Order(Ordered.LOWEST_PRECEDENCE - 20) protected static class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter { @Autowired private DataSource dataSource; /** * Setup 2 users with different roles */ @Override public void init(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.jdbcAuthentication().dataSource(dataSource).withUser("dave") .password("secret").roles("USER"); auth.jdbcAuthentication().dataSource(dataSource).withUser("anil") .password("password").roles("ADMIN"); // @formatter:on } } }
repos\spring-boot-microservices-master\auth-server\src\main\java\com\rohitghatol\microservice\auth\config\OAuthConfiguration.java
2
请完成以下Java代码
public void setStartTime (java.sql.Timestamp StartTime) { set_Value (COLUMNNAME_StartTime, StartTime); } /** Get Startdatum. @return Startdatum */ @Override public java.sql.Timestamp getStartTime () { return (java.sql.Timestamp)get_Value(COLUMNNAME_StartTime); } /** Set Summary. @param Summary Textual summary of this request */ @Override public void setSummary (java.lang.String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ @Override public java.lang.String getSummary () { return (java.lang.String)get_Value(COLUMNNAME_Summary); } /** * TaskStatus AD_Reference_ID=366 * Reference name: R_Request TaskStatus */ public static final int TASKSTATUS_AD_Reference_ID=366; /** 0% Not Started = 0 */ public static final String TASKSTATUS_0NotStarted = "0"; /** 100% Complete = D */ public static final String TASKSTATUS_100Complete = "D";
/** 20% Started = 2 */ public static final String TASKSTATUS_20Started = "2"; /** 80% Nearly Done = 8 */ public static final String TASKSTATUS_80NearlyDone = "8"; /** 40% Busy = 4 */ public static final String TASKSTATUS_40Busy = "4"; /** 60% Good Progress = 6 */ public static final String TASKSTATUS_60GoodProgress = "6"; /** 90% Finishing = 9 */ public static final String TASKSTATUS_90Finishing = "9"; /** 95% Almost Done = A */ public static final String TASKSTATUS_95AlmostDone = "A"; /** 99% Cleaning up = C */ public static final String TASKSTATUS_99CleaningUp = "C"; /** Set Task Status. @param TaskStatus Status of the Task */ @Override public void setTaskStatus (java.lang.String TaskStatus) { set_Value (COLUMNNAME_TaskStatus, TaskStatus); } /** Get Task Status. @return Status of the Task */ @Override public java.lang.String getTaskStatus () { return (java.lang.String)get_Value(COLUMNNAME_TaskStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Request.java
1
请完成以下Java代码
protected String getDiagramResourceForProcess(String bpmnFileResource, String processKey, Map<String, ResourceEntity> resources) { for (String diagramSuffix : DIAGRAM_SUFFIXES) { String diagramForBpmnFileResource = getBpmnFileImageResourceName(bpmnFileResource, diagramSuffix); String processDiagramResource = getProcessImageResourceName(bpmnFileResource, processKey, diagramSuffix); if (resources.containsKey(processDiagramResource)) { return processDiagramResource; } else if (resources.containsKey(diagramForBpmnFileResource)) { return diagramForBpmnFileResource; } } return null; } protected String getBpmnFileImageResourceName(String bpmnFileResource, String diagramSuffix) { String bpmnFileResourceBase = stripBpmnFileSuffix(bpmnFileResource); return bpmnFileResourceBase + diagramSuffix; } protected String getProcessImageResourceName(String bpmnFileResource, String processKey, String diagramSuffix) { String bpmnFileResourceBase = stripBpmnFileSuffix(bpmnFileResource); return bpmnFileResourceBase + processKey + "." + diagramSuffix; } protected String stripBpmnFileSuffix(String bpmnFileResource) { for (String suffix : BPMN_RESOURCE_SUFFIXES) { if (bpmnFileResource.endsWith(suffix)) { return bpmnFileResource.substring(0, bpmnFileResource.length() - suffix.length()); } } return bpmnFileResource; } protected void createResource(String name, byte[] bytes, DeploymentEntity deploymentEntity) { ResourceEntity resource = new ResourceEntity(); resource.setName(name); resource.setBytes(bytes); resource.setDeploymentId(deploymentEntity.getId()); // Mark the resource as 'generated' resource.setGenerated(true); Context .getCommandContext() .getDbSqlSession() .insert(resource); } protected boolean isBpmnResource(String resourceName) {
for (String suffix : BPMN_RESOURCE_SUFFIXES) { if (resourceName.endsWith(suffix)) { return true; } } return false; } public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public BpmnParser getBpmnParser() { return bpmnParser; } public void setBpmnParser(BpmnParser bpmnParser) { this.bpmnParser = bpmnParser; } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeployer.java
1
请完成以下Java代码
public void setMailServerUseTls(boolean mailServerUseTls) { this.mailServerUseTls = mailServerUseTls; } public List<String> getCustomMybatisMappers() { return customMybatisMappers; } public void setCustomMybatisMappers(List<String> customMyBatisMappers) { this.customMybatisMappers = customMyBatisMappers; } public List<String> getCustomMybatisXMLMappers() { return customMybatisXMLMappers; } public void setCustomMybatisXMLMappers(List<String> customMybatisXMLMappers) { this.customMybatisXMLMappers = customMybatisXMLMappers; } public boolean isUseStrongUuids() { return useStrongUuids; } public void setUseStrongUuids(boolean useStrongUuids) { this.useStrongUuids = useStrongUuids; } public boolean isCopyVariablesToLocalForTasks() { return copyVariablesToLocalForTasks; } public void setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) { this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks; } public String getDeploymentMode() { return deploymentMode; } public void setDeploymentMode(String deploymentMode) { this.deploymentMode = deploymentMode; } public boolean isSerializePOJOsInVariablesToJson() { return serializePOJOsInVariablesToJson; } public void setSerializePOJOsInVariablesToJson(boolean serializePOJOsInVariablesToJson) { this.serializePOJOsInVariablesToJson = serializePOJOsInVariablesToJson; } public String getJavaClassFieldForJackson() { return javaClassFieldForJackson; }
public void setJavaClassFieldForJackson(String javaClassFieldForJackson) { this.javaClassFieldForJackson = javaClassFieldForJackson; } public Integer getProcessDefinitionCacheLimit() { return processDefinitionCacheLimit; } public void setProcessDefinitionCacheLimit(Integer processDefinitionCacheLimit) { this.processDefinitionCacheLimit = processDefinitionCacheLimit; } public String getProcessDefinitionCacheName() { return processDefinitionCacheName; } public void setProcessDefinitionCacheName(String processDefinitionCacheName) { this.processDefinitionCacheName = processDefinitionCacheName; } public void setDisableExistingStartEventSubscriptions(boolean disableExistingStartEventSubscriptions) { this.disableExistingStartEventSubscriptions = disableExistingStartEventSubscriptions; } public boolean shouldDisableExistingStartEventSubscriptions() { return disableExistingStartEventSubscriptions; } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\ActivitiProperties.java
1
请完成以下Java代码
public KeyName[] getLowCardinalityKeyNames() { return DataLoaderLowCardinalityKeyNames.values(); } @Override public KeyName[] getHighCardinalityKeyNames() { return DataLoaderHighCardinalityKeyNames.values(); } }; public enum ExecutionRequestLowCardinalityKeyNames implements KeyName { /** * Outcome of the GraphQL request. */ OUTCOME { @Override public String asString() { return "graphql.outcome"; } }, /** * GraphQL {@link graphql.language.OperationDefinition.Operation Operation type}. */ OPERATION_TYPE { @Override public String asString() { return "graphql.operation.type"; } } } public enum ExecutionRequestHighCardinalityKeyNames implements KeyName { /** * GraphQL Operation name. */ OPERATION_NAME { @Override public String asString() { return "graphql.operation.name"; } }, /** * {@link graphql.execution.ExecutionId} of the GraphQL request. */ EXECUTION_ID { @Override public String asString() { return "graphql.execution.id"; } } } public enum DataFetcherLowCardinalityKeyNames implements KeyName { /** * Outcome of the GraphQL data fetching operation. */ OUTCOME { @Override public String asString() { return "graphql.outcome"; } }, /** * Name of the field being fetched. */ FIELD_NAME { @Override public String asString() { return "graphql.field.name"; } }, /** * Class name of the data fetching error. */ ERROR_TYPE { @Override
public String asString() { return "graphql.error.type"; } } } public enum DataFetcherHighCardinalityKeyNames implements KeyName { /** * Path to the field being fetched. */ FIELD_PATH { @Override public String asString() { return "graphql.field.path"; } } } public enum DataLoaderLowCardinalityKeyNames implements KeyName { /** * Class name of the data fetching error. */ ERROR_TYPE { @Override public String asString() { return "graphql.error.type"; } }, /** * {@link DataLoader#getName()} of the data loader. */ LOADER_NAME { @Override public String asString() { return "graphql.loader.name"; } }, /** * Outcome of the GraphQL data fetching operation. */ OUTCOME { @Override public String asString() { return "graphql.outcome"; } } } public enum DataLoaderHighCardinalityKeyNames implements KeyName { /** * Size of the list of elements returned by the data loading operation. */ LOADER_SIZE { @Override public String asString() { return "graphql.loader.size"; } } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\GraphQlObservationDocumentation.java
1
请完成以下Java代码
public I_C_Tax getC_Tax() throws RuntimeException { return (I_C_Tax)MTable.get(getCtx(), I_C_Tax.Table_Name) .getPO(getC_Tax_ID(), get_TrxName()); } /** Set Tax. @param C_Tax_ID Tax identifier */ public void setC_Tax_ID (int C_Tax_ID) { if (C_Tax_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Tax_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Tax_ID, Integer.valueOf(C_Tax_ID)); } /** Get Tax. @return Tax identifier */ public int getC_Tax_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Tax_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Tax ZIP. @param C_TaxPostal_ID Tax Postal/ZIP */ public void setC_TaxPostal_ID (int C_TaxPostal_ID) { if (C_TaxPostal_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxPostal_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxPostal_ID, Integer.valueOf(C_TaxPostal_ID)); } /** Get Tax ZIP. @return Tax Postal/ZIP */ public int getC_TaxPostal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxPostal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ZIP. @param Postal Postal code */ public void setPostal (String Postal) { set_Value (COLUMNNAME_Postal, Postal); } /** Get ZIP.
@return Postal code */ public String getPostal () { return (String)get_Value(COLUMNNAME_Postal); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getPostal()); } /** Set ZIP To. @param Postal_To Postal code to */ public void setPostal_To (String Postal_To) { set_Value (COLUMNNAME_Postal_To, Postal_To); } /** Get ZIP To. @return Postal code to */ public String getPostal_To () { return (String)get_Value(COLUMNNAME_Postal_To); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxPostal.java
1
请在Spring Boot框架中完成以下Java代码
class RSocketSecurityConfiguration { private static final String BEAN_NAME_PREFIX = "org.springframework.security.config.annotation.rsocket.RSocketSecurityConfiguration."; private static final String RSOCKET_SECURITY_BEAN_NAME = BEAN_NAME_PREFIX + "rsocketSecurity"; private ReactiveAuthenticationManager authenticationManager; private ReactiveUserDetailsService reactiveUserDetailsService; private PasswordEncoder passwordEncoder; private ObjectPostProcessor<ReactiveAuthenticationManager> postProcessor = ObjectPostProcessor.identity(); @Autowired(required = false) void setAuthenticationManager(ReactiveAuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired(required = false) void setUserDetailsService(ReactiveUserDetailsService userDetailsService) { this.reactiveUserDetailsService = userDetailsService; } @Autowired(required = false) void setPasswordEncoder(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } @Autowired(required = false) void setAuthenticationManagerPostProcessor( Map<String, ObjectPostProcessor<ReactiveAuthenticationManager>> postProcessors) { if (postProcessors.size() == 1) { this.postProcessor = postProcessors.values().iterator().next(); } this.postProcessor = postProcessors.get("rSocketAuthenticationManagerPostProcessor"); } @Bean(name = RSOCKET_SECURITY_BEAN_NAME) @Scope("prototype") RSocketSecurity rsocketSecurity(ApplicationContext context) { RSocketSecurity security = new RSocketSecurity().authenticationManager(authenticationManager()); security.setApplicationContext(context);
return security; } private ReactiveAuthenticationManager authenticationManager() { if (this.authenticationManager != null) { return this.authenticationManager; } if (this.reactiveUserDetailsService != null) { UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager( this.reactiveUserDetailsService); if (this.passwordEncoder != null) { manager.setPasswordEncoder(this.passwordEncoder); } return this.postProcessor.postProcess(manager); } return null; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\rsocket\RSocketSecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class OssServiceImpl implements OssService { private static final Logger LOGGER = LoggerFactory.getLogger(OssServiceImpl.class); @Value("${aliyun.oss.policy.expire}") private int ALIYUN_OSS_EXPIRE; @Value("${aliyun.oss.maxSize}") private int ALIYUN_OSS_MAX_SIZE; @Value("${aliyun.oss.callback}") private String ALIYUN_OSS_CALLBACK; @Value("${aliyun.oss.bucketName}") private String ALIYUN_OSS_BUCKET_NAME; @Value("${aliyun.oss.endpoint}") private String ALIYUN_OSS_ENDPOINT; @Value("${aliyun.oss.dir.prefix}") private String ALIYUN_OSS_DIR_PREFIX; @Autowired private OSSClient ossClient; /** * 签名生成 */ @Override public OssPolicyResult policy() { OssPolicyResult result = new OssPolicyResult(); // 存储目录 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dir = ALIYUN_OSS_DIR_PREFIX+sdf.format(new Date()); // 签名有效期 long expireEndTime = System.currentTimeMillis() + ALIYUN_OSS_EXPIRE * 1000; Date expiration = new Date(expireEndTime); // 文件大小 long maxSize = ALIYUN_OSS_MAX_SIZE * 1024 * 1024; // 回调 OssCallbackParam callback = new OssCallbackParam(); callback.setCallbackUrl(ALIYUN_OSS_CALLBACK); callback.setCallbackBody("filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}"); callback.setCallbackBodyType("application/x-www-form-urlencoded"); // 提交节点 String action = "http://" + ALIYUN_OSS_BUCKET_NAME + "." + ALIYUN_OSS_ENDPOINT; try { PolicyConditions policyConds = new PolicyConditions(); policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir); String postPolicy = ossClient.generatePostPolicy(expiration, policyConds); byte[] binaryData = postPolicy.getBytes("utf-8"); String policy = BinaryUtil.toBase64String(binaryData); String signature = ossClient.calculatePostSignature(postPolicy); String callbackData = BinaryUtil.toBase64String(JSONUtil.parse(callback).toString().getBytes("utf-8")); // 返回结果 result.setAccessKeyId(ossClient.getCredentialsProvider().getCredentials().getAccessKeyId()); result.setPolicy(policy); result.setSignature(signature); result.setDir(dir); result.setCallback(callbackData); result.setHost(action); } catch (Exception e) { LOGGER.error("签名生成失败", e); } return result; } @Override public OssCallbackResult callback(HttpServletRequest request) { OssCallbackResult result= new OssCallbackResult(); String filename = request.getParameter("filename"); filename = "http://".concat(ALIYUN_OSS_BUCKET_NAME).concat(".").concat(ALIYUN_OSS_ENDPOINT).concat("/").concat(filename); result.setFilename(filename); result.setSize(request.getParameter("size")); result.setMimeType(request.getParameter("mimeType")); result.setWidth(request.getParameter("width")); result.setHeight(request.getParameter("height")); return result; } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\OssServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class HistoricIdentityLinkResponse { protected String type; protected String userId; protected String groupId; protected String taskId; protected String taskUrl; protected String caseInstanceId; protected String caseInstanceUrl; @ApiModelProperty(example = "participant") public String getType() { return type; } public void setType(String type) { this.type = type; } @ApiModelProperty(example = "kermit") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @ApiModelProperty(example = "sales") public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @ApiModelProperty(example = "null") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "null") public String getTaskUrl() { return taskUrl;
} public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @ApiModelProperty(example = "5") public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/5") public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricIdentityLinkResponse.java
2
请完成以下Java代码
private void buildDescription(StringBuilder description, @Nullable ConfigurationProperty property) { if (property != null) { description.append(String.format("%n Property: %s", property.getName())); description.append(String.format("%n Value: \"%s\"", property.getValue())); description.append(String.format("%n Origin: %s", property.getOrigin())); } } private String getMessage(BindException cause) { Throwable rootCause = getRootCause(cause.getCause()); ConversionFailedException conversionFailure = findCause(cause, ConversionFailedException.class); if (conversionFailure != null) { String message = "failed to convert " + conversionFailure.getSourceType() + " to " + conversionFailure.getTargetType(); if (rootCause != null) { message += " (caused by " + getExceptionTypeAndMessage(rootCause) + ")"; } return message; } if (rootCause != null && StringUtils.hasText(rootCause.getMessage())) { return getExceptionTypeAndMessage(rootCause); } return getExceptionTypeAndMessage(cause); } private @Nullable Throwable getRootCause(@Nullable Throwable cause) { Throwable rootCause = cause; while (rootCause != null && rootCause.getCause() != null) { rootCause = rootCause.getCause(); } return rootCause; } private String getExceptionTypeAndMessage(Throwable ex) { String message = ex.getMessage(); return ex.getClass().getName() + (StringUtils.hasText(message) ? ": " + message : ""); } private FailureAnalysis getFailureAnalysis(String description, BindException cause, @Nullable FailureAnalysis missingParametersAnalysis) { StringBuilder action = new StringBuilder("Update your application's configuration"); Collection<String> validValues = findValidValues(cause); if (!validValues.isEmpty()) { action.append(String.format(". The following values are valid:%n"));
validValues.forEach((value) -> action.append(String.format("%n %s", value))); } if (missingParametersAnalysis != null) { action.append(String.format("%n%n%s", missingParametersAnalysis.getAction())); } return new FailureAnalysis(description, action.toString(), cause); } private Collection<String> findValidValues(BindException ex) { ConversionFailedException conversionFailure = findCause(ex, ConversionFailedException.class); if (conversionFailure != null) { Object[] enumConstants = conversionFailure.getTargetType().getType().getEnumConstants(); if (enumConstants != null) { return Stream.of(enumConstants).map(Object::toString).collect(Collectors.toCollection(TreeSet::new)); } } return Collections.emptySet(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\BindFailureAnalyzer.java
1
请完成以下Java代码
protected void doSetRollbackOnly(DefaultTransactionStatus status) { RabbitTransactionObject txObject = (RabbitTransactionObject) status.getTransaction(); RabbitResourceHolder resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.setRollbackOnly(); } } @Override protected void doCleanupAfterCompletion(Object transaction) { RabbitTransactionObject txObject = (RabbitTransactionObject) transaction; TransactionSynchronizationManager.unbindResource(getResourceFactory()); RabbitResourceHolder resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.closeAll(); resourceHolder.clear(); } } /** * Rabbit transaction object, representing a RabbitResourceHolder. Used as transaction object by * RabbitTransactionManager. * @see RabbitResourceHolder */ private static class RabbitTransactionObject implements SmartTransactionObject { private @Nullable RabbitResourceHolder resourceHolder; RabbitTransactionObject() { } public void setResourceHolder(@Nullable RabbitResourceHolder resourceHolder) { this.resourceHolder = resourceHolder; }
public @Nullable RabbitResourceHolder getResourceHolder() { return this.resourceHolder; } @Override public boolean isRollbackOnly() { return this.resourceHolder != null && this.resourceHolder.isRollbackOnly(); } @Override public void flush() { // no-op } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\transaction\RabbitTransactionManager.java
1
请完成以下Java代码
public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setData_Export_Audit_ID (final int Data_Export_Audit_ID) { if (Data_Export_Audit_ID < 1) set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_ID, null); else set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_ID, Data_Export_Audit_ID); } @Override public int getData_Export_Audit_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_ID); } @Override public org.compiere.model.I_Data_Export_Audit getData_Export_Audit_Parent() { return get_ValueAsPO(COLUMNNAME_Data_Export_Audit_Parent_ID, org.compiere.model.I_Data_Export_Audit.class); } @Override public void setData_Export_Audit_Parent(final org.compiere.model.I_Data_Export_Audit Data_Export_Audit_Parent) { set_ValueFromPO(COLUMNNAME_Data_Export_Audit_Parent_ID, org.compiere.model.I_Data_Export_Audit.class, Data_Export_Audit_Parent);
} @Override public void setData_Export_Audit_Parent_ID (final int Data_Export_Audit_Parent_ID) { if (Data_Export_Audit_Parent_ID < 1) set_Value (COLUMNNAME_Data_Export_Audit_Parent_ID, null); else set_Value (COLUMNNAME_Data_Export_Audit_Parent_ID, Data_Export_Audit_Parent_ID); } @Override public int getData_Export_Audit_Parent_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Parent_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit.java
1
请在Spring Boot框架中完成以下Java代码
public void setCode(String value) { this.code = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value;
} /** * Gets the value of the unit property. * * @return * possible object is * {@link String } * */ public String getUnit() { return unit; } /** * Sets the value of the unit property. * * @param value * allowed object is * {@link String } * */ public void setUnit(String value) { this.unit = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\FeatureType.java
2
请在Spring Boot框架中完成以下Java代码
AnnotationMBeanExporter mbeanExporter(ObjectNamingStrategy namingStrategy, BeanFactory beanFactory) { AnnotationMBeanExporter exporter = new AnnotationMBeanExporter(); exporter.setRegistrationPolicy(this.properties.getRegistrationPolicy()); exporter.setNamingStrategy(namingStrategy); String serverBean = this.properties.getServer(); if (StringUtils.hasLength(serverBean)) { exporter.setServer(beanFactory.getBean(serverBean, MBeanServer.class)); } exporter.setEnsureUniqueRuntimeObjectNames(this.properties.isUniqueNames()); return exporter; } @Bean @ConditionalOnMissingBean(value = ObjectNamingStrategy.class, search = SearchStrategy.CURRENT) ParentAwareNamingStrategy objectNamingStrategy() { ParentAwareNamingStrategy namingStrategy = new ParentAwareNamingStrategy(new AnnotationJmxAttributeSource()); String defaultDomain = this.properties.getDefaultDomain(); if (StringUtils.hasLength(defaultDomain)) { namingStrategy.setDefaultDomain(defaultDomain); }
namingStrategy.setEnsureUniqueRuntimeObjectNames(this.properties.isUniqueNames()); return namingStrategy; } @Bean @ConditionalOnMissingBean MBeanServer mbeanServer() { MBeanServerFactoryBean factory = new MBeanServerFactoryBean(); factory.setLocateExistingServerIfPossible(true); factory.afterPropertiesSet(); MBeanServer mBeanServer = factory.getObject(); Assert.state(mBeanServer != null, "'mBeanServer' must not be null"); return mBeanServer; } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\jmx\JmxAutoConfiguration.java
2
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_Error[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Error. @param AD_Error_ID Error */ public void setAD_Error_ID (int AD_Error_ID) { if (AD_Error_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Error_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Error_ID, Integer.valueOf(AD_Error_ID)); } /** Get Error. @return Error */ public int getAD_Error_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Error_ID); if (ii == null) return 0; return ii.intValue(); } /** AD_Language AD_Reference_ID=106 */ public static final int AD_LANGUAGE_AD_Reference_ID=106; /** Set Language. @param AD_Language Language for this entity */ public void setAD_Language (String AD_Language) { set_Value (COLUMNNAME_AD_Language, AD_Language); } /** Get Language. @return Language for this entity */ public String getAD_Language () { return (String)get_Value(COLUMNNAME_AD_Language); } /** Set Validation code.
@param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); } /** 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_AD_Error.java
1
请完成以下Java代码
public class LicenseDto { private UUID id; private LocalDateTime startDate; private LocalDateTime endDate; private String licenseType; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public LocalDateTime getStartDate() { return startDate; } public void setStartDate(LocalDateTime startDate) { this.startDate = startDate; } public LocalDateTime getEndDate() { return endDate;
} public void setEndDate(LocalDateTime endDate) { this.endDate = endDate; } public String getLicenseType() { return licenseType; } public void setLicenseType(String licenseType) { this.licenseType = licenseType; } }
repos\tutorials-master\mapstruct\src\main\java\com\baeldung\expression\dto\LicenseDto.java
1
请完成以下Java代码
public class M_ReceiptSchedule_ChangeDatePromised_OverrideAndPOReference extends JavaProcess implements IProcessPrecondition { private final IReceiptScheduleDAO receiptScheduleDAO = Services.get(IReceiptScheduleDAO.class); private final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class); private static final AdMessageKey MSG_NO_UNPROCESSED_LINES = AdMessageKey.of("receiptschedule.noUnprocessedLines"); @Param(parameterName = I_M_ReceiptSchedule.COLUMNNAME_DatePromised_Override) private LocalDate datePromisedOverride; @Param(parameterName = I_M_ReceiptSchedule.COLUMNNAME_POReference) private String poReference; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } final boolean someSchedsAreStillNotProcessed = receiptScheduleBL.hasUnProcessedRecords(context.getQueryFilter(I_M_ReceiptSchedule.class)); if (!someSchedsAreStillNotProcessed) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_NO_UNPROCESSED_LINES)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() {
final int selectionCount = receiptScheduleDAO .createQueryForReceiptScheduleSelection(getCtx(), getProcessInfo().getQueryFilterOrElseFalse()) .create() .createSelection(getPinstanceId()); if (selectionCount <= 0) { throw new AdempiereException(MSG_NO_UNPROCESSED_LINES) .markAsUserValidationError(); } final int updatedCnt = receiptScheduleBL.updateDatePromisedOverrideAndPOReference(getPinstanceId(), datePromisedOverride, poReference); addLog("Updated {} M_ReceiptSchedules", updatedCnt); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_ChangeDatePromised_OverrideAndPOReference.java
1
请完成以下Java代码
protected void ensureProcessInstanceExist(String processInstanceId, ExecutionEntity processInstance) { if (processInstance == null) { throw LOG.processInstanceDoesNotExist(processInstanceId); } } protected ProcessInstanceModificationBuilderImpl createProcessInstanceModificationBuilder( String processInstanceId, CommandContext commandContext) { ProcessInstanceModificationBuilderImpl processInstanceModificationBuilder = new ProcessInstanceModificationBuilderImpl(commandContext, processInstanceId); List<AbstractProcessInstanceModificationCommand> operations = processInstanceModificationBuilder.getModificationOperations(); ActivityInstance activityInstanceTree = null; for (AbstractProcessInstanceModificationCommand instruction : builder.getInstructions()) { instruction.setProcessInstanceId(processInstanceId); if (!(instruction instanceof ActivityCancellationCmd) || !((ActivityCancellationCmd)instruction).isCancelCurrentActiveActivityInstances()) { operations.add(instruction);
} else { if (activityInstanceTree == null) { activityInstanceTree = commandContext.runWithoutAuthorization(new GetActivityInstanceCmd(processInstanceId)); } ActivityCancellationCmd cancellationInstruction = (ActivityCancellationCmd) instruction; List<AbstractInstanceCancellationCmd> cmds = cancellationInstruction.createActivityInstanceCancellations(activityInstanceTree, commandContext); operations.addAll(cmds); } } return processInstanceModificationBuilder; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ProcessInstanceModificationCmd.java
1
请在Spring Boot框架中完成以下Java代码
public final class Article { @Id @GeneratedValue private Long id; private String title; private String content; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title;
} public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
repos\tutorials-master\spring-web-modules\spring-rest-shell\src\main\java\com\baeldung\acticle\Article.java
2
请完成以下Java代码
public void setAD_Issue_ID (final int AD_Issue_ID) { if (AD_Issue_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, AD_Issue_ID); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } /** * ExportStatus AD_Reference_ID=541161 * Reference name: API_ExportStatus */ public static final int EXPORTSTATUS_AD_Reference_ID=541161; /** PENDING = PENDING */ public static final String EXPORTSTATUS_PENDING = "PENDING"; /** EXPORTED = EXPORTED */ public static final String EXPORTSTATUS_EXPORTED = "EXPORTED"; /** EXPORTED_AND_FORWARDED = EXPORTED_AND_FORWARDED */ public static final String EXPORTSTATUS_EXPORTED_AND_FORWARDED = "EXPORTED_AND_FORWARDED"; /** EXPORTED_FORWARD_ERROR = EXPORTED_FORWARD_ERROR */ public static final String EXPORTSTATUS_EXPORTED_FORWARD_ERROR = "EXPORTED_FORWARD_ERROR"; /** EXPORT_ERROR = EXPORT_ERROR */ public static final String EXPORTSTATUS_EXPORT_ERROR = "EXPORT_ERROR"; /** DONT_EXPORT = DONT_EXPORT */ public static final String EXPORTSTATUS_DONT_EXPORT = "DONT_EXPORT"; @Override public void setExportStatus (final java.lang.String ExportStatus) { set_Value (COLUMNNAME_ExportStatus, ExportStatus); } @Override public java.lang.String getExportStatus() { return get_ValueAsString(COLUMNNAME_ExportStatus); } @Override public void setM_ReceiptSchedule_ExportAudit_ID (final int M_ReceiptSchedule_ExportAudit_ID) { if (M_ReceiptSchedule_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID, M_ReceiptSchedule_ExportAudit_ID); } @Override public int getM_ReceiptSchedule_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID); } @Override public de.metas.inoutcandidate.model.I_M_ReceiptSchedule getM_ReceiptSchedule() { return get_ValueAsPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class); }
@Override public void setM_ReceiptSchedule(final de.metas.inoutcandidate.model.I_M_ReceiptSchedule M_ReceiptSchedule) { set_ValueFromPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class, M_ReceiptSchedule); } @Override public void setM_ReceiptSchedule_ID (final int M_ReceiptSchedule_ID) { if (M_ReceiptSchedule_ID < 1) set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null); else set_Value (COLUMNNAME_M_ReceiptSchedule_ID, M_ReceiptSchedule_ID); } @Override public int getM_ReceiptSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule_ExportAudit.java
1
请完成以下Java代码
public String getLocation() { return locationAttribute.getValue(this); } public void setLocation(String location) { locationAttribute.setValue(this, location); } public String getImportType() { return importTypeAttribute.getValue(this); } public void setImportType(String importType) { importTypeAttribute.setValue(this, importType); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Import.class, CMMN_ELEMENT_IMPORT) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Import>() { public Import newInstance(ModelTypeInstanceContext instanceContext) { return new ImportImpl(instanceContext); } });
namespaceAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAMESPACE) .build(); locationAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_LOCATION) .required() .build(); importTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPORT_TYPE) .required() .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ImportImpl.java
1
请完成以下Java代码
public void setT_Receivables_Acct (int T_Receivables_Acct) { set_Value (COLUMNNAME_T_Receivables_Acct, Integer.valueOf(T_Receivables_Acct)); } /** Get Steuerüberzahlungen. @return Konto für Steuerüberzahlungen */ @Override public int getT_Receivables_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_T_Receivables_Acct); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ValidCombination getT_Revenue_A() { return get_ValueAsPO(COLUMNNAME_T_Revenue_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setT_Revenue_A(org.compiere.model.I_C_ValidCombination T_Revenue_A)
{ set_ValueFromPO(COLUMNNAME_T_Revenue_Acct, org.compiere.model.I_C_ValidCombination.class, T_Revenue_A); } /** Set Erlös Konto. @param T_Revenue_Acct Steuerabhängiges Konto zur Verbuchung Erlöse */ @Override public void setT_Revenue_Acct (int T_Revenue_Acct) { set_Value (COLUMNNAME_T_Revenue_Acct, Integer.valueOf(T_Revenue_Acct)); } /** Get Erlös Konto. @return Steuerabhängiges Konto zur Verbuchung Erlöse */ @Override public int getT_Revenue_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_T_Revenue_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Tax_Acct.java
1
请完成以下Java代码
public int getC_RecurrentPaymentHistory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPaymentHistory_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.banking.model.I_C_RecurrentPaymentLine getC_RecurrentPaymentLine() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_RecurrentPaymentLine_ID, de.metas.banking.model.I_C_RecurrentPaymentLine.class); } @Override public void setC_RecurrentPaymentLine(de.metas.banking.model.I_C_RecurrentPaymentLine C_RecurrentPaymentLine) { set_ValueFromPO(COLUMNNAME_C_RecurrentPaymentLine_ID, de.metas.banking.model.I_C_RecurrentPaymentLine.class, C_RecurrentPaymentLine); } /** Set Recurrent Payment Line. @param C_RecurrentPaymentLine_ID Recurrent Payment Line */ @Override public void setC_RecurrentPaymentLine_ID (int C_RecurrentPaymentLine_ID) { if (C_RecurrentPaymentLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RecurrentPaymentLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RecurrentPaymentLine_ID, Integer.valueOf(C_RecurrentPaymentLine_ID));
} /** Get Recurrent Payment Line. @return Recurrent Payment Line */ @Override public int getC_RecurrentPaymentLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPaymentLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public org.compiere.util.KeyNamePair getKeyNamePair() { return new org.compiere.util.KeyNamePair(get_ID(), String.valueOf(getC_RecurrentPaymentLine_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPaymentHistory.java
1
请完成以下Java代码
public String getExecutionId() { return executionId; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean iswithException() { return withJobException; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<ProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } /** * Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property. */ public String getParentId() { return null; } public boolean isOnlyChildExecutions() { return onlyChildExecutions; } public boolean isOnlyProcessInstanceExecutions() { return onlyProcessInstanceExecutions; } public boolean isOnlySubProcessExecutions() { return onlySubProcessExecutions; } public Date getStartedBefore() {
return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public List<String> getInvolvedGroups() { return involvedGroups; } public ProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) { if (involvedGroups == null || involvedGroups.isEmpty()) { throw new ActivitiIllegalArgumentException("Involved groups list is null or empty."); } if (inOrStatement) { this.currentOrQueryObject.involvedGroups = involvedGroups; } else { this.involvedGroups = involvedGroups; } return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public void setPrefix (final @Nullable java.lang.String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } @Override public java.lang.String getPrefix() { return get_ValueAsString(COLUMNNAME_Prefix); } /** * RestartFrequency AD_Reference_ID=541879 * Reference name: AD_SequenceRestart Frequency */ public static final int RESTARTFREQUENCY_AD_Reference_ID=541879; /** Year = Y */ public static final String RESTARTFREQUENCY_Year = "Y"; /** Month = M */ public static final String RESTARTFREQUENCY_Month = "M"; /** Day = D */ public static final String RESTARTFREQUENCY_Day = "D"; @Override public void setRestartFrequency (final @Nullable java.lang.String RestartFrequency) { set_Value (COLUMNNAME_RestartFrequency, RestartFrequency); } @Override public java.lang.String getRestartFrequency() { return get_ValueAsString(COLUMNNAME_RestartFrequency); } @Override public void setStartNo (final int StartNo) { set_Value (COLUMNNAME_StartNo, StartNo); } @Override public int getStartNo() { return get_ValueAsInt(COLUMNNAME_StartNo); }
@Override public void setSuffix (final @Nullable java.lang.String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } @Override public java.lang.String getSuffix() { return get_ValueAsString(COLUMNNAME_Suffix); } @Override public void setVFormat (final @Nullable java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } @Override public java.lang.String getVFormat() { return get_ValueAsString(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence.java
1
请完成以下Java代码
public class FifoFixedSizeQueue<E> extends AbstractQueue<E> { /** The queued items */ final Object[] items; /** Number of elements in the queue */ int count; public FifoFixedSizeQueue(int capacity) { super(); items = new Object[capacity]; count = 0; } @Override public boolean offer(E e) { if (e == null) { throw new NullPointerException("Queue doesn't allow nulls"); } if (count == items.length) { this.poll(); } this.items[count] = e; count++; return true; } @Override public E poll() { if (count <= 0) { return null; } E item = (E) items[0]; shiftLeft(); count--; return item; } private void shiftLeft() { int i = 1; while (i < items.length) { if (items[i] == null) {
break; } items[i - 1] = items[i]; i++; } } @Override public E peek() { if (count <= 0) { return null; } return (E) items[0]; } @Override public int size() { return count; } @Override public Iterator<E> iterator() { List<E> list = new ArrayList<>(count); for (int i = 0; i < count; i++) { list.add((E) items[i]); } return list.iterator(); } }
repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\fixedsizequeues\FifoFixedSizeQueue.java
1
请在Spring Boot框架中完成以下Java代码
protected void completeTask(Task task, TaskActionRequest actionRequest) { TaskCompletionBuilder taskCompletionBuilder = taskService.createTaskCompletionBuilder(); if (actionRequest.getVariables() != null) { for (RestVariable var : actionRequest.getVariables()) { if (var.getName() == null) { throw new FlowableIllegalArgumentException("Variable name is required"); } Object actualVariableValue = restResponseFactory.getVariableValue(var); if (var.getVariableScope() != null && RestVariable.RestVariableScope.LOCAL.equals(var.getVariableScope())) { taskCompletionBuilder.variableLocal(var.getName(), actualVariableValue); } else { taskCompletionBuilder.variable(var.getName(), actualVariableValue); } } } if (actionRequest.getTransientVariables() != null) { for (RestVariable var : actionRequest.getTransientVariables()) { if (var.getName() == null) { throw new FlowableIllegalArgumentException("Transient variable name is required"); } Object actualVariableValue = restResponseFactory.getVariableValue(var); if (var.getVariableScope() != null && RestVariable.RestVariableScope.LOCAL.equals(var.getVariableScope())) { taskCompletionBuilder.transientVariableLocal(var.getName(), actualVariableValue); } else { taskCompletionBuilder.transientVariable(var.getName(), actualVariableValue);
} } } taskCompletionBuilder .taskId(task.getId()) .formDefinitionId(actionRequest.getFormDefinitionId()) .outcome(actionRequest.getOutcome()) .complete(); } protected void resolveTask(Task task, TaskActionRequest actionRequest) { taskService.resolveTask(task.getId()); } protected void delegateTask(Task task, TaskActionRequest actionRequest) { if (actionRequest.getAssignee() == null) { throw new FlowableIllegalArgumentException("An assignee is required when delegating a task."); } taskService.delegateTask(task.getId(), actionRequest.getAssignee()); } protected void claimTask(Task task, TaskActionRequest actionRequest) { // In case the task is already claimed, a // FlowableTaskAlreadyClaimedException is thrown and converted to // a CONFLICT response by the ExceptionHandlerAdvice taskService.claim(task.getId(), actionRequest.getAssignee()); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskResource.java
2
请完成以下Java代码
public TranslatableStringBuilder appendTemporal( @Nullable final Temporal value, @Nullable final String defaultValueIfNull) { return value != null ? append(TranslatableStrings.temporal(value)) : append(defaultValueIfNull); } public TranslatableStringBuilder appendDateTime(@NonNull final Date value) { return append(TranslatableStrings.dateAndTime(value)); } public TranslatableStringBuilder appendDateTime(@NonNull final Instant value) { return append(DateTimeTranslatableString.ofDateTime(value)); } public TranslatableStringBuilder appendDateTime(@NonNull final ZonedDateTime value) { return append(DateTimeTranslatableString.ofDateTime(value)); } public TranslatableStringBuilder appendTimeZone( @NonNull final ZoneId zoneId, @NonNull final TextStyle textStyle) { return append(TimeZoneTranslatableString.ofZoneId(zoneId, textStyle)); } public TranslatableStringBuilder append(final Boolean value) { if (value == null) { return append("?"); } else { return append(msgBL.getTranslatableMsgText(value)); } } public TranslatableStringBuilder appendADMessage( final AdMessageKey adMessage, final Object... msgParameters) { final ITranslatableString value = msgBL.getTranslatableMsgText(adMessage, msgParameters); return append(value); } @Deprecated public TranslatableStringBuilder appendADMessage(
@NonNull final String adMessage, final Object... msgParameters) { return appendADMessage(AdMessageKey.of(adMessage), msgParameters); } public TranslatableStringBuilder insertFirstADMessage( final AdMessageKey adMessage, final Object... msgParameters) { final ITranslatableString value = msgBL.getTranslatableMsgText(adMessage, msgParameters); return insertFirst(value); } @Deprecated public TranslatableStringBuilder insertFirstADMessage( final String adMessage, final Object... msgParameters) { return insertFirstADMessage(AdMessageKey.of(adMessage), msgParameters); } public TranslatableStringBuilder appendADElement(final String columnName) { final ITranslatableString value = msgBL.translatable(columnName); return append(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TranslatableStringBuilder.java
1
请完成以下Java代码
void add(String key, int value) { Integer f = get(key); if (f == null) f = 0; f += value; d.put(key, f); total += value; } void add(int value, char... key) { Integer f = d.get(key); if (f == null) f = 0; f += value; d.put(key, f); total += value; } public void add(int value, char[]... keyArray) { add(convert(keyArray), value); } public void add(int value, Collection<char[]> keyArray) { add(convert(keyArray), value); } private String convert(Collection<char[]> keyArray) { StringBuilder sbKey = new StringBuilder(keyArray.size() * 2); for (char[] key : keyArray) { sbKey.append(key[0]); sbKey.append(key[1]); } return sbKey.toString(); }
static private String convert(char[]... keyArray) { StringBuilder sbKey = new StringBuilder(keyArray.length * 2); for (char[] key : keyArray) { sbKey.append(key[0]); sbKey.append(key[1]); } return sbKey.toString(); } @Override public void save(DataOutputStream out) throws Exception { out.writeInt(total); Integer[] valueArray = d.getValueArray(new Integer[0]); out.writeInt(valueArray.length); for (Integer v : valueArray) { out.writeInt(v); } d.save(out); } @Override public boolean load(ByteArray byteArray) { total = byteArray.nextInt(); int size = byteArray.nextInt(); Integer[] valueArray = new Integer[size]; for (int i = 0; i < valueArray.length; ++i) { valueArray[i] = byteArray.nextInt(); } d.load(byteArray, valueArray); return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\trigram\frequency\Probability.java
1
请在Spring Boot框架中完成以下Java代码
public void setPassword(String password) { this.password = password; } public String getDataType() { return dataType; } public String getServerAddr() { return serverAddr; } public String getNamespace() { return namespace; }
public String getDataId() { return dataId; } public String getRouteGroup() { return routeGroup; } public String getUsername() { return username; } public String getPassword() { return password; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\config\GatewayRoutersConfig.java
2
请完成以下Java代码
public Long getID() { return ID; } public void setID(Long ID) { this.ID = ID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() {
return age; } public void setAge(Integer age) { this.age = age; } public LocalDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(LocalDateTime createdDate) { this.createdDate = createdDate; } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\customer\Customer.java
1
请完成以下Java代码
private static URI extractURI(final Resource resource) { try { return resource.getURI(); } catch (IOException e) { return null; } } private int getInsertBatchSize() { return sysConfigBL.getIntValue(SYSCONFIG_InsertBatchSize, -1); } private PInstanceId getOrCreateRecordsToImportSelectionId() { if (_recordsToImportSelectionId == null) { final ImportTableDescriptor importTableDescriptor = importFormat.getImportTableDescriptor(); final DataImportRunId dataImportRunId = getOrCreateDataImportRunId(); final IQuery<Object> query = queryBL.createQueryBuilder(importTableDescriptor.getTableName()) .addEqualsFilter(ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID, dataImportRunId) .addEqualsFilter(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg, null) .create(); _recordsToImportSelectionId = query.createSelection(); if (_recordsToImportSelectionId == null) { throw new AdempiereException("No records to import for " + query); } } return _recordsToImportSelectionId; }
private DataImportResult createResult() { final Duration duration = Duration.between(startTime, SystemTime.asInstant()); return DataImportResult.builder() .dataImportConfigId(dataImportConfigId) .duration(duration) // .insertIntoImportTable(insertIntoImportTableResult) .importRecordsValidation(validationResult) .actualImport(actualImportResult) .asyncImportResult(asyncImportResult) // .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\DataImportCommand.java
1
请完成以下Java代码
private ProcessVariableValue buildProcessVariableValue(Object value) { ProcessVariableValue variableValue = null; if (value != null) { Class<?> entryValueClass = value.getClass(); String entryType = resolveEntryType(entryValueClass, value); if (OBJECT_TYPE_KEY.equals(entryType)) { value = new ObjectValue(value); } String entryValue = conversionService.convert(value, String.class); variableValue = new ProcessVariableValue(entryType, entryValue); }
return variableValue; } private String resolveEntryType(Class<?> clazz, Object value) { Class<?> entryType; if (isScalarType(clazz)) { entryType = clazz; } else { entryType = getContainerType(clazz, value).orElse(ObjectValue.class); } return forClass(entryType); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessVariablesMapSerializer.java
1
请完成以下Java代码
public class Application { AtomicInteger atomic = new AtomicInteger(0); public static void main(String[] args) { Application app = new Application(); new Thread(() -> { for (int i = 0; i < 10; i++) { //app.atomic.set(i); app.atomic.lazySet(i); System.out.println("Set: " + i); try { Thread.sleep(100); } catch (InterruptedException e) {} }
}).start(); new Thread(() -> { for (int i = 0; i < 10; i++) { synchronized (app.atomic) { int counter = app.atomic.get(); System.out.println("Get: " + counter); } try { Thread.sleep(100); } catch (InterruptedException e) {} } }).start(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-4\src\main\java\com\baeldung\setvslazyset\Application.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, JSONArray> getKeysSizeReport() throws Exception { return redisService.getMapForReport("1"); } /** * 获取redis 内存 for 报表 * * @return * @throws Exception */ @GetMapping("/memoryForReport") public Map<String, JSONArray> memoryForReport() throws Exception { return redisService.getMapForReport("2"); } /** * 获取redis 全部信息 for 报表 * @return * @throws Exception */ @GetMapping("/infoForReport") public Map<String, JSONArray> infoForReport() throws Exception { return redisService.getMapForReport("3"); } @GetMapping("/memoryInfo") public Map<String, Object> getMemoryInfo() throws Exception { return redisService.getMemoryInfo(); } /** * @功能:获取磁盘信息 * @param request * @param response * @return */ @GetMapping("/queryDiskInfo") public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){ Result<List<Map<String,Object>>> res = new Result<>(); try { // 当前文件系统类 FileSystemView fsv = FileSystemView.getFileSystemView(); // 列出所有windows 磁盘 File[] fs = File.listRoots(); log.info("查询磁盘信息:"+fs.length+"个"); List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) { if(fs[i].getTotalSpace()==0) { continue; } Map<String,Object> map = new HashMap(5); map.put("name", fsv.getSystemDisplayName(fs[i])); map.put("max", fs[i].getTotalSpace()); map.put("rest", fs[i].getFreeSpace()); map.put("restPPT", (fs[i].getTotalSpace()-fs[i].getFreeSpace())*100/fs[i].getTotalSpace()); list.add(map); log.info(map.toString()); } res.setResult(list); res.success("查询成功"); } catch (Exception e) { res.error500("查询失败"+e.getMessage()); } return res; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\controller\ActuatorRedisController.java
2
请完成以下Java代码
public void setC_BPartner_ID(final int bpartnerId) { order.setC_BPartner_ID(bpartnerId); } @Override public int getC_BPartner_ID() { return order.getC_BPartner_ID(); } @Override public boolean isInDispute() { return false; }
@Override public void setInDispute(final boolean inDispute) { throw new UnsupportedOperationException(); } @Override public String toString() { return String .format("OrderHUPackingAware [order=%s, getM_Product_ID()=%s, getM_Product()=%s, getM_AttributeSetInstance_ID()=%s, getC_UOM()=%s, getQty()=%s, getM_HU_PI_Item_Product()=%s, getQtyPacks()=%s, getC_BPartner()=%s, getM_HU_PI_Item_Product_ID()=%s, isInDispute()=%s]", order, getM_Product_ID(), getM_Product_ID(), getM_AttributeSetInstance_ID(), getC_UOM_ID(), getQty(), getM_HU_PI_Item_Product_ID(), getQtyTU(), getC_BPartner_ID(), getM_HU_PI_Item_Product_ID(), isInDispute()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderHUPackingAware.java
1
请完成以下Java代码
SingleArticleResponse updateArticle( AuthToken authorsToken, @PathVariable String slug, @RequestBody EditArticleRequest request) { var author = userService.getUser(authorsToken.userId()); var article = articleService.getArticle(slug); if (request.article().title() != null) { article = articleService.editTitle(author, article, request.article().title()); } if (request.article().description() != null) { article = articleService.editDescription( author, article, request.article().description()); } if (request.article().body() != null) { article = articleService.editContent( author, article, request.article().body()); } return new SingleArticleResponse(articleService.getArticleDetails(author, article)); } @DeleteMapping("/api/articles/{slug}") void deleteArticle(AuthToken authorsToken, @PathVariable String slug) { var author = userService.getUser(authorsToken.userId()); var article = articleService.getArticle(slug); articleService.delete(author, article); } @GetMapping("/api/articles/feed") MultipleArticlesResponse getArticleFeeds(
AuthToken readersToken, // Must be verified @RequestParam(value = "offset", required = false, defaultValue = "0") int offset, @RequestParam(value = "limit", required = false, defaultValue = "20") int limit) { var reader = userService.getUser(readersToken.userId()); var facets = new ArticleFacets(offset, limit); var articleDetails = articleService.getFeeds(reader, facets); return this.getArticlesResponse(articleDetails); } private MultipleArticlesResponse getArticlesResponse(List<ArticleDetails> articles) { return articles.stream() .map(ArticleResponse::new) .collect(collectingAndThen(toList(), MultipleArticlesResponse::new)); } }
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\api\ArticleController.java
1
请完成以下Java代码
public int getAD_PInstance_ID() { return get_ValueAsInt(COLUMNNAME_AD_PInstance_ID); } @Override public void setC_Async_Batch_ID (final int C_Async_Batch_ID) { if (C_Async_Batch_ID < 1) set_Value (COLUMNNAME_C_Async_Batch_ID, null); else set_Value (COLUMNNAME_C_Async_Batch_ID, C_Async_Batch_ID); } @Override public int getC_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID); } @Override public I_C_Invoice_Candidate getC_Invoice_Candidate() { return get_ValueAsPO(COLUMNNAME_C_Invoice_Candidate_ID, I_C_Invoice_Candidate.class); } @Override public void setC_Invoice_Candidate(final de.metas.invoicecandidate.model.I_C_Invoice_Candidate C_Invoice_Candidate) { set_ValueFromPO(COLUMNNAME_C_Invoice_Candidate_ID, I_C_Invoice_Candidate.class, C_Invoice_Candidate); } @Override public void setC_Invoice_Candidate_ID (final int C_Invoice_Candidate_ID) { if (C_Invoice_Candidate_ID < 1) set_Value (COLUMNNAME_C_Invoice_Candidate_ID, null); else set_Value (COLUMNNAME_C_Invoice_Candidate_ID, C_Invoice_Candidate_ID); } @Override public int getC_Invoice_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_ID); } @Override public void setC_Invoice_Candidate_Recompute_ID (final int C_Invoice_Candidate_Recompute_ID) { if (C_Invoice_Candidate_Recompute_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Recompute_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Recompute_ID, C_Invoice_Candidate_Recompute_ID); } @Override public int getC_Invoice_Candidate_Recompute_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_Recompute_ID); } @Override public void setChunkUUID (final @Nullable String ChunkUUID) { set_Value (COLUMNNAME_ChunkUUID, ChunkUUID); } @Override public String getChunkUUID() { return get_ValueAsString(COLUMNNAME_ChunkUUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_Recompute.java
1