instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private @Nullable FileDescriptorProto findFileByName(FileDescriptorSet input, String name) { for (FileDescriptorProto file : input.getFileList()) { if (file.getName().equals(name)) { return file; } } return null; } private ManagedChannel createChannel() { Route route = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); URI requestURI = Objects.requireNonNull(route, "Route not found in exchange attributes").getUri(); return createChannelChannel(requestURI.getHost(), requestURI.getPort()); } private Function<JsonNode, DynamicMessage> callGRPCServer() { return jsonRequest -> { try { DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor); JsonFormat.parser().merge(jsonRequest.toString(), builder); return ClientCalls.blockingUnaryCall(clientCall, builder.build()); } catch (IOException e) { throw new RuntimeException(e); } }; } private Function<DynamicMessage, Object> serialiseGRPCResponse() { return gRPCResponse -> { try { return objectReader .readValue(JsonFormat.printer().omittingInsignificantWhitespace().print(gRPCResponse)); } catch (IOException e) { throw new RuntimeException(e); } }; } private Flux<JsonNode> deserializeJSONRequest() { return exchange.getRequest().getBody().mapNotNull(dataBufferBody -> { if (dataBufferBody.capacity() == 0) { return objectNode; } ResolvableType targetType = ResolvableType.forType(JsonNode.class); return new JacksonJsonDecoder().decode(dataBufferBody, targetType, null, null); }).cast(JsonNode.class);
} private Function<Object, DataBuffer> wrapGRPCResponse() { return jsonResponse -> new NettyDataBufferFactory(new PooledByteBufAllocator()) .wrap(Objects.requireNonNull(new ObjectMapper().writeValueAsBytes(jsonResponse))); } // We are creating this on every call, should optimize? private ManagedChannel createChannelChannel(String host, int port) { NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port); try { return grpcSslConfigurer.configureSsl(nettyChannelBuilder); } catch (SSLException e) { throw new RuntimeException(e); } } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\JsonToGrpcGatewayFilterFactory.java
1
请完成以下Java代码
public void setBackground() { } // setBackground /** * Set Background - nop * @param error */ public void setBackground(boolean error) { } // setBackground /** * Property Change * @param evt */ public void propertyChange(PropertyChangeEvent evt) { log.info(evt.toString()); if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) setValue(evt.getNewValue()); // metas: request focus (2009_0027_G131) if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS)) requestFocus(); // metas end } // propertyChange /** * ActionListener - start dialog and set value * @param e event */ public void actionPerformed (ActionEvent e) { JFileChooser fc = new JFileChooser(""); fc.setMultiSelectionEnabled(false); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = 0; boolean save = m_data != null; if (save) option = fc.showSaveDialog(this); else option = fc.showOpenDialog(this); if (option != JFileChooser.APPROVE_OPTION) return; File file = fc.getSelectedFile(); if (file == null) return; // log.info(file.toString()); try { if (save) { FileOutputStream os = new FileOutputStream(file); byte[] buffer = (byte[])m_data; os.write(buffer); os.flush(); os.close(); log.info("Save to " + file + " #" + buffer.length); } else // load { FileInputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[1024*8]; // 8kB int length = -1; while ((length = is.read(buffer)) != -1) os.write(buffer, 0, length); is.close(); byte[] data = os.toByteArray(); m_data = data;
log.info("Load from " + file + " #" + data.length); os.close(); } } catch (Exception ex) { log.warn("Save=" + save, ex); } try { fireVetoableChange(m_columnName, null, m_data); } catch (PropertyVetoException pve) {} } // actionPerformed // Field for Value Preference private GridField m_mField = null; /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField */ public void setField (GridField mField) { m_mField = mField; } // setField @Override public GridField getField() { return m_mField; } // metas @Override public boolean isAutoCommit() { return true; } } // VBinary
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VBinary.java
1
请在Spring Boot框架中完成以下Java代码
public boolean hasRelationQuerySource() { return toArgument().hasRelationQuerySource(); } public boolean hasCurrentOwnerSource() { return toArgument().hasOwnerSource(); } @JsonIgnore public boolean isCfEntitySource(EntityId cfEntityId) { if (refEntityId == null && refDynamicSourceConfiguration == null) { return true; } return refEntityId != null && refEntityId.equals(cfEntityId); }
@JsonIgnore public boolean isLinkedCfEntitySource(EntityId cfEntityId) { return refEntityId != null && !refEntityId.equals(cfEntityId); } public Argument toArgument() { var argument = new Argument(); argument.setRefEntityId(refEntityId); argument.setRefDynamicSourceConfiguration(refDynamicSourceConfiguration); argument.setRefEntityKey(new ReferencedEntityKey(perimeterKeyName, ArgumentType.ATTRIBUTE, AttributeScope.SERVER_SCOPE)); return argument; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\geofencing\ZoneGroupConfiguration.java
2
请完成以下Java代码
public String getTour() { return tour; } /** * Sets the value of the tour property. * * @param value * allowed object is * {@link String } * */ public void setTour(String value) { this.tour = value; } /** * Gets the value of the retourenAnteilTyp property. * * @return * possible object is * {@link RetourenAnteilTypType } * */ public RetourenAnteilTypType getRetourenAnteilTyp() { return retourenAnteilTyp; } /** * Sets the value of the retourenAnteilTyp property. * * @param value * allowed object is * {@link RetourenAnteilTypType } * */ public void setRetourenAnteilTyp(RetourenAnteilTypType value) {
this.retourenAnteilTyp = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;extension base="{urn:msv3:v2}RetourePositionType"&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Position extends RetourePositionType { } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigungAntwort.java
1
请完成以下Java代码
private String getBaseDirectory(final @NonNull PrintingData printingData) { final String sysconfigDirectory = sysConfigBL.getValue(SYSCONFIG_STORE_PDF_BASE_DIRECTORY, ClientId.METASFRESH.getRepoId(), printingData.getOrgId().getRepoId()); if (Check.isNotBlank(sysconfigDirectory)) { return sysconfigDirectory; } final String tempDir = System.getProperty("java.io.tmpdir"); logger.debug("AD_SysConfig {} is not set; -> use temp-dir {} as base directory", SYSCONFIG_STORE_PDF_BASE_DIRECTORY, tempDir); return tempDir; } private void createDirectories(@NonNull final Path path) { try { Files.createDirectories(path); } catch (final IOException e) { throw new AdempiereException("IOException trying to create output directory", e) .setParameter("path", path); } } private ImmutableMultimap<Path, PrintingSegment> extractAndAssignPaths( @NonNull final String baseDirectory, @NonNull final PrintingData printingData) { final ImmutableMultimap.Builder<Path, PrintingSegment> path2Segments = new ImmutableMultimap.Builder<>(); for (final PrintingSegment segment : printingData.getSegments()) { final HardwarePrinter printer = segment.getPrinter();
if (!OutputType.Store.equals(printer.getOutputType())) { logger.debug("Printer with id={} has outputType={}; -> skipping it", printer.getId().getRepoId(), printer.getOutputType()); continue; } final Path path; if (segment.getTrayId() != null) { final HardwareTray tray = printer.getTray(segment.getTrayId()); path = Paths.get(baseDirectory, FileUtil.stripIllegalCharacters(printer.getName()), FileUtil.stripIllegalCharacters(tray.getTrayNumber() + "-" + tray.getName())); } else { path = Paths.get(baseDirectory, FileUtil.stripIllegalCharacters(printer.getName())); } path2Segments.put(path, segment); } return path2Segments.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataToPDFFileStorer.java
1
请完成以下Java代码
private boolean isJuelExpression(String expressionLanguage) { return DefaultDmnEngineConfiguration.JUEL_EXPRESSION_LANGUAGE.equalsIgnoreCase(expressionLanguage); } protected ScriptEngine getScriptEngineForName(String expressionLanguage) { ensureNotNull("expressionLanguage", expressionLanguage); ScriptEngine scriptEngine = scriptEngineResolver.getScriptEngineForLanguage(expressionLanguage); if (scriptEngine != null) { return scriptEngine; } else { throw LOG.noScriptEngineFoundForLanguage(expressionLanguage); } }
protected boolean isElExpression(String expressionLanguage) { return isJuelExpression(expressionLanguage); } public boolean isFeelExpressionLanguage(String expressionLanguage) { ensureNotNull("expressionLanguage", expressionLanguage); return expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE) || expressionLanguage.toLowerCase().equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_ALTERNATIVE) || expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN12) || expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN13) || expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN14) || expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN15); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\evaluation\ExpressionEvaluationHandler.java
1
请完成以下Java代码
public class PP_Product_BOM { private final IProductBL productsService = Services.get(IProductBL.class); private final ProductBOMVersionsDAO bomVersionsDAO; public PP_Product_BOM(final ProductBOMVersionsDAO bomVersionsDAO) { this.bomVersionsDAO = bomVersionsDAO; } /** * Updates BOM fields from selected bom versions, if any. * * @param bom */ @CalloutMethod(columnNames = I_PP_Product_BOM.COLUMNNAME_PP_Product_BOMVersions_ID) public void onBOMVersionsChanged(final I_PP_Product_BOM bom) { final ProductBOMVersionsId bomVersionsId = ProductBOMVersionsId.ofRepoId(bom.getPP_Product_BOMVersions_ID());
final I_PP_Product_BOMVersions bomVersions = bomVersionsDAO.getBOMVersions(bomVersionsId); final ProductId productId = ProductId.ofRepoId(bomVersions.getM_Product_ID()); final I_M_Product product = productsService.getById(productId); bom.setM_Product_ID(product.getM_Product_ID()); bom.setValue(product.getValue()); bom.setName(product.getName()); bom.setDescription(product.getDescription()); bom.setHelp(product.getHelp()); bom.setC_UOM_ID(product.getC_UOM_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Product_BOM.java
1
请完成以下Java代码
public SqlAndParams buildSqlCount(final String selectionId, final DocumentIdsSelection rowIds) { Check.assumeNotEmpty(selectionId, "selectionId is not empty"); final SqlAndParams.Builder sql = SqlAndParams.builder() .append("SELECT COUNT(1) FROM " + I_T_WEBUI_ViewSelection.Table_Name + " WHERE " + I_T_WEBUI_ViewSelection.COLUMNNAME_UUID + "=?", selectionId); if (rowIds.isAll()) { return sql.build(); } else if (rowIds.isEmpty()) { throw new IllegalArgumentException("empty rowIds is not allowed"); } else { return sql.append(" AND (") .append(getSqlViewKeyColumnNamesMap() .prepareSqlFilterByRowIds() .rowIds(rowIds) .build()) .append(")") .build(); } } public SqlAndParams buildSqlDeleteSelection(@NonNull final Set<String> selectionIds) { final ArrayList<Object> sqlParams = new ArrayList<>(selectionIds.size()); final String sql = "DELETE FROM " + I_T_WEBUI_ViewSelection.Table_Name + " WHERE " + DB.buildSqlList(I_T_WEBUI_ViewSelection.COLUMNNAME_UUID, selectionIds, sqlParams); return SqlAndParams.of(sql, sqlParams); } public SqlAndParams buildSqlDeleteSelectionLines(@NonNull final Set<String> selectionIds) { final ArrayList<Object> sqlParams = new ArrayList<>(selectionIds.size()); final String sql = "DELETE FROM " + I_T_WEBUI_ViewSelectionLine.Table_Name + " WHERE " + DB.buildSqlList(I_T_WEBUI_ViewSelectionLine.COLUMNNAME_UUID, selectionIds, sqlParams); return SqlAndParams.of(sql, sqlParams); }
public static SqlAndParams buildSqlSelectRowIdsForLineIds( @NonNull final SqlViewKeyColumnNamesMap keyColumnNamesMap, @NonNull final String selectionId, final Collection<Integer> lineIds) { Check.assumeNotEmpty(lineIds, "lineIds is not empty"); final List<Object> sqlParams = new ArrayList<>(); sqlParams.add(selectionId); final String sql = "SELECT " + keyColumnNamesMap.getWebuiSelectionColumnNamesCommaSeparated() + " FROM " + I_T_WEBUI_ViewSelectionLine.Table_Name + " WHERE " + I_T_WEBUI_ViewSelectionLine.COLUMNNAME_UUID + "=?" + " AND " + DB.buildSqlList(I_T_WEBUI_ViewSelectionLine.COLUMNNAME_Line_ID, lineIds, sqlParams); return SqlAndParams.of(sql, sqlParams); } private IStringExpressionWrapper securityRestrictionsWrapper(final String sqlTableAlias) { if (applySecurityRestrictions) { return AccessSqlStringExpression.wrapper(sqlTableAlias, IUserRolePermissions.SQL_FULLYQUALIFIED, Access.READ); } else { return expression -> expression; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewSelectionQueryBuilder.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Drucker. @param PrinterName Name of the Printer */
@Override public void setPrinterName (java.lang.String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); } /** Get Drucker. @return Name of the Printer */ @Override public java.lang.String getPrinterName () { return (java.lang.String)get_Value(COLUMNNAME_PrinterName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFormat.java
1
请完成以下Java代码
public class WebRequestInterceptor implements AsyncHandlerInterceptor { private final ThreadLocal<Long> exeTimeThreadLocal = new ThreadLocal<>(); private final HibernateStatementStatInterceptor statisticsInterceptor; public WebRequestInterceptor(HibernateStatementStatInterceptor statisticsInterceptor) { this.statisticsInterceptor = statisticsInterceptor; } @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) { exeTimeThreadLocal.set(System.currentTimeMillis()); statisticsInterceptor.startCounter(); return true; } @Override public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView modelAndView) { Long queryCount = statisticsInterceptor.getQueryCount(); if (modelAndView != null) { //to display to the View modelAndView.addObject("_queryCount", queryCount); }
} @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse resp, Object handler, Exception ex) { long duration = System.currentTimeMillis() - exeTimeThreadLocal.get(); Long queryCount = statisticsInterceptor.getQueryCount(); statisticsInterceptor.clearCounter(); exeTimeThreadLocal.remove(); log.debug("Queries executed: {}, Request Url: {}, Time: {} ms", queryCount, request.getRequestURI(), duration); } @Override public void afterConcurrentHandlingStarted(HttpServletRequest req, HttpServletResponse resp, Object handler) { //concurrent handling cannot be supported here statisticsInterceptor.clearCounter(); exeTimeThreadLocal.remove(); } }
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\config\logging\WebRequestInterceptor.java
1
请完成以下Java代码
private String toCsvValue(Object value) { final String valueStr; if (value == null) { valueStr = ""; } else if (value instanceof java.util.Date) { valueStr = dateFormat.format(value); } else { valueStr = value.toString(); } return quoteCsvValue(valueStr); } private String quoteCsvValue(String valueStr) { return fieldQuote + valueStr.replace(fieldQuote, fieldQuote + fieldQuote) + fieldQuote; } @Override public void close() throws IOException { if (writer == null) { return;
} try { writer.flush(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // shall not happen e.printStackTrace(); // NOPMD by tsa on 3/13/13 1:46 PM } writer = null; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\CSVWriter.java
1
请完成以下Java代码
protected <T extends TypedValue> TypedValueField toTypedValueField(T typedValue) { ValueMapper<T> serializer = findSerializer(typedValue); if(typedValue instanceof UntypedValueImpl) { typedValue = serializer.convertToTypedValue((UntypedValueImpl) typedValue); } TypedValueField typedValueField = new TypedValueField(); serializer.writeValue(typedValue, typedValueField); ValueType valueType = typedValue.getType(); typedValueField.setValueInfo(valueType.getValueInfo(typedValue)); String typeName = valueType.getName(); String typeNameCapitalized = Character.toUpperCase(typeName.charAt(0)) + typeName.substring(1); typedValueField.setType(typeNameCapitalized); return typedValueField; } @SuppressWarnings("unchecked") protected <T extends TypedValue> ValueMapper<T> findSerializer(T typedValue) { return serializers.findMapperForTypedValue(typedValue);
} protected TypedValue createTypedValue(Object value) { TypedValue typedValue = null; if (value instanceof TypedValue) { typedValue = (TypedValue) value; } else { typedValue = Variables.untypedValue(value); } return typedValue; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\TypedValues.java
1
请完成以下Java代码
public ConfigurationPropertyName map(String propertySourceName) { ConfigurationPropertyName configurationPropertyName = this.propertySourceNameCache.get(propertySourceName); if (configurationPropertyName == null) { configurationPropertyName = convertName(propertySourceName); this.propertySourceNameCache.put(propertySourceName, configurationPropertyName); } return configurationPropertyName; } private ConfigurationPropertyName convertName(String propertySourceName) { try { return ConfigurationPropertyName.adapt(propertySourceName, '_', this::processElementValue); } catch (Exception ex) { return ConfigurationPropertyName.EMPTY; } } private CharSequence processElementValue(CharSequence value) { String result = value.toString().toLowerCase(Locale.ENGLISH); return isNumber(result) ? "[" + result + "]" : result; } private static boolean isNumber(String string) {
return string.chars().allMatch(Character::isDigit); } @Override public BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> getAncestorOfCheck() { return this::isAncestorOf; } private boolean isAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) { return name.isAncestorOf(candidate) || isLegacyAncestorOf(name, candidate); } private boolean isLegacyAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) { if (!name.hasDashedElement()) { return false; } ConfigurationPropertyName legacyCompatibleName = name.asSystemEnvironmentLegacyName(); return legacyCompatibleName != null && legacyCompatibleName.isAncestorOf(candidate); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\SystemEnvironmentPropertyMapper.java
1
请在Spring Boot框架中完成以下Java代码
public static String getStringFromJson(ObjectNode objectNode, String fieldName) { if (objectNode.has(fieldName)) { return objectNode.get(fieldName).asString(); } return null; } public static Date getDateFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); return AsyncHistoryDateUtil.parseDate(s); } public static Integer getIntegerFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Integer.valueOf(s); } return null; } public static Double getDoubleFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Double.valueOf(s); } return null; } public static Long getLongFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Long.valueOf(s); } return null; }
public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName, Boolean defaultValue) { Boolean value = getBooleanFromJson(objectNode, fieldName); return value != null ? value : defaultValue; } public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Boolean.valueOf(s); } return null; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\history\async\util\AsyncHistoryJsonUtil.java
2
请完成以下Java代码
private I_M_ReceiptSchedule getReceiptSchedule(@NonNull final DocumentPath referencingDocumentPath) { return documentsCollection .getTableRecordReference(referencingDocumentPath) .getModel(this, I_M_ReceiptSchedule.class); } protected Set<HuId> retrieveHUsToReceive() { // https://github.com/metasfresh/metasfresh/issues/1863 // if the queryFilter is empty, then *do not* return everything to avoid an OOME final IQueryFilter<I_M_HU> processInfoFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); final IQuery<I_M_HU> query = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class, this) .filter(processInfoFilter) .addOnlyActiveRecordsFilter() .create();
final Set<HuId> huIds = query .listIds() .stream() .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (huIds.isEmpty()) { throw new AdempiereException("@NoSelection@ @M_HU_ID@") .appendParametersToMessage() .setParameter("query", query); } return huIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_CreateReceipt_Base.java
1
请完成以下Java代码
public ServerResponse build() { return build((request, response) -> null); } @Override public ServerResponse build(WriteFunction writeFunction) { return new WriteFunctionResponse(this.statusCode, this.headers, this.cookies, writeFunction); } @Override public ServerResponse body(Object body) { return GatewayEntityResponseBuilder.fromObject(body) .status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .build(); } @Override public <T> ServerResponse body(T body, ParameterizedTypeReference<T> bodyType) { return GatewayEntityResponseBuilder.fromObject(body, bodyType) .status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .build(); } @Override public ServerResponse render(String name, Object... modelAttributes) { return new GatewayRenderingResponseBuilder(name).status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .modelAttributes(modelAttributes) .build(); } @Override public ServerResponse render(String name, Map<String, ?> model) { return new GatewayRenderingResponseBuilder(name).status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .modelAttributes(model) .build(); } @Override public ServerResponse stream(Consumer<ServerResponse.StreamBuilder> streamConsumer) {
return GatewayStreamingServerResponse.create(this.statusCode, this.headers, this.cookies, streamConsumer, null); } private static class WriteFunctionResponse extends AbstractGatewayServerResponse { private final WriteFunction writeFunction; WriteFunctionResponse(HttpStatusCode statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies, WriteFunction writeFunction) { super(statusCode, headers, cookies); Objects.requireNonNull(writeFunction, "WriteFunction must not be null"); this.writeFunction = writeFunction; } @Override protected @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response, Context context) throws Exception { return this.writeFunction.write(request, response); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponseBuilder.java
1
请完成以下Java代码
public static <T> AuthorizationManager<T> hasScope(String scope) { assertScope(scope); return AuthorityAuthorizationManager.hasAuthority("SCOPE_" + scope); } /** * Create an {@link AuthorizationManager} that requires an {@link Authentication} to * have at least one authority among {@code SCOPE_scope1}, {@code SCOPE_scope2}, ... * {@code SCOPE_scopeN}. * * <p> * For example, if you call {@code hasAnyScope("read", "write")}, then this will * require that each authentication have at least a * {@link org.springframework.security.core.GrantedAuthority} whose value is either * {@code SCOPE_read} or {@code SCOPE_write}. * * <p> * This would equivalent to calling * {@code AuthorityAuthorizationManager#hasAnyAuthority("SCOPE_read", "SCOPE_write")}. * @param scopes the scope values to allow * @param <T> the secure object * @return an {@link AuthorizationManager} that requires at least one authority among * {@code "SCOPE_scope1"}, {@code SCOPE_scope2}, ... {@code SCOPE_scopeN}. * */ public static <T> AuthorizationManager<T> hasAnyScope(String... scopes) { String[] mappedScopes = new String[scopes.length];
for (int i = 0; i < scopes.length; i++) { assertScope(scopes[i]); mappedScopes[i] = "SCOPE_" + scopes[i]; } return AuthorityAuthorizationManager.hasAnyAuthority(mappedScopes); } private static void assertScope(String scope) { Assert.isTrue(!scope.startsWith("SCOPE_"), () -> scope + " should not start with SCOPE_ since SCOPE_" + " is automatically prepended when using hasScope and hasAnyScope. Consider using " + " AuthorityAuthorizationManager#hasAuthority or #hasAnyAuthority instead."); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\authorization\OAuth2AuthorizationManagers.java
1
请完成以下Java代码
public class MetricsIntervalResultDto { protected Date timestamp; protected String name; protected String reporter; protected long value; public MetricsIntervalResultDto(MetricIntervalValue metric) { this.timestamp = metric.getTimestamp(); this.name = metric.getName(); this.reporter = metric.getReporter(); this.value = metric.getValue(); } public MetricsIntervalResultDto(Date timestamp, String name, String reporter, long value) { this.timestamp = timestamp; this.name = name; this.reporter = reporter; this.value = value; } public MetricsIntervalResultDto() { } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getReporter() { return reporter; } public void setReporter(String reporter) { this.reporter = reporter; } public long getValue() { return value; } public void setValue(long value) { this.value = value; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\metrics\MetricsIntervalResultDto.java
1
请完成以下Java代码
public int getC_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID); } @Override public void setCommodityCode (final @Nullable java.lang.String CommodityCode) { set_Value (COLUMNNAME_CommodityCode, CommodityCode); } @Override public java.lang.String getCommodityCode() { return get_ValueAsString(COLUMNNAME_CommodityCode); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setInternalName (final @Nullable java.lang.String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public java.lang.String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * ProductType AD_Reference_ID=270 * Reference name: M_Product_ProductType */ public static final int PRODUCTTYPE_AD_Reference_ID=270; /** Item = I */ public static final String PRODUCTTYPE_Item = "I"; /** Service = S */ public static final String PRODUCTTYPE_Service = "S"; /** Resource = R */ public static final String PRODUCTTYPE_Resource = "R"; /** ExpenseType = E */
public static final String PRODUCTTYPE_ExpenseType = "E"; /** Online = O */ public static final String PRODUCTTYPE_Online = "O"; /** FreightCost = F */ public static final String PRODUCTTYPE_FreightCost = "F"; @Override public void setProductType (final @Nullable java.lang.String ProductType) { set_Value (COLUMNNAME_ProductType, ProductType); } @Override public java.lang.String getProductType() { return get_ValueAsString(COLUMNNAME_ProductType); } /** * VATType AD_Reference_ID=540842 * Reference name: VATType */ public static final int VATTYPE_AD_Reference_ID=540842; /** RegularVAT = N */ public static final String VATTYPE_RegularVAT = "N"; /** ReducedVAT = R */ public static final String VATTYPE_ReducedVAT = "R"; /** TaxExempt = E */ public static final String VATTYPE_TaxExempt = "E"; @Override public void setVATType (final @Nullable java.lang.String VATType) { set_Value (COLUMNNAME_VATType, VATType); } @Override public java.lang.String getVATType() { return get_ValueAsString(COLUMNNAME_VATType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxCategory.java
1
请在Spring Boot框架中完成以下Java代码
protected void validateCreate(TenantId tenantId, Asset asset) { validateNumberOfEntitiesPerTenant(tenantId, EntityType.ASSET); } @Override protected Asset validateUpdate(TenantId tenantId, Asset asset) { Asset old = assetDao.findById(asset.getTenantId(), asset.getId().getId()); if (old == null) { throw new DataValidationException("Can't update non existing asset!"); } return old; } @Override protected void validateDataImpl(TenantId tenantId, Asset asset) { validateString("Asset name", asset.getName()); if (asset.getTenantId() == null) { throw new DataValidationException("Asset should be assigned to tenant!"); } else {
if (!tenantService.tenantExists(asset.getTenantId())) { throw new DataValidationException("Asset is referencing to non-existent tenant!"); } } if (asset.getCustomerId() == null) { asset.setCustomerId(new CustomerId(NULL_UUID)); } else if (!asset.getCustomerId().getId().equals(NULL_UUID)) { Customer customer = customerDao.findById(tenantId, asset.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("Can't assign asset to non-existent customer!"); } if (!customer.getTenantId().equals(asset.getTenantId())) { throw new DataValidationException("Can't assign asset to customer from different tenant!"); } } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\AssetDataValidator.java
2
请在Spring Boot框架中完成以下Java代码
class GzipRequestInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { return chain.proceed(originalRequest); } Request compressedRequest = originalRequest.newBuilder() .header("Content-Encoding", "gzip") .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) .build(); return chain.proceed(compressedRequest); } private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return new RequestBody() { @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() { return buffer.size(); }
@Override public void writeTo(BufferedSink sink) throws IOException { sink.write(buffer.snapshot()); } }; } private RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\GzipRequestInterceptor.java
2
请完成以下Java代码
public String getTypeRef() { return typeRefAttribute.getValue(this); } public void setTypeRef(String typeRef) { typeRefAttribute.setValue(this, typeRef); } public OutputValues getOutputValues() { return outputValuesChild.getChild(this); } public void setOutputValues(OutputValues outputValues) { outputValuesChild.setChild(this, outputValues); } public DefaultOutputEntry getDefaultOutputEntry() { return defaultOutputEntryChild.getChild(this); } public void setDefaultOutputEntry(DefaultOutputEntry defaultOutputEntry) { defaultOutputEntryChild.setChild(this, defaultOutputEntry); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(OutputClause.class, DMN_ELEMENT_OUTPUT_CLAUSE) .namespaceUri(LATEST_DMN_NS) .extendsType(DmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<OutputClause>() { public OutputClause newInstance(ModelTypeInstanceContext instanceContext) { return new OutputClauseImpl(instanceContext); } });
nameAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAME) .build(); typeRefAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_REF) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); outputValuesChild = sequenceBuilder.element(OutputValues.class) .build(); defaultOutputEntryChild = sequenceBuilder.element(DefaultOutputEntry.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\OutputClauseImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void putLocale(@Nullable final Locale locale) { put(JRParameter.REPORT_LOCALE, locale); } @Nullable public Locale getLocale() { return (Locale)get(JRParameter.REPORT_LOCALE); } public void putRecordId(final int recordId) { put(PARAM_RECORD_ID, recordId); } public void putTableId(final int tableId)
{ put(PARAM_AD_Table_ID, tableId); } public void putBarcodeURL(final String barcodeURL) { put(PARAM_BARCODE_URL, barcodeURL); } @Nullable public String getBarcodeUrl() { final Object barcodeUrl = get(PARAM_BARCODE_URL); return barcodeUrl != null ? barcodeUrl.toString() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JRParametersCollector.java
2
请在Spring Boot框架中完成以下Java代码
private void configureH2ConsoleSettings(ServletRegistrationBean<JakartaWebServlet> registration, Settings settings) { if (settings.isTrace()) { registration.addInitParameter("trace", ""); } if (settings.isWebAllowOthers()) { registration.addInitParameter("webAllowOthers", ""); } if (settings.getWebAdminPassword() != null) { registration.addInitParameter("webAdminPassword", settings.getWebAdminPassword()); } } static class H2ConsoleLogger { H2ConsoleLogger(ObjectProvider<DataSource> dataSources, String path) { if (logger.isInfoEnabled()) { ClassLoader classLoader = getClass().getClassLoader(); withThreadContextClassLoader(classLoader, () -> log(getConnectionUrls(dataSources), path)); } } private void withThreadContextClassLoader(ClassLoader classLoader, Runnable action) { ClassLoader previous = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); action.run(); } finally { Thread.currentThread().setContextClassLoader(previous); } }
private List<String> getConnectionUrls(ObjectProvider<DataSource> dataSources) { return dataSources.orderedStream(ObjectProvider.UNFILTERED) .map(this::getConnectionUrl) .filter(Objects::nonNull) .toList(); } private @Nullable String getConnectionUrl(DataSource dataSource) { try (Connection connection = dataSource.getConnection()) { return "'" + connection.getMetaData().getURL() + "'"; } catch (Exception ex) { return null; } } private void log(List<String> urls, String path) { if (!urls.isEmpty()) { logger.info(LogMessage.format("H2 console available at '%s'. %s available at %s", path, (urls.size() > 1) ? "Databases" : "Database", String.join(", ", urls))); } } } }
repos\spring-boot-4.0.1\module\spring-boot-h2console\src\main\java\org\springframework\boot\h2console\autoconfigure\H2ConsoleAutoConfiguration.java
2
请完成以下Java代码
public class PageInfo<T> implements Serializable { private static final long serialVersionUID = 1L; //当前页 private int pageNum; //每页的数量 private int pageSize; //总记录数 private long total; //总页数 private int pages; //结果集 private List<T> list; //是否为第一页 private boolean isFirstPage = false; //是否为最后一页 private boolean isLastPage = false; public PageInfo() { } /** * 包装Page对象 * * @param list */ public PageInfo(List<T> list) { if (list instanceof Page) { Page page = (Page) list; this.pageNum = page.getPageNum(); this.pageSize = page.getPageSize(); this.pages = page.getPages(); this.list = page; this.total = page.getTotal(); } else if (list instanceof Collection) { this.pageNum = 1; this.pageSize = list.size(); this.pages = 1; this.list = list; this.total = list.size(); } if (list instanceof Collection) { //判断页面边界 judgePageBoudary(); } } /** * 判定页面边界 */ private void judgePageBoudary() { isFirstPage = pageNum == 1; isLastPage = pageNum == pages; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total;
} public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public boolean isIsFirstPage() { return isFirstPage; } public void setIsFirstPage(boolean isFirstPage) { this.isFirstPage = isFirstPage; } public boolean isIsLastPage() { return isLastPage; } public void setIsLastPage(boolean isLastPage) { this.isLastPage = isLastPage; } @Override public String toString() { final StringBuffer sb = new StringBuffer("PageInfo{"); sb.append("pageNum=").append(pageNum); sb.append(", pageSize=").append(pageSize); sb.append(", total=").append(total); sb.append(", pages=").append(pages); sb.append(", list=").append(list); sb.append(", isFirstPage=").append(isFirstPage); sb.append(", isLastPage=").append(isLastPage); sb.append(", navigatepageNums="); sb.append('}'); return sb.toString(); } }
repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\page\PageInfo.java
1
请完成以下Java代码
public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setC_User_Assigned_Role_ID (final int C_User_Assigned_Role_ID) { if (C_User_Assigned_Role_ID < 1) set_ValueNoCheck (COLUMNNAME_C_User_Assigned_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_C_User_Assigned_Role_ID, C_User_Assigned_Role_ID); } @Override public int getC_User_Assigned_Role_ID() { return get_ValueAsInt(COLUMNNAME_C_User_Assigned_Role_ID); }
@Override public org.compiere.model.I_C_User_Role getC_User_Role() { return get_ValueAsPO(COLUMNNAME_C_User_Role_ID, org.compiere.model.I_C_User_Role.class); } @Override public void setC_User_Role(final org.compiere.model.I_C_User_Role C_User_Role) { set_ValueFromPO(COLUMNNAME_C_User_Role_ID, org.compiere.model.I_C_User_Role.class, C_User_Role); } @Override public void setC_User_Role_ID (final int C_User_Role_ID) { if (C_User_Role_ID < 1) set_Value (COLUMNNAME_C_User_Role_ID, null); else set_Value (COLUMNNAME_C_User_Role_ID, C_User_Role_ID); } @Override public int getC_User_Role_ID() { return get_ValueAsInt(COLUMNNAME_C_User_Role_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_User_Assigned_Role.java
1
请完成以下Java代码
public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) { try { LOGGER.info("Initializing flowable-cdi."); // initialize the process engine ProcessEngine processEngine = lookupProcessEngine(beanManager); // deploy the processes if engine was set up correctly deployProcesses(processEngine); } catch (Exception e) { // interpret engine initialization problems as definition errors event.addDeploymentProblem(e); } } protected ProcessEngine lookupProcessEngine(BeanManager beanManager) { ServiceLoader<ProcessEngineLookup> processEngineServiceLoader = ServiceLoader.load(ProcessEngineLookup.class); Iterator<ProcessEngineLookup> serviceIterator = processEngineServiceLoader.iterator(); List<ProcessEngineLookup> discoveredLookups = new ArrayList<>(); while (serviceIterator.hasNext()) { ProcessEngineLookup serviceInstance = serviceIterator.next(); discoveredLookups.add(serviceInstance); } Collections.sort(discoveredLookups, new Comparator<ProcessEngineLookup>() { @Override public int compare(ProcessEngineLookup o1, ProcessEngineLookup o2) { return (-1) * ((Integer) o1.getPrecedence()).compareTo(o2.getPrecedence()); } }); ProcessEngine processEngine = null; for (ProcessEngineLookup processEngineLookup : discoveredLookups) {
processEngine = processEngineLookup.getProcessEngine(); if (processEngine != null) { this.processEngineLookup = processEngineLookup; LOGGER.debug("ProcessEngineLookup service {} returned process engine.", processEngineLookup.getClass()); break; } else { LOGGER.debug("ProcessEngineLookup service {} returned 'null' value.", processEngineLookup.getClass()); } } if (processEngineLookup == null) { throw new FlowableException("Could not find an implementation of the org.flowable.cdi.spi.ProcessEngineLookup service " + "returning a non-null processEngine. Giving up."); } FlowableServices services = ProgrammaticBeanLookup.lookup(FlowableServices.class, beanManager); services.setProcessEngine(processEngine); return processEngine; } private void deployProcesses(ProcessEngine processEngine) { new ProcessDeployer(processEngine).deployProcesses(); } public void beforeShutdown(@Observes BeforeShutdown event) { if (processEngineLookup != null) { processEngineLookup.ungetProcessEngine(); processEngineLookup = null; } LOGGER.info("Shutting down flowable-cdi"); } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\FlowableExtension.java
1
请完成以下Java代码
public final boolean isConsolidateDocument() { return consolidateDocument; } public final void setConsolidateDocument(boolean consolidateDocument) { this.consolidateDocument = consolidateDocument; } public final Timestamp getMovementDate() { return movementDate; } public final void setMovementDate(Timestamp dateShipped) { this.movementDate = dateShipped; } public final boolean isPreferBPartner() { return preferBPartner; } public final void setPreferBPartner(boolean preferBPartner) {
this.preferBPartner = preferBPartner; } public final boolean isIgnorePostageFreeamount() { return ignorePostageFreeamount; } public final void setIgnorePostageFreeamount(boolean ignorePostageFreeamount) { this.ignorePostageFreeamount = ignorePostageFreeamount; } public Set<Integer> getSelectedOrderLineIds() { return selectedOrderLineIds; } public void setSelectedOrderLineIds(Set<Integer> selectedOrderLineIds) { this.selectedOrderLineIds = selectedOrderLineIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\shipment\ShipmentParams.java
1
请完成以下Java代码
private String postLogoutRedirectUri(HttpServletRequest request, ClientRegistration clientRegistration) { if (this.postLogoutRedirectUri == null) { return null; } // @formatter:off UriComponents uriComponents = UriComponentsBuilder .fromUriString(UrlUtils.buildFullRequestUrl(request)) .replacePath(request.getContextPath()) .replaceQuery(null) .fragment(null) .build(); Map<String, String> uriVariables = new HashMap<>(); String scheme = uriComponents.getScheme(); uriVariables.put("baseScheme", (scheme != null) ? scheme : ""); uriVariables.put("baseUrl", uriComponents.toUriString()); String host = uriComponents.getHost(); uriVariables.put("baseHost", (host != null) ? host : ""); String path = uriComponents.getPath(); uriVariables.put("basePath", (path != null) ? path : ""); int port = uriComponents.getPort(); uriVariables.put("basePort", (port == -1) ? "" : ":" + port); uriVariables.put("registrationId", clientRegistration.getRegistrationId()); return UriComponentsBuilder.fromUriString(this.postLogoutRedirectUri) .buildAndExpand(uriVariables) .toUriString(); // @formatter:on } private String endpointUri(URI endSessionEndpoint, String idToken, String postLogoutRedirectUri) { UriComponentsBuilder builder = UriComponentsBuilder.fromUri(endSessionEndpoint); builder.queryParam("id_token_hint", idToken); if (postLogoutRedirectUri != null) { builder.queryParam("post_logout_redirect_uri", postLogoutRedirectUri); } // @formatter:off return builder.encode(StandardCharsets.UTF_8) .build() .toUriString();
// @formatter:on } /** * Set the post logout redirect uri template. * * <br /> * The supported uri template variables are: {@code {baseScheme}}, {@code {baseHost}}, * {@code {basePort}} and {@code {basePath}}. * * <br /> * <b>NOTE:</b> {@code "{baseUrl}"} is also supported, which is the same as * {@code "{baseScheme}://{baseHost}{basePort}{basePath}"} * * <pre> * handler.setPostLogoutRedirectUri("{baseUrl}"); * </pre> * * will make so that {@code post_logout_redirect_uri} will be set to the base url for * the client application. * @param postLogoutRedirectUri - A template for creating the * {@code post_logout_redirect_uri} query parameter * @since 5.3 */ public void setPostLogoutRedirectUri(String postLogoutRedirectUri) { Assert.notNull(postLogoutRedirectUri, "postLogoutRedirectUri cannot be null"); this.postLogoutRedirectUri = postLogoutRedirectUri; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\web\logout\OidcClientInitiatedLogoutSuccessHandler.java
1
请完成以下Java代码
public String list(ModelMap map) { map.addAttribute("users", getUserList()); return "list"; } @RequestMapping("/url") public String url(ModelMap map) { map.addAttribute("type", "link"); map.addAttribute("pageId", "springcloud/2017/09/11/"); map.addAttribute("img", "http://www.ityouknow.com/assets/images/neo.jpg"); return "url"; } @RequestMapping("/eq") public String eq(ModelMap map) { map.addAttribute("name", "neo"); map.addAttribute("age", 30); map.addAttribute("flag", "yes"); return "eq"; } @RequestMapping("/switch") public String switchcase(ModelMap map) {
map.addAttribute("sex", "woman"); return "switch"; } private List<User> getUserList(){ List<User> list=new ArrayList<User>(); User user1=new User("大牛",12,"123456"); User user2=new User("小牛",6,"123563"); User user3=new User("纯洁的微笑",66,"666666"); list.add(user1); list.add(user2); list.add(user3); return list; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-3 课 模板引擎 Thymeleaf 基础使用\spring-boot-thymeleaf\src\main\java\com\neo\web\ExampleController.java
1
请完成以下Java代码
public String getOwner() { return owner; } /** * indication of how important/urgent this task is with a number between 0 and * 100 where higher values mean a higher priority and lower values mean lower * priority: [0..19] lowest, [20..39] low, [40..59] normal, [60..79] high * [80..100] highest */ public int getPriority() { return priority; } /** * Reference to the process definition or null if it is not related to a * process. */ public String getProcessDefinitionId() { return processDefinitionId; } /** * Reference to the process instance or null if it is not related to a process * instance. */ public String getProcessInstanceId() { return processInstanceId; } /** * The id of the activity in the process defining this task or null if this is * not related to a process */ public String getTaskDefinitionKey() { return taskDefinitionKey; } /** * Return the id of the tenant this task belongs to. Can be <code>null</code> * if the task belongs to no single tenant. */ public String getTenantId() { return tenantId; } @Override public String toString() {
return this.getClass().getSimpleName() + "[id=" + id + ", eventName=" + eventName + ", name=" + name + ", createTime=" + createTime + ", lastUpdated=" + lastUpdated + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskDefinitionKey=" + taskDefinitionKey + ", assignee=" + assignee + ", owner=" + owner + ", description=" + description + ", dueDate=" + dueDate + ", followUpDate=" + followUpDate + ", priority=" + priority + ", deleteReason=" + deleteReason + ", caseDefinitionId=" + caseDefinitionId + ", caseExecutionId=" + caseExecutionId + ", caseInstanceId=" + caseInstanceId + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\TaskEvent.java
1
请完成以下Java代码
public CostAmountAndQty negate() {return isZero() ? this : of(amt.negate(), qty.negate());} public CostAmountAndQty mapQty(@NonNull final UnaryOperator<Quantity> qtyMapper) { if (qty.isZero()) { return this; } final Quantity newQty = qtyMapper.apply(qty); if (Objects.equals(qty, newQty)) { return this; } return of(amt, newQty); } public CostAmountAndQty add(@NonNull final CostAmountAndQty other)
{ if (other.isZero()) { return this; } else if (this.isZero()) { return other; } else { return of(this.amt.add(other.amt), this.qty.add(other.qty)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmountAndQty.java
1
请完成以下Java代码
public static double evaluate(String folderPath, String algorithm) { if (folderPath == null) throw new IllegalArgumentException("参数 folderPath == null"); File root = new File(folderPath); if (!root.exists()) throw new IllegalArgumentException(String.format("目录 %s 不存在", root.getAbsolutePath())); if (!root.isDirectory()) throw new IllegalArgumentException(String.format("目录 %s 不是一个目录", root.getAbsolutePath())); ClusterAnalyzer<String> analyzer = new ClusterAnalyzer<String>(); File[] folders = root.listFiles(); if (folders == null) return 1.; ConsoleLogger.logger.start("根目录:%s\n加载中...\n", folderPath); int docSize = 0; int[] ni = new int[folders.length]; String[] cat = new String[folders.length]; int offset = 0; for (File folder : folders) { if (folder.isFile()) continue; File[] files = folder.listFiles(); if (files == null) continue; String category = folder.getName(); cat[offset] = category; ConsoleLogger.logger.out("[%s]...", category); int b = 0; int e = files.length; int logEvery = (int) Math.ceil((e - b) / 10000f); for (int i = b; i < e; i++) { analyzer.addDocument(folder.getName() + " " + files[i].getName(), IOUtil.readTxt(files[i].getAbsolutePath())); if (i % logEvery == 0) { ConsoleLogger.logger.out("%c[%s]...%.2f%%", 13, category, MathUtility.percentage(i - b + 1, e - b)); } ++docSize; ++ni[offset];
} ConsoleLogger.logger.out(" %d 篇文档\n", e - b); ++offset; } ConsoleLogger.logger.finish(" 加载了 %d 个类目,共 %d 篇文档\n", folders.length, docSize); ConsoleLogger.logger.start(algorithm + "聚类中..."); List<Set<String>> clusterList = algorithm.replaceAll("[-\\s]", "").toLowerCase().equals("kmeans") ? analyzer.kmeans(ni.length) : analyzer.repeatedBisection(ni.length); ConsoleLogger.logger.finish(" 完毕。\n"); double[] fi = new double[ni.length]; for (int i = 0; i < ni.length; i++) { for (Set<String> j : clusterList) { int nij = 0; for (String d : j) { if (d.startsWith(cat[i])) ++nij; } if (nij == 0) continue; double p = nij / (double) (j.size()); double r = nij / (double) (ni[i]); double f = 2 * p * r / (p + r); fi[i] = Math.max(fi[i], f); } } double f = 0; for (int i = 0; i < fi.length; i++) { f += fi[i] * ni[i] / docSize; } return f; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\cluster\ClusterAnalyzer.java
1
请在Spring Boot框架中完成以下Java代码
public class JwtUtils { private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); @Value("${baeldung.app.jwtSecret}") private String jwtSecret; @Value("${baeldung.app.jwtExpirationMs}") private int jwtExpirationMs; public String generateJwtToken(Authentication authentication) { UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); return Jwts.builder() .subject((userPrincipal.getUsername())) .issuedAt(new Date()) .expiration(new Date((new Date()).getTime() + jwtExpirationMs)) .signWith(getSigningKey()) .compact(); } private SecretKey getSigningKey() { byte[] keyBytes = Decoders.BASE64.decode(jwtSecret); return Keys.hmacShaKeyFor(keyBytes); } public String getUserNameFromJwtToken(String token) { return Jwts.parser() .verifyWith(getSigningKey()) .build() .parseSignedClaims(token) .getPayload() .getSubject();
} public boolean validateJwtToken(String authToken) { try { Jwts.parser() .verifyWith(getSigningKey()) .build() .parseSignedClaims(authToken); return true; } catch (SignatureException e) { logger.error("Invalid JWT signature: {}", e.getMessage()); } catch (MalformedJwtException e) { logger.error("Invalid JWT token: {}", e.getMessage()); } catch (ExpiredJwtException e) { logger.error("JWT token is expired: {}", e.getMessage()); } catch (UnsupportedJwtException e) { logger.error("JWT token is unsupported: {}", e.getMessage()); } catch (IllegalArgumentException e) { logger.error("JWT claims string is empty: {}", e.getMessage()); } return false; } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\jwtconfig\JwtUtils.java
2
请完成以下Java代码
public void handle(OrderProcessContext orderProcessContext) { setAllowStateList(); preHandle(orderProcessContext); // 获取订单当前状态 OrderStateEnum curOrderState = getOrderState(orderProcessContext); // 幂等性检查 checkIdempotency(curOrderState, allowStateList); afterHandle(orderProcessContext); } /** * 检查幂等性 * @param curOrderState 订单当前的状态 * @param allowStateList 订单允许的状态列表 */ private void checkIdempotency(OrderStateEnum curOrderState, List<OrderStateEnum> allowStateList) { // allowStateList为空 if (CollectionUtils.isEmpty(allowStateList)) { throw new CommonSysException(ExpCodeEnum.AllowStateList_NULL); } for (OrderStateEnum orderStateEnum : allowStateList) { if (orderStateEnum == curOrderState) { // 幂等性检查通过 return; } } // 幂等性检查不通过 throw new CommonBizException(ExpCodeEnum.NO_REPEAT); } /**
* 获取当前订单的状态 * @param orderProcessContext 订单受理上下文 * @return 订单状态 */ private OrderStateEnum getOrderState(OrderProcessContext orderProcessContext) { // 获取订单ID String orderId = orderProcessContext.getOrderProcessReq().getOrderId(); if (StringUtils.isEmpty(orderId)) { throw new CommonBizException(ExpCodeEnum.PROCESSREQ_ORDERID_NULL); } // 查询订单 OrderQueryReq orderQueryReq = new OrderQueryReq(); orderQueryReq.setId(orderId); List<OrdersEntity> ordersEntityList = orderDAO.findOrders(orderQueryReq); // 订单不存在 if (CollectionUtils.isEmpty(ordersEntityList)) { throw new CommonBizException(ExpCodeEnum.ORDER_NULL); } // 获取订单状态 // TODO 更新订单状态时,要连带更新order表中的状态 OrderStateEnum orderStateEnum = ordersEntityList.get(0).getOrderStateEnum(); // 订单存在 & 订单状态不存在 if (orderStateEnum == null) { throw new CommonBizException(ExpCodeEnum.ORDER_STATE_NULL); } // 返回订单状态 return orderStateEnum; } /** * 设置订单允许的状态(子类必须重写这个函数) */ protected abstract void setAllowStateList(); }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\idempotent\BaseIdempotencyComponent.java
1
请完成以下Java代码
default IHUProductStorage getSingleHUProductStorage(final I_M_HU hu) {return getHUStorageFactory().getSingleHUProductStorage(hu);} /** * @return attribute storage factory; never return null */ IAttributeStorageFactory getHUAttributeStorageFactory(); /** * @return processing date to be used */ ZonedDateTime getDate(); /** * Returns the collector that is supposed to be used to keep track of packaging material that was allocated/"picked up" during the creation of new HUs, and the packaging material that was * released/discarded during the destruction of HUs. * <p> * task 07617 */ IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> getHUPackingMaterialsCollector(); /** * @return transaction listeners */ IHUTrxListener getTrxListeners(); /** * @return previously added listeners that want to be notified before an empty HU is destroyed */ List<EmptyHUListener> getEmptyHUListeners(); /** * Flush the contents stored only in memory. * Useful for example to persist the HU Attributes. */ void flush();
/** * Temporarily make sure that the given HU is not destroyed. * We sometimes need this when splitting out something from a TU that is on an LU * and the new TU has to be on the same LU. * Without this, the LU might be destroyed after the old TU was destroyed (if it was the last one) and before the new TU was added. * * @return a closable that makes the HUId destructible again. * Note that the result of {@link #copyAsMutable()} contains a copy and this closable won'T remove the HuId from the copy. */ IAutoCloseable temporarilyDontDestroyHU(@NonNull HuId huId); /** * @return {@code true} if the HU shall not be destroyed right now */ boolean isDontDestroyHu(@NonNull HuId ofRepoId); boolean isPropertyTrue(@NonNull String propertyName); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHUContext.java
1
请完成以下Java代码
private BPartnerLocationAndCaptureId getShipFromBPartnerAndLocation(final I_M_InOut shipment) { final WarehouseId warehouseId = WarehouseId.ofRepoId(shipment.getM_Warehouse_ID()); return warehouseDAO.getWarehouseLocationById(warehouseId); } @NonNull private List<CreatePackagesRequest> buildCreatePackageRequest( @NonNull final ShipperId shipperId, @NonNull final CreatePackagesForInOutRequest request, @NonNull final ShippingWeightCalculator weightCalculator) { if (Check.isEmpty(request.getPackageInfos())) { return huInOutDAO.retrieveShippedHandlingUnits(request.getShipment()) .stream() .map(hu -> CreatePackagesRequest.builder() .inOutId(request.getShipmentId()) .shipperId(shipperId) .processed(request.isProcessed()) .weightInKg(weightCalculator.calculateWeightInKg(hu) .map(weight -> weight.toBigDecimal()) .orElse(null)) .packageDimensions(extractPackageDimensions(hu)) .build()) .collect(Collectors.toList()); } else { return request.getPackageInfos() .stream() .map(packageInfo -> CreatePackagesRequest.builder() .inOutId(request.getShipmentId()) .shipperId(shipperId) .processed(request.isProcessed()) // .trackingCode(packageInfo.getTrackingNumber()) .trackingURL(packageInfo.getTrackingUrl()) .weightInKg(packageInfo.getWeight()) .packageDimensions(packageInfo.getPackageDimensions()) .build()
) .collect(ImmutableList.toImmutableList()); } } private PackageDimensions extractPackageDimensions(final I_M_HU hu) { final PackageDimensions packageDimensions = huPackageBL.getPackageDimensions(hu); if (packageDimensions.isUnspecified()) { throw new AdempiereException(MSG_CANNOT_DETERMINE_HU_PACKAGE_DIMENSIONS, hu.getM_HU_ID()); } return packageDimensions; } private void linkTransportationToShipment(@NonNull final I_M_InOut shipment, @NonNull final ShipperTransportationId shipperTransportationId) { final de.metas.inout.model.I_M_InOut inOutShipment = InterfaceWrapperHelper.create(shipment, de.metas.inout.model.I_M_InOut.class); inOutShipment.setM_ShipperTransportation_ID(shipperTransportationId.getRepoId()); inOutDAO.save(inOutShipment); } private ShippingWeightCalculator newWeightCalculator() { return ShippingWeightCalculator.builder() .weightSourceTypes(getWeightsSourceTypes()) .build(); } private ShippingWeightSourceTypes getWeightsSourceTypes() { return ShippingWeightSourceTypes.ofCommaSeparatedString(sysConfigBL.getValue(SYSCONFIG_WeightSourceTypes)).orElse(ShippingWeightSourceTypes.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\impl\HUShipperTransportationBL.java
1
请完成以下Java代码
public class FamilyMembers { // private final Long id; private String firstName; private String lastName; private int age; private String nation; public FamilyMembers(Long id, String firstName, String lastName, int age, String nation) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.age = age; this.nation = nation; } public Long getId() { return id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) {
this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public String getNation() { return nation; } public void setNation(String nation) { this.nation = nation; } }
repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSourceCode\SpringBootFamilyMember\src\main\java\spring\basic\FamilyMembers.java
1
请完成以下Java代码
public void createRandomProduct(@PathVariable final Integer storeId) { storeService.createRandomProduct(storeId); } @PostMapping("/stores/{storeId}/rebrand") public void rebrandStore(@PathVariable final Integer storeId, @RequestBody RebrandStoreDto rebrandStoreDto) { storeService.rebrandStore(storeId, rebrandStoreDto.name); } @PostMapping(value = "/stores/{storeId}/products/{productId}/price", consumes = MediaType.APPLICATION_JSON_VALUE) public void updateProductPrice(@PathVariable final Integer productId, @PathVariable String storeId, @RequestBody UpdatePriceDto priceDto) { storeService.updateProductPrice(productId, priceDto.price); } @GetMapping("/products/{productId}/changes") public String getProductChanges(@PathVariable int productId) { Product product = storeService.findProductById(productId); QueryBuilder jqlQuery = QueryBuilder.byInstance(product); Changes changes = javers.findChanges(jqlQuery.build()); return javers.getJsonConverter().toJson(changes); } @GetMapping("/products/snapshots") public String getProductSnapshots() { QueryBuilder jqlQuery = QueryBuilder.byClass(Product.class); List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build()); return javers.getJsonConverter().toJson(snapshots);
} @GetMapping("/stores/{storeId}/shadows") public String getStoreShadows(@PathVariable int storeId) { Store store = storeService.findStoreById(storeId); JqlQuery jqlQuery = QueryBuilder.byInstance(store) .withChildValueObjects().build(); List<Shadow<Store>> shadows = javers.findShadows(jqlQuery); return javers.getJsonConverter().toJson(shadows.get(0)); } @GetMapping("/stores/snapshots") public String getStoresSnapshots() { QueryBuilder jqlQuery = QueryBuilder.byClass(Store.class); List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build()); return javers.getJsonConverter().toJson(snapshots); } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\web\StoreController.java
1
请完成以下Java代码
public static void stoppableSleep(@Nullable MessageListenerContainer container, long interval) throws InterruptedException { conditionalSleep(Objects.requireNonNull(container)::isRunning, interval); } /** * Sleep for the desired timeout, as long as shouldSleepCondition supplies true. * @param shouldSleepCondition to. * @param interval the timeout. * @throws InterruptedException if the thread is interrupted. * @since 3.0.9 */ public static void conditionalSleep(Supplier<Boolean> shouldSleepCondition, long interval) throws InterruptedException { long timeout = System.currentTimeMillis() + interval; long sleepInterval = interval > SMALL_INTERVAL_THRESHOLD ? DEFAULT_SLEEP_INTERVAL : SMALL_SLEEP_INTERVAL; do { Thread.sleep(sleepInterval); if (!shouldSleepCondition.get()) { break; } } while (System.currentTimeMillis() < timeout); } /** * Sleep for the desired timeout, as long as shouldSleepCondition supplies true. * This method requires that the consumer is paused; otherwise, ConsumerRecord may be lost. * Periodically calls {@code Consumer.poll(Duration.ZERO)} to prevent a paused consumer from being rebalanced. * @param shouldSleepCondition to. * @param interval the timeout. * @param consumer the kafka consumer to call poll(). * @throws InterruptedException if the thread is interrupted. */ public static void conditionalSleepWithPoll(Supplier<Boolean> shouldSleepCondition, long interval, Consumer<?, ?> consumer) throws InterruptedException { boolean isFirst = true; long timeout = System.currentTimeMillis() + interval;
long sleepInterval = interval > SMALL_INTERVAL_THRESHOLD ? DEFAULT_SLEEP_INTERVAL : SMALL_SLEEP_INTERVAL; do { Thread.sleep(sleepInterval); if (!shouldSleepCondition.get()) { break; } if (isFirst) { isFirst = false; } else { // To prevent consumer group rebalancing during retry backoff. consumer.poll(Duration.ZERO); } } while (System.currentTimeMillis() < timeout); } /** * Create a new {@link OffsetAndMetadata} using the given container and offset. * @param container a container. * @param offset an offset. * @return an offset and metadata. * @since 2.8.6 */ public static OffsetAndMetadata createOffsetAndMetadata(@Nullable MessageListenerContainer container, long offset) { Assert.state(container != null, "Container cannot be null"); final OffsetAndMetadataProvider metadataProvider = container.getContainerProperties() .getOffsetAndMetadataProvider(); if (metadataProvider != null) { return metadataProvider.provide(new DefaultListenerMetadata(container), offset); } return new OffsetAndMetadata(offset); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ListenerUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class AlbertaPrescriptionRequestDAO { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); private final AlbertaPatientRepository albertaPatientRepository; public AlbertaPrescriptionRequestDAO(@NonNull final AlbertaPatientRepository albertaPatientRepository) { this.albertaPatientRepository = albertaPatientRepository; } @NonNull public List<I_Alberta_PrescriptionRequest> getByOrderIds(@NonNull final Set<OrderId> orderIds) { return queryBL.createQueryBuilder(I_Alberta_PrescriptionRequest.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_Alberta_PrescriptionRequest.COLUMN_C_Order_ID, orderIds) .create() .list(); }
@Nullable public I_C_BPartner getPayer(@NonNull final I_Alberta_PrescriptionRequest prescriptionRequest) { final BPartnerId patientBPartnerId = BPartnerId.ofRepoId(prescriptionRequest.getC_BPartner_Patient_ID()); final Optional<AlbertaPatient> albertaPatient = albertaPatientRepository.getByBPartnerId(patientBPartnerId); if (!albertaPatient.isPresent()) { return null; } if (albertaPatient.get().getPayerId() == null) { return null; } final BPartnerId payerId = albertaPatient.get().getPayerId(); return bpartnerDAO.getById(payerId, I_C_BPartner.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\prescription\dao\AlbertaPrescriptionRequestDAO.java
2
请完成以下Java代码
public class JsonAlbertaBPartner { @ApiModelProperty(position = 20) @Nullable private Boolean isArchived; @ApiModelProperty(hidden = true) private boolean archivedSet; @ApiModelProperty(position = 30) @Nullable private String title; @ApiModelProperty(hidden = true) private boolean titleSet; @ApiModelProperty(position = 40) @Nullable private String titleShort; @ApiModelProperty(hidden = true) private boolean titleShortSet; @ApiModelProperty(position = 50) @Nullable private Instant timestamp; @ApiModelProperty(hidden = true) private boolean timestampSet;
public void setIsArchived(@Nullable final Boolean isArchived) { this.isArchived = isArchived; this.archivedSet = true; } public void setTitle(@Nullable final String title) { this.title = title; this.titleSet = true; } public void setTitleShort(@Nullable final String titleShort) { this.titleShort = titleShort; this.titleShortSet = true; } public void setTimestamp(@Nullable final Instant timestamp) { this.timestamp = timestamp; this.timestampSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaBPartner.java
1
请完成以下Java代码
public static class PDFs { @XmlElement(name = "Frachtbrief") protected byte[] frachtbrief; @XmlElement(name = "Routerlabel") protected byte[] routerlabel; @XmlElement(name = "RouterlabelZebra") protected byte[] routerlabelZebra; /** * Gets the value of the frachtbrief property. * * @return * possible object is * byte[] */ public byte[] getFrachtbrief() { return frachtbrief; } /** * Sets the value of the frachtbrief property. * * @param value * allowed object is * byte[] */ public void setFrachtbrief(byte[] value) { this.frachtbrief = value; } /** * Gets the value of the routerlabel property. * * @return * possible object is * byte[] */ public byte[] getRouterlabel() { return routerlabel; } /** * Sets the value of the routerlabel property. * * @param value * allowed object is * byte[] */ public void setRouterlabel(byte[] value) {
this.routerlabel = value; } /** * Gets the value of the routerlabelZebra property. * * @return * possible object is * byte[] */ public byte[] getRouterlabelZebra() { return routerlabelZebra; } /** * Sets the value of the routerlabelZebra property. * * @param value * allowed object is * byte[] */ public void setRouterlabelZebra(byte[] value) { this.routerlabelZebra = value; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\Label.java
1
请完成以下Java代码
public String getAsString() {return barcode;} /** * @return true if standard/fixed code (i.e. not starting with prefix 28 nor 29) */ public boolean isFixed() {return prefix.isFixed();} public boolean isVariable() {return prefix.isFixed();} /** * @return true if variable weight EAN13 (i.e. starts with prefix 28) */ public boolean isVariableWeight() {return prefix.isVariableWeight();} /** * @return true if internal or variable measure EAN13 (i.e. starts with prefix 29)
*/ public boolean isInternalUseOrVariableMeasure() {return prefix.isInternalUseOrVariableMeasure();} public Optional<BigDecimal> getWeightInKg() {return Optional.ofNullable(weightInKg);} public GTIN toGTIN() {return GTIN.ofEAN13(this);} public boolean isMatching(@NonNull final EAN13ProductCode expectedProductNo) { return EAN13ProductCode.equals(this.productNo, expectedProductNo); } public boolean productCodeEndsWith(final @NonNull EAN13ProductCode expectedProductCode) { return this.productNo.endsWith(expectedProductCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\ean13\EAN13.java
1
请完成以下Java代码
public QueueStats findByTenantIdQueueNameAndServiceId(TenantId tenantId, String queueName, String serviceId) { return DaoUtil.getData(queueStatsRepository.findByTenantIdAndQueueNameAndServiceId(tenantId.getId(), queueName, serviceId)); } @Override public PageData<QueueStats> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(queueStatsRepository.findByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public void deleteByTenantId(TenantId tenantId) { queueStatsRepository.deleteByTenantId(tenantId.getId()); } @Override
public List<QueueStats> findByIds(TenantId tenantId, List<QueueStatsId> queueStatsIds) { return DaoUtil.convertDataList(queueStatsRepository.findByTenantIdAndIdIn(tenantId.getId(), toUUIDs(queueStatsIds))); } @Override public List<QueueStatsFields> findNextBatch(UUID id, int batchSize) { return queueStatsRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.QUEUE_STATS; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\queue\JpaQueueStatsDao.java
1
请在Spring Boot框架中完成以下Java代码
public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } @ApiModelProperty(example = "kermit") public String getEndUserId() { return endUserId; } public void setEndUserId(String endUserId) { this.endUserId = endUserId; } @ApiModelProperty(example = "3") public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "null") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } @ApiModelProperty(example = "active") public String getState() { return state; } public void setState(String state) { this.state = state; } @ApiModelProperty(example = "123") public String getCallbackId() {
return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case") public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java
2
请完成以下Java代码
public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() {
return get_ValueAsInt(COLUMNNAME_ExternalSystem_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.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_ExportAudit.java
1
请完成以下Java代码
public void setCM_Ad_Cat_ID (int CM_Ad_Cat_ID) { if (CM_Ad_Cat_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Ad_Cat_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Ad_Cat_ID, Integer.valueOf(CM_Ad_Cat_ID)); } /** Get Advertisement Category. @return Advertisement Category like Banner Homepage */ public int getCM_Ad_Cat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Ad_Cat_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_WebProject getCM_WebProject() throws RuntimeException { return (I_CM_WebProject)MTable.get(getCtx(), I_CM_WebProject.Table_Name) .getPO(getCM_WebProject_ID(), get_TrxName()); } /** Set Web Project. @param CM_WebProject_ID A web project is the main data container for Containers, URLs, Ads, Media etc. */ public void setCM_WebProject_ID (int CM_WebProject_ID) { if (CM_WebProject_ID < 1) set_Value (COLUMNNAME_CM_WebProject_ID, null); else set_Value (COLUMNNAME_CM_WebProject_ID, Integer.valueOf(CM_WebProject_ID)); } /** Get Web Project. @return A web project is the main data container for Containers, URLs, Ads, Media etc. */ public int getCM_WebProject_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_WebProject_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 Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** 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_CM_Ad_Cat.java
1
请完成以下Java代码
public void setReadWrite (boolean rw) { if (this.readWrite == rw) { return; } setEnabled(rw); setBackground(false); } // setReadWrite /** * Get ReadWrite * @return true if rw */ @Override public boolean isReadWrite() { return readWrite; } // getReadWrite /** * Set Mandatory * @param mandatory */ @Override public void setMandatory (final boolean mandatory) { if (this.m_mandatory == mandatory) { return; } m_mandatory = mandatory; setBackground(false); } // setMandatory /** * Get Mandatory * @return true if mandatory */ @Override public boolean isMandatory() { return m_mandatory; } // isMandatory /** * Set Background - nop * @param color */ @Override public void setBackground(Color color) { } /** * Set Background * @param error */ @Override public void setBackground(boolean error) { if (error) super.setBackground(AdempierePLAF.getFieldBackground_Error()); else if (!isReadWrite()) super.setBackground(AdempierePLAF.getFieldBackground_Inactive()); else if (isMandatory()) super.setBackground(AdempierePLAF.getFieldBackground_Mandatory()); else super.setBackground(AdempierePLAF.getFieldBackground_Normal()); } /** * Property Change * @param evt */ @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) setValue(evt.getNewValue()); // metas: request focus (2009_0027_G131) if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS)) requestFocus(); // metas end } // propertyChange /** * Start dialog and set value
*/ private final void onButtonPressed() { try { // Show the dialog final VImageDialog vid = new VImageDialog(Env.getWindow(m_WindowNo), m_WindowNo, m_mImage); vid.setVisible(true); // Do nothing if user canceled (i.e. closed the window) if (vid.isCanceled()) { return; } final int AD_Image_ID = vid.getAD_Image_ID(); final Integer newValue = AD_Image_ID > 0 ? AD_Image_ID : null; // m_mImage = null; // force reload setValue(newValue); // set explicitly // try { fireVetoableChange(m_columnName, null, newValue); } catch (PropertyVetoException pve) {} } catch (Exception e) { Services.get(IClientUI.class).error(m_WindowNo, e); } } // actionPerformed // Field for Value Preference private GridField m_mField = null; /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField */ @Override public void setField (GridField mField) { m_mField = mField; } // setField @Override public GridField getField() { return m_mField; } // metas @Override public boolean isAutoCommit() { return true; } } // VImage
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VImage.java
1
请完成以下Java代码
public String toString() { return isNoLimit() ? "NO_LIMIT" : String.valueOf(value); } public int toInt() { if (isNoLimit()) { throw new AdempiereException("Calling toInt() to NO_LIMIT instances is not allowed. Use toIntOrZero()"); } return value; } @JsonValue public int toIntOrZero() { return value; } public int toIntOrInfinit() { return toIntOr(Integer.MAX_VALUE); } public int toIntOr(final int noLimitValue) { return isNoLimit() ? noLimitValue : value; } public boolean isLimited() { return !isNoLimit(); } public boolean isNoLimit() { return isNoLimit(value); } private static boolean isNoLimit(final int value) { return value <= 0; } public QueryLimit ifNoLimitUse(final int limit) { return isNoLimit() ? ofInt(limit) : this; } @SuppressWarnings("unused") public QueryLimit ifNoLimitUse(@NonNull final QueryLimit limit) { return isNoLimit() ? limit : this; } public boolean isLessThanOrEqualTo(final int other) { return isLimited() && value <= other; } public boolean isLimitHitOrExceeded(@NonNull final Collection<?> collection) { return isLimitHitOrExceeded(collection.size()); } public boolean isLimitHitOrExceeded(@NonNull final MutableInt countHolder) {
return isLimitHitOrExceeded(countHolder.getValue()); } public boolean isLimitHitOrExceeded(final int count) { return isLimited() && value <= count; } public boolean isBelowLimit(@NonNull final Collection<?> collection) { return isNoLimit() || value > collection.size(); } public QueryLimit minusSizeOf(@NonNull final Collection<?> collection) { if (isNoLimit() || collection.isEmpty()) { return this; } else { final int collectionSize = collection.size(); final int newLimitInt = value - collectionSize; if (newLimitInt <= 0) { throw new AdempiereException("Invalid collection size. It shall be less than " + value + " but it was " + collectionSize); } return ofInt(newLimitInt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\QueryLimit.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setES_CreateIndexCommand (final java.lang.String ES_CreateIndexCommand) { set_Value (COLUMNNAME_ES_CreateIndexCommand, ES_CreateIndexCommand); } @Override public java.lang.String getES_CreateIndexCommand() { return get_ValueAsString(COLUMNNAME_ES_CreateIndexCommand); } @Override public void setES_DocumentToIndexTemplate (final java.lang.String ES_DocumentToIndexTemplate) { set_Value (COLUMNNAME_ES_DocumentToIndexTemplate, ES_DocumentToIndexTemplate); } @Override public java.lang.String getES_DocumentToIndexTemplate() { return get_ValueAsString(COLUMNNAME_ES_DocumentToIndexTemplate); } @Override public void setES_FTS_Config_ID (final int ES_FTS_Config_ID) { if (ES_FTS_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, null);
else set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID); } @Override public int getES_FTS_Config_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID); } @Override public void setES_Index (final java.lang.String ES_Index) { set_Value (COLUMNNAME_ES_Index, ES_Index); } @Override public java.lang.String getES_Index() { return get_ValueAsString(COLUMNNAME_ES_Index); } @Override public void setES_QueryCommand (final java.lang.String ES_QueryCommand) { set_Value (COLUMNNAME_ES_QueryCommand, ES_QueryCommand); } @Override public java.lang.String getES_QueryCommand() { return get_ValueAsString(COLUMNNAME_ES_QueryCommand); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Config.java
1
请完成以下Java代码
public class DBNoConnectionException extends DBException { /** * */ private static final long serialVersionUID = -2725091243007392188L; public static final DBNoConnectionException wrapIfNeeded(final Throwable throwable) { if (throwable == null) { return null; } else if (throwable instanceof DBNoConnectionException) { return (DBNoConnectionException)throwable; } else { return new DBNoConnectionException(throwable.getLocalizedMessage(), throwable); } }
private static final String MSG = "@NoDBConnection@"; public DBNoConnectionException() { super(MSG); } public DBNoConnectionException(final String additionalMessage) { super(MSG + ": " + additionalMessage); } public DBNoConnectionException(final String additionalMessage, final Throwable cause) { super(MSG + ": " + additionalMessage, cause); } private DBNoConnectionException(Throwable cause) { super(MSG, cause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\exceptions\DBNoConnectionException.java
1
请完成以下Java代码
public void setMD_Stock_ID (final int MD_Stock_ID) { if (MD_Stock_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Stock_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Stock_ID, MD_Stock_ID); } @Override public int getMD_Stock_ID() { return get_ValueAsInt(COLUMNNAME_MD_Stock_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); }
@Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_Value (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Stock.java
1
请完成以下Java代码
public IoSpecification newInstance(ModelTypeInstanceContext instanceContext) { return new IoSpecificationImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); dataInputCollection = sequenceBuilder.elementCollection(DataInput.class) .build(); dataOutputCollection = sequenceBuilder.elementCollection(DataOutput.class) .build(); inputSetCollection = sequenceBuilder.elementCollection(InputSet.class) .required() .build(); outputSetCollection = sequenceBuilder.elementCollection(OutputSet.class) .required() .build(); typeBuilder.build(); } public IoSpecificationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext); } public Collection<DataInput> getDataInputs() { return dataInputCollection.get(this); } public Collection<DataOutput> getDataOutputs() { return dataOutputCollection.get(this); } public Collection<InputSet> getInputSets() { return inputSetCollection.get(this); } public Collection<OutputSet> getOutputSets() { return outputSetCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\IoSpecificationImpl.java
1
请完成以下Spring Boot application配置
spring: profiles: # fixed-backoff, exponential-backoff, exponential-random-backoff active: fixed-backoff application: name: ribbon-client weather-service: ribbon: eureka: enabled: false listOfServers: http://localhost:8021, http://localhost:8022 ServerListRefreshInterv
al: 5000 MaxAutoRetries: 3 MaxAutoRetriesNextServer: 1 OkToRetryOnAllOperations: true retryableStatusCodes: 503, 408
repos\tutorials-master\spring-cloud-modules\spring-cloud-ribbon-retry\ribbon-client-service\src\main\resources\application.yml
2
请完成以下Java代码
private void handleAlbertaInfo( @NonNull final OrgId orgId, @NonNull final SyncAdvise syncAdvise, @NonNull final JsonRequestBPartnerUpsertItem requestItem, @NonNull final JsonResponseBPartnerCompositeUpsertItem result) { final JsonRequestComposite requestBPartnerComposite = requestItem.getBpartnerComposite(); final JsonCompositeAlbertaBPartner compositeAlbertaBPartner = requestBPartnerComposite.getCompositeAlbertaBPartner(); if (compositeAlbertaBPartner != null) { final BPartnerId bPartnerId = BPartnerId.ofRepoId(result.getResponseBPartnerItem().getMetasfreshId().getValue()); albertaBPartnerCompositeService.upsertAlbertaCompositeInfo(orgId, bPartnerId, compositeAlbertaBPartner, syncAdvise); } if (!requestBPartnerComposite.getContactsNotNull().getRequestItems().isEmpty() && !Check.isEmpty(result.getResponseContactItems())) { final Map<String, JsonMetasfreshId> contactIdentifierToMetasfreshId = result.getResponseContactItems() .stream() .collect(ImmutableMap.toImmutableMap(JsonResponseUpsertItem::getIdentifier, JsonResponseUpsertItem::getMetasfreshId)); final SyncAdvise effectiveSyncAdvise = CoalesceUtil.coalesceNotNull(requestBPartnerComposite.getContactsNotNull().getSyncAdvise(), syncAdvise);
requestItem.getBpartnerComposite().getContactsNotNull().getRequestItems() .stream() .filter(contactRequestItem -> contactRequestItem.getJsonAlbertaContact() != null) .forEach(contactRequestItem -> { final JsonMetasfreshId contactMetasfreshId = contactIdentifierToMetasfreshId.get(contactRequestItem.getContactIdentifier()); if (contactMetasfreshId == null) { throw MissingResourceException.builder() .resourceName("BPartnerContact") .resourceIdentifier(contactRequestItem.getContactIdentifier()) .parentResource(requestBPartnerComposite) .build(); } albertaBPartnerCompositeService.upsertAlbertaContact(UserId.ofRepoId(contactMetasfreshId.getValue()), contactRequestItem.getJsonAlbertaContact(), effectiveSyncAdvise); }); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\bpartnercomposite\jsonpersister\JsonPersisterService.java
1
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("name", this.name); persistentState.put("key", key); persistentState.put("category", this.category); persistentState.put("createTime", this.createTime); persistentState.put("lastUpdateTime", lastUpdateTime); persistentState.put("version", this.version); persistentState.put("metaInfo", this.metaInfo); persistentState.put("deploymentId", deploymentId); persistentState.put("editorSourceValueId", this.editorSourceValueId); persistentState.put("editorSourceExtraValueId", this.editorSourceExtraValueId); return persistentState; } // getters and setters //////////////////////////////////////////////////////// public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(Date lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getMetaInfo() { return metaInfo; } public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } public String getDeploymentId() { return deploymentId; }
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getEditorSourceValueId() { return editorSourceValueId; } public void setEditorSourceValueId(String editorSourceValueId) { this.editorSourceValueId = editorSourceValueId; } public String getEditorSourceExtraValueId() { return editorSourceExtraValueId; } public void setEditorSourceExtraValueId(String editorSourceExtraValueId) { this.editorSourceExtraValueId = editorSourceExtraValueId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean hasEditorSource() { return this.editorSourceValueId != null; } public boolean hasEditorSourceExtra() { return this.editorSourceExtraValueId != null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setSUMUP_CardReader_ID (final int SUMUP_CardReader_ID) { if (SUMUP_CardReader_ID < 1) set_Value (COLUMNNAME_SUMUP_CardReader_ID, null); else set_Value (COLUMNNAME_SUMUP_CardReader_ID, SUMUP_CardReader_ID); } @Override public int getSUMUP_CardReader_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_CardReader_ID); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID()
{ return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } @Override public void setSUMUP_merchant_code (final java.lang.String SUMUP_merchant_code) { set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code); } @Override public java.lang.String getSUMUP_merchant_code() { return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Config.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isCachable() { return true; } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return LocalDateTime.class.isAssignableFrom(value.getClass()); } @Override public Object getValue(ValueFields valueFields) { Long longValue = valueFields.getLongValue();
if (longValue != null) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneOffset.UTC); } return null; } @Override public void setValue(Object value, ValueFields valueFields) { if (value != null) { valueFields.setLongValue(((LocalDateTime) value).toInstant(ZoneOffset.UTC).toEpochMilli()); } else { valueFields.setLongValue(null); } } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\LocalDateTimeType.java
2
请完成以下Java代码
private static class TaxAmounts { @NonNull @Getter private final Tax tax; @NonNull private final CurrencyPrecision precision; @NonNull @Getter private Money taxBaseAmt; private boolean isTaxCalculated = false; private Money _taxAmt; private Money _reverseChargeAmt; public TaxAmounts(@NonNull final Tax tax, @NonNull final CurrencyId currencyId, @NonNull final CurrencyPrecision precision) { this.tax = tax; this.precision = precision; this.taxBaseAmt = this._taxAmt = this._reverseChargeAmt = Money.zero(currencyId); } public void addTaxBaseAmt(@NonNull final Money taxBaseAmtToAdd) { if (taxBaseAmtToAdd.isZero()) { return; } this.taxBaseAmt = this.taxBaseAmt.add(taxBaseAmtToAdd); this.isTaxCalculated = false; } public Money getTaxAmt() { updateTaxAmtsIfNeeded(); return _taxAmt; } public Money getReverseChargeAmt() { updateTaxAmtsIfNeeded(); return _reverseChargeAmt; } private void updateTaxAmtsIfNeeded() { if (!isTaxCalculated)
{ final CalculateTaxResult result = tax.calculateTax(taxBaseAmt.toBigDecimal(), false, precision.toInt()); this._taxAmt = Money.of(result.getTaxAmount(), taxBaseAmt.getCurrencyId()); this._reverseChargeAmt = Money.of(result.getReverseChargeAmt(), taxBaseAmt.getCurrencyId()); this.isTaxCalculated = true; } } public void updateDocTax(@NonNull final DocTax docTax) { if (!TaxId.equals(tax.getTaxId(), docTax.getTaxId())) { throw new AdempiereException("TaxId not matching: " + this + ", " + docTax); } docTax.setTaxBaseAmt(getTaxBaseAmt().toBigDecimal()); docTax.setTaxAmt(getTaxAmt().toBigDecimal()); docTax.setReverseChargeTaxAmt(getReverseChargeAmt().toBigDecimal()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTaxUpdater.java
1
请完成以下Java代码
public int[] toIdList(int codePoint) { int count; if (codePoint < 0x80) count = 1; else if (codePoint < 0x800) count = 2; else if (codePoint < 0x10000) count = 3; else if (codePoint < 0x200000) count = 4; else if (codePoint < 0x4000000) count = 5; else if (codePoint <= 0x7fffffff) count = 6; else return EMPTYLIST; int[] r = new int[count]; switch (count) { /* note: code falls through cases! */ case 6: r[5] = (char) (0x80 | (codePoint & 0x3f)); codePoint = codePoint >> 6; codePoint |= 0x4000000; case 5: r[4] = (char) (0x80 | (codePoint & 0x3f)); codePoint = codePoint >> 6; codePoint |= 0x200000; case 4: r[3] = (char) (0x80 | (codePoint & 0x3f)); codePoint = codePoint >> 6; codePoint |= 0x10000; case 3: r[2] = (char) (0x80 | (codePoint & 0x3f)); codePoint = codePoint >> 6; codePoint |= 0x800; case 2: r[1] = (char) (0x80 | (codePoint & 0x3f)); codePoint = codePoint >> 6; codePoint |= 0xc0; case 1:
r[0] = (char) codePoint; } return r; } @Override public String toString(int[] ids) { byte[] bytes = new byte[ids.length]; for (int i = 0; i < ids.length; i++) { bytes[i] = (byte) ids[i]; } try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { return null; } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\Utf8CharacterMapping.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_ReplicationStrategy getAD_ReplicationStrategy() { return get_ValueAsPO(COLUMNNAME_AD_ReplicationStrategy_ID, org.compiere.model.I_AD_ReplicationStrategy.class); } @Override public void setAD_ReplicationStrategy(final org.compiere.model.I_AD_ReplicationStrategy AD_ReplicationStrategy) { set_ValueFromPO(COLUMNNAME_AD_ReplicationStrategy_ID, org.compiere.model.I_AD_ReplicationStrategy.class, AD_ReplicationStrategy); } @Override public void setAD_ReplicationStrategy_ID (final int AD_ReplicationStrategy_ID) { if (AD_ReplicationStrategy_ID < 1) set_Value (COLUMNNAME_AD_ReplicationStrategy_ID, null); else set_Value (COLUMNNAME_AD_ReplicationStrategy_ID, AD_ReplicationStrategy_ID); } @Override public int getAD_ReplicationStrategy_ID() { return get_ValueAsInt(COLUMNNAME_AD_ReplicationStrategy_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsEUOneStopShop (final boolean IsEUOneStopShop) { set_Value (COLUMNNAME_IsEUOneStopShop, IsEUOneStopShop); }
@Override public boolean isEUOneStopShop() { return get_ValueAsBoolean(COLUMNNAME_IsEUOneStopShop); } @Override public void setIsSummary (final boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, IsSummary); } @Override public boolean isSummary() { return get_ValueAsBoolean(COLUMNNAME_IsSummary); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org.java
1
请完成以下Spring Boot application配置
# keytool -genkeypair -alias seedappkeyalias -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore seedapp.p12 -validity 2650 server: ssl: key-store-type: PKCS12 key-store: classpath:keys/seedapp.p12
key-store-password: password key-alias: seedappkeyalias http2: enabled: true
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\resources\application-tls.yml
2
请完成以下Java代码
class JdbcAdaptingFlywayConnectionDetailsFactory implements ConnectionDetailsFactory<JdbcConnectionDetails, FlywayConnectionDetails> { @Override public FlywayConnectionDetails getConnectionDetails(JdbcConnectionDetails input) { return new FlywayConnectionDetails() { @Override public @Nullable String getUsername() { return input.getUsername(); } @Override public @Nullable String getPassword() { return input.getPassword();
} @Override public String getJdbcUrl() { return input.getJdbcUrl(); } @Override public String getDriverClassName() { return input.getDriverClassName(); } }; } }
repos\spring-boot-4.0.1\module\spring-boot-flyway\src\main\java\org\springframework\boot\flyway\docker\compose\JdbcAdaptingFlywayConnectionDetailsFactory.java
1
请完成以下Java代码
public int getR_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Anfrageart. @param RequestType Anfrageart */ @Override public void setRequestType (java.lang.String RequestType) { set_Value (COLUMNNAME_RequestType, RequestType); } /** Get Anfrageart. @return Anfrageart */ @Override public java.lang.String getRequestType () { return (java.lang.String)get_Value(COLUMNNAME_RequestType); } /** Set Ergebnis. @param Result Result of the action taken */ @Override public void setResult (java.lang.String Result) { set_Value (COLUMNNAME_Result, Result); } /** Get Ergebnis. @return Result of the action taken */ @Override public java.lang.String getResult () { return (java.lang.String)get_Value(COLUMNNAME_Result); } /** Set Status. @param Status Status */ @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status */ @Override public java.lang.String getStatus () { return (java.lang.String)get_Value(COLUMNNAME_Status); }
/** 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); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Request.java
1
请完成以下Java代码
public class Employee { private String name; private int age; private String department; public Employee(String name, int age, String department) { this.name = name; this.age = age; this.department = department; } public String toStringUsingNullCheck() { return "Name: " + (name != null ? name : "Unknown") + ", Age: " + age + ", Department: " + (department != null ? department : "Unknown"); } public String toStringUsingOptional() { return "Name: " + Optional.ofNullable(name).orElse("Unknown") + ", Age: " + age + ", Department: " + Optional.ofNullable(department).orElse("Unknown"); } private String getDefaultIfNull(String value, String defaultValue) {
return value != null ? value : defaultValue; } public String toStringUsingCustomHelper() { return "Name: " + getDefaultIfNull(name, "Unknown") + ", Age: " + age + ", Department: " + getDefaultIfNull(department, "Unknown"); } public String toStringUsingObjects() { return "Name: " + Objects.toString(name, "Unknown") + ", Age: " + age + ", Department: " + Objects.toString(department, "Unknown"); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-others\src\main\java\com\baeldung\printnullvalues\Employee.java
1
请完成以下Java代码
private boolean appliesToCustomer(@NonNull final BPartnerId customerCandidateId) { if (this.customerId == null) { return true; } return this.customerId.equals(customerCandidateId); } private boolean appliesToProduct(@NonNull final ProductId productId) { if (this.productId == null) { return true; } return this.productId.equals(productId); } private boolean appliesToProductCategory(@NonNull final ProductCategoryId productCategoryId) { if (this.productCategoryId == null) { return true; } return this.productCategoryId.equals(productCategoryId); }
@NonNull public Percent getPercent() { return Percent.of(this.marginPercent); } @Value @Builder public static class MappingCriteria { @NonNull BPartnerId customerId; @NonNull ProductId productId; @NonNull ProductCategoryId productCategoryId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\CustomerTradeMarginLine.java
1
请完成以下Java代码
public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get DB-Tabelle. @return Database Table information */ @Override public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Send Notification. @param IsSendNotification Send Notification */ @Override public void setIsSendNotification (boolean IsSendNotification) { set_Value (COLUMNNAME_IsSendNotification, Boolean.valueOf(IsSendNotification)); } /** Get Send Notification. @return Send Notification */ @Override public boolean isSendNotification () { Object oo = get_Value(COLUMNNAME_IsSendNotification); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_AttachmentListener.java
1
请完成以下Java代码
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = token.getUsername(); Random random = new Random(); Long userId = random.nextLong(); //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配 return new SimpleAccount(new ShiroUser(userId, username, username), "", getName()); } /** * 授权 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用 * * @param principals * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); Set<String> roles = Sets.newHashSet(); Set<String> permissions = Sets.newHashSet(); // try { //TODO 此处需要获取当前用户的所有角色和权限,放入验证器 //登录名为超级管理员账号 // // //获取用户所有角色 // User user = userService.getById( shiroUser.getUserId()); // if (CollectionUtils.isEmpty(user.getRoles())) { // return authorizationInfo; // } // // for (Role role : user.getRoles()) { // //停用的角色不查询权限 // roles.add(role.getName()); // List<Permission> permissionList = permissionService.getByMap(role.getId()); // permissionList.forEach(p -> { // permissions.add(p.getCode()); // }); // } // } catch (ServiceException e) { // logger.error(e.getMessage()); // return authorizationInfo; // } authorizationInfo.setRoles(roles); authorizationInfo.setStringPermissions(permissions); return authorizationInfo; }
@Override public void clearCachedAuthorizationInfo(PrincipalCollection principals) { super.clearCachedAuthorizationInfo(principals); clearAllCache(); } @Override public void clearCachedAuthenticationInfo(PrincipalCollection principals) { super.clearCachedAuthenticationInfo(principals); clearAllCache(); } @Override public void clearCache(PrincipalCollection principals) { super.clearCache(principals); clearAllCache(); } public void clearAllCachedAuthorizationInfo() { if (getAuthorizationCache() != null) { getAuthorizationCache().clear(); } } public void clearAllCachedAuthenticationInfo() { if (getAuthenticationCache() != null) { getAuthenticationCache().clear(); } } public void clearAllCache() { clearAllCachedAuthenticationInfo(); clearAllCachedAuthorizationInfo(); } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroRealm.java
1
请完成以下Java代码
public Evaluatee createEvaluationContext() { final Properties privateCtx = Env.deriveCtx(getCtx()); final PO po = getPO(); final POInfo poInfo = po.getPOInfo(); for (int i = 0; i < poInfo.getColumnCount(); i++) { final Object val; final int dispType = poInfo.getColumnDisplayType(i); if (DisplayType.isID(dispType)) { // make sure we get a 0 instead of a null for foreign keys val = po.get_ValueAsInt(i); } else { val = po.get_Value(i); } if (val == null) { continue; } if (val instanceof Integer) { Env.setContext(privateCtx, "#" + po.get_ColumnName(i), (Integer)val);
} else if (val instanceof String) { Env.setContext(privateCtx, "#" + po.get_ColumnName(i), (String)val); } } return Evaluatees.ofCtx(privateCtx, Env.WINDOW_None, false); } @Override public boolean hasField(final String columnName) { return po.getPOInfo().hasColumnName(columnName); } @Override public Object getFieldValue(final String columnName) { return po.get_Value(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\POZoomSource.java
1
请完成以下Java代码
private void setShipperInternalName( @NonNull final JsonResponseShipmentCandidateBuilder candidateBuilder, @NonNull final ShipmentSchedule shipmentSchedule, @NonNull final Map<ShipperId, String> shipperId2InternalName) { final ShipperId shipperId = shipmentSchedule.getShipperId(); if (shipperId == null) { return;// nothing to do } candidateBuilder.shipperInternalSearchKey(shipperId2InternalName.get(shipperId)); } private void setOrderReferences( @NonNull final JsonResponseShipmentCandidateBuilder candidateBuilder, @NonNull final ShipmentSchedule shipmentSchedule, @NonNull final Map<OrderId, I_C_Order> id2Order) { final OrderId orderId = shipmentSchedule.getOrderAndLineId() != null ? shipmentSchedule.getOrderAndLineId().getOrderId() : null; if (orderId == null) { return; // nothing to do } final I_C_Order orderRecord = id2Order.get(orderId); if (orderRecord == null)
{ Loggables.withLogger(logger, Level.WARN).addLog("*** WARNING: No I_C_Order was found in id2Order: {} for orderId: {}!", id2Order, orderId); return; } candidateBuilder.orderDocumentNo(orderRecord.getDocumentNo()); candidateBuilder.poReference(orderRecord.getPOReference()); candidateBuilder.deliveryInfo(orderRecord.getDeliveryInfo()); } private static class ShipmentCandidateExportException extends AdempiereException { public ShipmentCandidateExportException(final String message) { super(message); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ShipmentCandidateAPIService.java
1
请完成以下Java代码
public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public List<String> getCandidateUsers() { return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } @Override public CasePageTask clone() { CasePageTask clone = new CasePageTask();
clone.setValues(this); return clone; } public void setValues(CasePageTask otherElement) { super.setValues(otherElement); setType(otherElement.getType()); setFormKey(otherElement.getFormKey()); setSameDeployment(otherElement.isSameDeployment()); setLabel(otherElement.getLabel()); setIcon(otherElement.getIcon()); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers())); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CasePageTask.java
1
请完成以下Java代码
public final class MaximumSessionsContext { private final Authentication authentication; private final List<ReactiveSessionInformation> sessions; private final int maximumSessionsAllowed; private final WebSession currentSession; public MaximumSessionsContext(Authentication authentication, List<ReactiveSessionInformation> sessions, int maximumSessionsAllowed, WebSession currentSession) { this.authentication = authentication; this.sessions = sessions; this.maximumSessionsAllowed = maximumSessionsAllowed; this.currentSession = currentSession; }
public Authentication getAuthentication() { return this.authentication; } public List<ReactiveSessionInformation> getSessions() { return this.sessions; } public int getMaximumSessionsAllowed() { return this.maximumSessionsAllowed; } public WebSession getCurrentSession() { return this.currentSession; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\MaximumSessionsContext.java
1
请在Spring Boot框架中完成以下Java代码
public JsonDailyReport execute() { final HashSet<String> addedProductIds = new HashSet<>(); final ArrayList<JsonDailyReportItem> resultItems = new ArrayList<>(); final List<ProductSupply> dailySupplies = productSuppliesService.getProductSupplies(user.getBpartner(), date); for (final ProductSupply productSupply : dailySupplies) { final JsonDailyReportItem item = toJsonDailyReportItem(productSupply); resultItems.add(item); addedProductIds.add(item.getProductId()); } final List<Product> favoriteProducts = productSuppliesService.getUserFavoriteProducts(user); for (final Product product : favoriteProducts) { if (!addedProductIds.add(product.getIdAsString())) { continue; } resultItems.add(toZeroJsonDailyReportItem(product)); } resultItems.sort(Comparator.comparing(JsonDailyReportItem::getProductName)); return JsonDailyReport.builder() .date(date) .dayCaption(DateUtils.getDayName(date, locale)) .products(resultItems) .build(); }
private JsonDailyReportItem toJsonDailyReportItem(final ProductSupply productSupply) { final Product product = productSuppliesService.getProductById(productSupply.getProductId()); return JsonDailyReportItem.builder() .productId(product.getIdAsString()) .productName(product.getName(locale)) .packingInfo(product.getPackingInfo(locale)) .qty(productSupply.getQtyUserEntered()) .confirmedByUser(productSupply.isQtyConfirmedByUser()) .build(); } private JsonDailyReportItem toZeroJsonDailyReportItem(final Product product) { return JsonDailyReportItem.builder() .productId(product.getIdAsString()) .productName(product.getName(locale)) .packingInfo(product.getPackingInfo(locale)) .qty(BigDecimal.ZERO) .confirmedByUser(true) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\dailyReport\JsonDailyReportProducer.java
2
请在Spring Boot框架中完成以下Java代码
public List<ExternalWorkerJobEntity> findJobsByScopeIdAndSubScopeId(String scopeId, String subScopeId) { return dataManager.findJobsByScopeIdAndSubScopeId(scopeId, subScopeId); } @Override public List<ExternalWorkerJobEntity> findJobsByWorkerId(String workerId) { return dataManager.findJobsByWorkerId(workerId); } @Override public List<ExternalWorkerJobEntity> findJobsByWorkerIdAndTenantId(String workerId, String tenantId) { return dataManager.findJobsByWorkerIdAndTenantId(workerId, tenantId); } @Override public List<ExternalWorkerJob> findJobsByQueryCriteria(ExternalWorkerJobQueryImpl jobQuery) { return dataManager.findJobsByQueryCriteria(jobQuery); } @Override public long findJobCountByQueryCriteria(ExternalWorkerJobQueryImpl jobQuery) { return dataManager.findJobCountByQueryCriteria(jobQuery); } @Override public List<ExternalWorkerJobEntity> findExternalJobsToExecute(ExternalWorkerJobAcquireBuilderImpl builder, int numberOfJobs) {
return dataManager.findExternalJobsToExecute(builder, numberOfJobs); } @Override public void delete(ExternalWorkerJobEntity entity, boolean fireDeleteEvent) { deleteByteArrayRef(entity.getExceptionByteArrayRef()); deleteByteArrayRef(entity.getCustomValuesByteArrayRef()); if (serviceConfiguration.getInternalJobManager() != null) { serviceConfiguration.getInternalJobManager().handleJobDelete(entity); } super.delete(entity, fireDeleteEvent); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\ExternalWorkerJobEntityManagerImpl.java
2
请完成以下Java代码
public String toString() { StringBuilder strb = new StringBuilder(); strb .append(executionEntity.getId()) .append(" : ") .append(executionEntity.getActivityId()) .append(", parent id ") .append(executionEntity.getParentId()) .append("\r\n"); List<? extends ExecutionEntity> children = executionEntity.getExecutions(); if (children != null) { for (ExecutionEntity childExecution : children) { internalToString(childExecution, strb, "", true); } } return strb.toString(); } protected void internalToString(ExecutionEntity execution, StringBuilder strb, String prefix, boolean isTail) { strb .append(prefix) .append(isTail ? "└── " : "├── ")
.append(execution.getId()) .append(" : ") .append("activityId=" + execution.getActivityId()) .append(", parent id ") .append(execution.getParentId()) .append(execution.isScope() ? " (scope)" : "") .append(execution.isMultiInstanceRoot() ? " (multi instance root)" : "") .append("\r\n"); List<? extends ExecutionEntity> children = executionEntity.getExecutions(); if (children != null) { for (int i = 0; i < children.size() - 1; i++) { internalToString(children.get(i), strb, prefix + (isTail ? " " : "│ "), false); } if (children.size() > 0) { internalToString(children.get(children.size() - 1), strb, prefix + (isTail ? " " : "│ "), true); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\util\ExecutionTreeStringBuilder.java
1
请完成以下Java代码
public int getPP_Product_BOMVersions_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID); } @Override public void setPP_Product_Planning_ID (final int PP_Product_Planning_ID) { if (PP_Product_Planning_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, PP_Product_Planning_ID); } @Override public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID);
} @Override public void setQty (final @Nullable BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_Maturing_Candidates_v.java
1
请完成以下Java代码
private static POSTerminalPaymentProcessorConfig extractPaymentProcessorConfig(final SumUpTransaction sumUpTrx) { return POSTerminalPaymentProcessorConfig.builder() .type(POSPaymentProcessorType.SumUp) .sumUpConfigId(sumUpTrx.getConfigId()) .build(); } @Nullable private static POSCardReader extractCardReader(@Nullable final SumUpTransaction.CardReader sumUpCardReader) { if(sumUpCardReader == null) { return null; } return POSCardReader.builder() .externalId(POSCardReaderExternalId.ofString(sumUpCardReader.getExternalId().getAsString())) .name(sumUpCardReader.getName()) .build(); } @NonNull public static POSPaymentProcessingStatus toResponseStatus(final @NonNull SumUpTransactionStatus status, final boolean isRefunded) { if (SumUpTransactionStatus.SUCCESSFUL.equals(status)) { return isRefunded ? POSPaymentProcessingStatus.DELETED : POSPaymentProcessingStatus.SUCCESSFUL; } else if (SumUpTransactionStatus.CANCELLED.equals(status)) { return POSPaymentProcessingStatus.CANCELLED; } else if (SumUpTransactionStatus.FAILED.equals(status)) { return POSPaymentProcessingStatus.FAILED; } else if (SumUpTransactionStatus.PENDING.equals(status))
{ return POSPaymentProcessingStatus.PENDING; } else { throw new AdempiereException("Unknown SumUp status: " + status); } } public static SumUpPOSRef toPOSRef(@NonNull final POSOrderAndPaymentId posOrderAndPaymentId) { return SumUpPOSRef.builder() .posOrderId(posOrderAndPaymentId.getOrderId().getRepoId()) .posPaymentId(posOrderAndPaymentId.getPaymentId().getRepoId()) .build(); } @Nullable public static POSOrderAndPaymentId toPOSOrderAndPaymentId(@NonNull final SumUpPOSRef posRef) { return POSOrderAndPaymentId.ofRepoIdsOrNull(posRef.getPosOrderId(), posRef.getPosPaymentId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\payment_gateway\sumup\SumUpUtils.java
1
请完成以下Java代码
public String getModelPackage(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return null; } return entry.getModelPackage(); } public String getWebUIServletListenerClass(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return null; } return entry.getWebUIServletListenerClass(); } public boolean isSystemMaintained(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return false; } return entry.isSystemMaintained(); } } @Value
@VisibleForTesting public static final class EntityTypeEntry { private final String entityType; private final String modelPackage; private final boolean displayedInUI; private final boolean systemMaintained; private final String webUIServletListenerClass; @Builder private EntityTypeEntry( final String entityType, final String modelPackage, final boolean displayedInUI, final boolean systemMaintained, final String webUIServletListenerClass) { super(); this.entityType = entityType; this.modelPackage = modelPackage; this.displayedInUI = displayedInUI; this.systemMaintained = systemMaintained; this.webUIServletListenerClass = webUIServletListenerClass; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\EntityTypesCache.java
1
请完成以下Java代码
public class ApiResponse implements Serializable { /** * 返回信息 */ private String message; /** * 返回数据 */ private Object data; public ApiResponse() { } private ApiResponse(String message, Object data) { this.message = message; this.data = data; } /** * 通用封装获取ApiResponse对象 * * @param message 返回信息 * @param data 返回数据 * @return ApiResponse */
public static ApiResponse of(String message, Object data) { return new ApiResponse(message, data); } /** * 通用成功封装获取ApiResponse对象 * * @param data 返回数据 * @return ApiResponse */ public static ApiResponse ok(Object data) { return new ApiResponse(HttpStatus.OK.getReasonPhrase(), data); } /** * 通用封装获取ApiResponse对象 * * @param message 返回信息 * @return ApiResponse */ public static ApiResponse msg(String message) { return of(message, null); } }
repos\spring-boot-demo-master\demo-task-quartz\src\main\java\com\xkcoding\task\quartz\common\ApiResponse.java
1
请完成以下Java代码
public DistributionJob withChangedLine(final DistributionJobLineId lineId, final UnaryOperator<DistributionJobLine> lineMapper) { return withChangedLines(line -> DistributionJobLineId.equals(line.getId(), lineId) ? lineMapper.apply(line) : line); } public DistributionJobLine getLineById(@NonNull final DistributionJobLineId lineId) { return lines.stream() .filter(line -> DistributionJobLineId.equals(line.getId(), lineId)) .findFirst() .orElseThrow(() -> new AdempiereException("No line found for " + lineId)); } @NonNull public DistributionJobLine getLineByStepId(@NonNull final DistributionJobStepId stepId) { return lines.stream() .filter(line -> line.getStepById(stepId).isPresent()) .findFirst() .orElseThrow(() -> new AdempiereException("No line found for " + stepId)); } @Nullable public String getPlantName() { return plantInfo != null ? plantInfo.getCaption() : null; } public Stream<DistributionJobStep> streamSteps() { return lines.stream().flatMap(line -> line.getSteps().stream()); } public boolean isFullyMoved() { return lines.stream().allMatch(DistributionJobLine::isFullyMoved); } public boolean isInTransit() { return lines.stream().anyMatch(DistributionJobLine::isInTransit); } @Nullable public LocatorId getSinglePickFromLocatorIdOrNull() { return lines.stream() .map(DistributionJobLine::getPickFromLocatorId) .distinct() .collect(GuavaCollectors.singleElementOrNull()); } public Optional<LocatorInfo> getSinglePickFromLocator() { return lines.stream() .map(DistributionJobLine::getPickFromLocator) .distinct() .collect(GuavaCollectors.singleElementOrEmpty()); } @Nullable public LocatorId getSingleDropToLocatorIdOrNull() {
return lines.stream() .map(DistributionJobLine::getDropToLocatorId) .distinct() .collect(GuavaCollectors.singleElementOrNull()); } public Optional<LocatorInfo> getSingleDropToLocator() { return lines.stream() .map(DistributionJobLine::getDropToLocator) .distinct() .collect(GuavaCollectors.singleElementOrEmpty()); } @Nullable public ProductId getSingleProductIdOrNull() { return lines.stream() .map(DistributionJobLine::getProductId) .distinct() .collect(GuavaCollectors.singleElementOrNull()); } @Nullable public Quantity getSingleUnitQuantityOrNull() { final MixedQuantity qty = lines.stream() .map(DistributionJobLine::getQtyToMove) .distinct() .collect(MixedQuantity.collectAndSum()); return qty.toNoneOrSingleValue().orElse(null); } public Optional<DistributionJobLineId> getNextEligiblePickFromLineId(@NonNull final ProductId productId) { return lines.stream() .filter(line -> ProductId.equals(line.getProductId(), productId)) .filter(DistributionJobLine::isEligibleForPicking) .map(DistributionJobLine::getId) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJob.java
1
请完成以下Java代码
public abstract class Parser { protected static final EngineUtilLogger LOG = ProcessEngineLogger.UTIL_LOGGER; protected static final String EXTERNAL_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities"; protected static final String DISALLOW_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl"; protected static final String LOAD_EXTERNAL_DTD = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; protected static final String EXTERNAL_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; protected static final String NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; protected static ThreadLocal<SAXParserFactory> SAX_PARSER_FACTORY_INSTANCE = ThreadLocal.withInitial(SAXParserFactory::newInstance); public abstract Parse createParse(); protected SAXParser getSaxParser() throws Exception { SAXParserFactory saxParserFactory = getSaxParserFactoryLazily(); setXxeProcessing(saxParserFactory); return saxParserFactory.newSAXParser(); } protected SAXParserFactory getSaxParserFactoryLazily() { return Parser.SAX_PARSER_FACTORY_INSTANCE.get(); } protected void enableSchemaValidation(boolean enableSchemaValidation) { SAXParserFactory saxParserFactory = getSaxParserFactoryLazily(); saxParserFactory.setNamespaceAware(enableSchemaValidation); saxParserFactory.setValidating(enableSchemaValidation); try { saxParserFactory.setFeature(NAMESPACE_PREFIXES, true); } catch (Exception e) { LOG.unableToSetSchemaResource(e); } } protected void setXxeProcessing(SAXParserFactory saxParserFactory) { boolean enableXxeProcessing = isEnableXxeProcessing();
saxParserFactory.setXIncludeAware(enableXxeProcessing); try { saxParserFactory.setFeature(EXTERNAL_GENERAL_ENTITIES, enableXxeProcessing); saxParserFactory.setFeature(DISALLOW_DOCTYPE_DECL, !enableXxeProcessing); saxParserFactory.setFeature(LOAD_EXTERNAL_DTD, enableXxeProcessing); saxParserFactory.setFeature(EXTERNAL_PARAMETER_ENTITIES, enableXxeProcessing); saxParserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (Exception e) { throw LOG.exceptionWhileSettingXxeProcessing(e); } } public Boolean isEnableXxeProcessing() { ProcessEngineConfigurationImpl engineConfig = Context.getProcessEngineConfiguration(); if (engineConfig != null) { return engineConfig.isEnableXxeProcessing(); } else { // can be null if implementation is called outside command context return false; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\Parser.java
1
请完成以下Java代码
public long getContentLengthLong() { try { connect(); return this.resources.getContentLength(); } catch (IOException ex) { return -1; } } @Override public String getContentType() { return CONTENT_TYPE; } @Override public long getLastModified() { if (this.lastModified == -1) { try { this.lastModified = Files.getLastModifiedTime(this.resources.getLocation().path()).toMillis(); } catch (IOException ex) { this.lastModified = 0; } } return this.lastModified; } @Override public Permission getPermission() throws IOException { if (this.permission == null) { File file = this.resources.getLocation().path().toFile(); this.permission = new FilePermission(file.getCanonicalPath(), "read"); } return this.permission; } @Override public InputStream getInputStream() throws IOException { connect(); return new ConnectionInputStream(this.resources.getInputStream()); } @Override public void connect() throws IOException { if (this.connected) { return; } this.resources.connect(); this.connected = true; } /** * Connection {@link InputStream}. */
class ConnectionInputStream extends FilterInputStream { private volatile boolean closing; ConnectionInputStream(InputStream in) { super(in); } @Override public void close() throws IOException { if (this.closing) { return; } this.closing = true; try { super.close(); } finally { try { NestedUrlConnection.this.cleanup.clean(); } catch (UncheckedIOException ex) { throw ex.getCause(); } } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnection.java
1
请完成以下Java代码
public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request) { final ManufacturingJobActivityId jobActivityId = request.getWfActivity().getId().getAsId(ManufacturingJobActivityId.class); final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(request.getWfProcess()); final ManufacturingJobActivity activity = job.getActivityById(jobActivityId); final GlobalQRCode scannedQRCode = GlobalQRCode.ofString(request.getScannedBarcode()); validateScannedQRCode(activity, scannedQRCode); final ManufacturingJob changedJob = manufacturingJobService.withScannedQRCode(job, jobActivityId, scannedQRCode); return ManufacturingRestService.toWFProcess(changedJob); } @Nullable private ImmutableList<JsonQRCode> getSourceLocatorQRCodes(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess); final ManufacturingJobActivity activity = job.getActivityById(wfActivity.getId()); if (activity.getSourceLocatorValidate() == null) { return null; } return activity.getSourceLocatorValidate() .getSourceLocatorList() .stream() .map(locatorInfo -> JsonQRCode.builder() .caption(locatorInfo.getCaption()) .qrCode(LocatorQRCode.builder() .locatorId(locatorInfo.getId()) .caption(locatorInfo.getCaption()) .build().toGlobalQRCodeJsonString()) .build()) .collect(ImmutableList.toImmutableList()); } @Nullable private static GlobalQRCode getScannedQRCode(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess);
final ManufacturingJobActivityId jobActivityId = wfActivity.getId().getAsId(ManufacturingJobActivityId.class); final ManufacturingJobActivity jobActivity = job.getActivityById(jobActivityId); return jobActivity.getScannedQRCode(); } private static void validateScannedQRCode( @NonNull final ManufacturingJobActivity activity, @NonNull final GlobalQRCode qrCode) { final ValidateLocatorInfo validateLocatorInfo = activity.getSourceLocatorValidate(); if (validateLocatorInfo == null) { throw new AdempiereException(NO_SOURCE_LOCATOR_ERR_MSG); } if (!LocatorQRCode.isTypeMatching(qrCode)) { throw new AdempiereException(QR_CODE_INVALID_TYPE_ERR_MSG); } final LocatorId scannedLocatorId = LocatorQRCode.ofGlobalQRCode(qrCode).getLocatorId(); if (!validateLocatorInfo.isLocatorIdValid(scannedLocatorId)) { throw new AdempiereException(QR_CODE_DOES_NOT_MATCH_ERR_MSG); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\validateLocator\ValidateLocatorActivityHandler.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } /** * Therapy AD_Reference_ID=541282 * Reference name: Therapy */ public static final int THERAPY_AD_Reference_ID=541282; /** Unknown = 0 */ public static final String THERAPY_Unknown = "0"; /** ParenteralNutrition = 1 */ public static final String THERAPY_ParenteralNutrition = "1"; /** EnteralNutrition = 2 */ public static final String THERAPY_EnteralNutrition = "2"; /** Stoma = 3 */ public static final String THERAPY_Stoma = "3"; /** Tracheostoma = 4 */ public static final String THERAPY_Tracheostoma = "4"; /** Inkontinenz ableitend = 5 */ public static final String THERAPY_InkontinenzAbleitend = "5"; /** Wundversorgung = 6 */ public static final String THERAPY_Wundversorgung = "6"; /** IV-Therapien = 7 */ public static final String THERAPY_IV_Therapien = "7"; /** Beatmung = 8 */ public static final String THERAPY_Beatmung = "8"; /** Sonstiges = 9 */ public static final String THERAPY_Sonstiges = "9"; /** OSA = 10 */ public static final String THERAPY_OSA = "10"; /** Hustenhilfen = 11 */ public static final String THERAPY_Hustenhilfen = "11"; /** Absaugung = 12 */ public static final String THERAPY_Absaugung = "12"; /** Patientenüberwachung = 13 */ public static final String THERAPY_Patientenueberwachung = "13"; /** Sauerstoff = 14 */ public static final String THERAPY_Sauerstoff = "14"; /** Inhalations- und Atemtherapie = 15 */ public static final String THERAPY_Inhalations_UndAtemtherapie = "15"; /** Lagerungshilfsmittel = 16 */ public static final String THERAPY_Lagerungshilfsmittel = "16"; /** Schmerztherapie = 17 */ public static final String THERAPY_Schmerztherapie = "17";
@Override public void setTherapy (final String Therapy) { set_Value (COLUMNNAME_Therapy, Therapy); } @Override public String getTherapy() { return get_ValueAsString(COLUMNNAME_Therapy); } @Override public void setValue (final @Nullable String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaBillableTherapy.java
1
请完成以下Java代码
private static class HUIdsFilterConverter implements SqlDocumentFilterConverter { public static final HUIdsFilterConverter instance = new HUIdsFilterConverter(); @Override public boolean canConvert(final String filterId) { return Objects.equals(filterId, HU_IDS_FilterId); } @Override public FilterSql getSql( final DocumentFilter filter, final SqlOptions sqlOpts, final SqlDocumentFilterConverterContext context) { if (!HU_IDS_FilterId.equals(filter.getFilterId())) { throw new AdempiereException("Invalid filterId " + filter.getFilterId() + ". Expected: " + HU_IDS_FilterId); } final int shipmentScheduleId = context.getPropertyAsInt(PARAM_CurrentShipmentScheduleId, -1); if (shipmentScheduleId <= 0) { return FilterSql.allowNoneWithComment("no shipment schedule"); } final boolean considerAttributes = filter.getParameterValueAsBoolean(PARAM_ConsiderAttributes, false); final List<Integer> huIds = retrieveAvailableHuIdsForCurrentShipmentScheduleId(shipmentScheduleId, considerAttributes); if (huIds.isEmpty()) { return FilterSql.allowNoneWithComment("no M_HU_IDs"); } return FilterSql.ofWhereClause(sqlOpts.getTableNameOrAlias() + "." + I_M_HU.COLUMNNAME_M_HU_ID + " IN " + DB.buildSqlList(huIds));
} } private static List<Integer> retrieveAvailableHuIdsForCurrentShipmentScheduleId( final int shipmentScheduleId, final boolean considerAttributes) { final IHUPickingSlotBL huPickingSlotBL = Services.get(IHUPickingSlotBL.class); final ShipmentScheduleId sScheduleID = ShipmentScheduleId.ofRepoId(shipmentScheduleId); final RetrieveAvailableHUIdsToPickRequest request = RetrieveAvailableHUIdsToPickRequest .builder() .scheduleId(sScheduleID) .considerAttributes(considerAttributes) .onlyTopLevel(false) .build(); return huPickingSlotBL.retrieveAvailableHUIdsToPickForShipmentSchedule(request) .stream() .map(HuId::getRepoId) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\HUsToPickViewFilters.java
1
请在Spring Boot框架中完成以下Java代码
public class WSTerminalHandler implements WebSocketHandler { private static final Logger LOG = LoggerFactory.getLogger(WSTerminalHandler.class); private final Map<String, WebSocketSession> sessions; private final ScheduledExecutorService executorService; public WSTerminalHandler() { this.sessions = new ConcurrentHashMap<>(); this.executorService = Executors.newScheduledThreadPool(8); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { LOG.info("WS Terminal session: {}", session.getId()); this.sessions.put(session.getId(), session); this.executorService.execute(new WSTerminalSession(session)); } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { TextMessage textMessage = (TextMessage)message; String payload = textMessage.getPayload(); LOG.info("WS Terminal message: {} message={}", session.getId(), payload); session.sendMessage(new TextMessage("Echo: " + payload)); } @Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { LOG.info("WS Terminal transport error: {}", session.getId()); this.sessions.remove(session.getId(), session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { LOG.info("WS Terminal connection closed: {}", session.getId()); this.sessions.remove(session.getId(), session); } @Override public boolean supportsPartialMessages() { return false; } @PreDestroy public void close() throws Exception { LOG.info("WS Terminal shutdown"); this.executorService.shutdownNow(); } }
repos\spring-examples-java-17\spring-websockets\src\main\java\itx\examples\springboot\websockets\config\WSTerminalHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class JsonCustomer { @NonNull @JsonProperty("FLAG") Integer flag; @NonNull @JsonProperty("METASFRESHID") JsonMetasfreshId id; @NonNull @JsonProperty("MKDID") String bpartnerValue; @NonNull @JsonProperty("MATCHCODE") String name; @JsonProperty("METASFRESHURL") String url; @JsonProperty("MID") String tenantId; @JsonProperty("KREDITORENNR") Integer creditorId; @JsonProperty("DEBITORENNR") Integer debtorId; @JsonProperty("ANHANGORDNER") String bpartnerDirPath; @JsonProperty("INAKTIV") Integer inactiveBit; @JsonProperty("KDDATA") List<JsonCustomerLocation> locations; @JsonProperty("PERSDATA") List<JsonCustomerContact> contacts; @JsonProperty("REZDET") List<String> bpartnerProductExternalReferences; @Builder public JsonCustomer(
@JsonProperty("FLAG") final @NonNull Integer flag, @JsonProperty("METASFRESHID") final @NonNull JsonMetasfreshId id, @JsonProperty("MKDID") final @NonNull String bpartnerValue, @JsonProperty("MATCHCODE") final @NonNull String name, @JsonProperty("METASFRESHURL") final @Nullable String url, @JsonProperty("MID") final @Nullable String tenantId, @JsonProperty("KREDITORENNR") final @Nullable Integer creditorId, @JsonProperty("DEBITORENNR") final @Nullable Integer debtorId, @JsonProperty("ANHANGORDNER") final @Nullable String bpartnerDirPath, @JsonProperty("INAKTIV") final int inactive, @JsonProperty("KDDATA") final @Nullable List<JsonCustomerLocation> locations, @JsonProperty("PERSDATA") final @Nullable List<JsonCustomerContact> contacts, @JsonProperty("REZDET") final @Nullable List<String> bpartnerProductExternalReferences) { this.flag = flag; this.id = id; this.bpartnerValue = bpartnerValue; this.url = url; this.name = name; this.inactiveBit = inactive; this.tenantId = tenantId; this.creditorId = creditorId; this.debtorId = debtorId; this.bpartnerDirPath = bpartnerDirPath; this.locations = locations; this.contacts = contacts; this.bpartnerProductExternalReferences = bpartnerProductExternalReferences; } @JsonIgnoreProperties(ignoreUnknown = true) @JsonPOJOBuilder(withPrefix = "") public static class JsonCustomerBuilder { } @JsonIgnore public boolean isActive() { return inactiveBit != 1; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\api\model\JsonCustomer.java
2
请在Spring Boot框架中完成以下Java代码
public ApiResponse<User> getByUserName(String username) { log.info("多个参数用 @ApiImplicitParams"); return ApiResponse.<User>builder().code(200).message("操作成功").data(new User(1, username, "JAVA")).build(); } @GetMapping("/{id}") @ApiOperation(value = "主键查询(DONE)", notes = "备注") @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户编号", dataType = DataType.INT, paramType = ParamType.PATH)}) public ApiResponse<User> get(@PathVariable Integer id) { log.info("单个参数用 @ApiImplicitParam"); return ApiResponse.<User>builder().code(200).message("操作成功").data(new User(id, "u1", "p1")).build(); } @DeleteMapping("/{id}") @ApiOperation(value = "删除用户(DONE)", notes = "备注") @ApiImplicitParam(name = "id", value = "用户编号", dataType = DataType.INT, paramType = ParamType.PATH) public void delete(@PathVariable Integer id) { log.info("单个参数用 ApiImplicitParam"); } @PostMapping @ApiOperation(value = "添加用户(DONE)") public User post(@RequestBody User user) { log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam"); return user; } @PostMapping("/multipar") @ApiOperation(value = "添加用户(DONE)") public List<User> multipar(@RequestBody List<User> user) { log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam"); return user; } @PostMapping("/array") @ApiOperation(value = "添加用户(DONE)") public User[] array(@RequestBody User[] user) { log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user; } @PutMapping("/{id}") @ApiOperation(value = "修改用户(DONE)") public void put(@PathVariable Long id, @RequestBody User user) { log.info("如果你不想写 @ApiImplicitParam 那么 swagger 也会使用默认的参数名作为描述信息 "); } @PostMapping("/{id}/file") @ApiOperation(value = "文件上传(DONE)") public String file(@PathVariable Long id, @RequestParam("file") MultipartFile file) { log.info(file.getContentType()); log.info(file.getName()); log.info(file.getOriginalFilename()); return file.getOriginalFilename(); } }
repos\spring-boot-demo-master\demo-swagger\src\main\java\com\xkcoding\swagger\controller\UserController.java
2
请完成以下Java代码
public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public String getProductAttribute() { return productAttribute; } public void setProductAttribute(String productAttribute) { this.productAttribute = productAttribute; } public Integer getCollectCouont() { return collectCouont; } public void setCollectCouont(Integer collectCouont) { this.collectCouont = collectCouont; } public Integer getReadCount() { return readCount; } public void setReadCount(Integer readCount) { this.readCount = readCount; } public String getPics() { return pics; } public void setPics(String pics) { this.pics = pics; } public String getMemberIcon() { return memberIcon; } public void setMemberIcon(String memberIcon) { this.memberIcon = memberIcon; } public Integer getReplayCount() { return replayCount; } public void setReplayCount(Integer replayCount) { this.replayCount = replayCount;
} public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", memberNickName=").append(memberNickName); sb.append(", productName=").append(productName); sb.append(", star=").append(star); sb.append(", memberIp=").append(memberIp); sb.append(", createTime=").append(createTime); sb.append(", showStatus=").append(showStatus); sb.append(", productAttribute=").append(productAttribute); sb.append(", collectCouont=").append(collectCouont); sb.append(", readCount=").append(readCount); sb.append(", pics=").append(pics); sb.append(", memberIcon=").append(memberIcon); sb.append(", replayCount=").append(replayCount); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsComment.java
1
请完成以下Java代码
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { forecastLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public BigDecimal getQtyTU() { return forecastLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { forecastLine.setQtyEnteredTU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); }
@Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ForecastLineHUPackingAware.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Child child = (Child) o; return Objects.equals(childPK, child.childPK) && Objects.equals(father, child.father) && Objects.equals(mother, child.mother) &&
Objects.equals(name, child.name); } @Override public int hashCode() { return Objects.hash(childPK, father, mother, name); } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } }
repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\entity\Child.java
1
请完成以下Java代码
public class BasicStudent { private String name; private transient String major; @SerializedName("major") private String concentration; public BasicStudent() { } public BasicStudent(String name, String major, String concentration) { this.name = name; this.major = major; this.concentration = concentration; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof BasicStudent)) return false; BasicStudent student = (BasicStudent) o; return Objects.equals(name, student.name) && Objects.equals(major, student.major) && Objects.equals(concentration, student.concentration); }
@Override public int hashCode() { return Objects.hash(name, major, concentration); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getConcentration() { return concentration; } public void setConcentration(String concentration) { this.concentration = concentration; } }
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\multiplefields\BasicStudent.java
1
请在Spring Boot框架中完成以下Java代码
public String getReturnUrl() { return returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", status=").append(status); sb.append(", orderPrice=").append(orderPrice); sb.append(", returnUrl=").append(returnUrl); sb.append(", productName=").append(productName); sb.append("]"); return sb.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\OrderPayResultVo.java
2
请完成以下Java代码
public void onBill_BPartner_ID(final I_C_Invoice_Candidate ic) { if (ic.isManual() && ic.getBill_BPartner_ID() > 0) { final Properties ctx = InterfaceWrapperHelper.getCtx(ic); setPricingSystem(ctx, ic); } } private void setPricingSystem(final Properties ctx, final I_C_Invoice_Candidate ic) { final IBPartnerDAO bPartnerPA = Services.get(IBPartnerDAO.class); final PricingSystemId pricingSysId = bPartnerPA.retrievePricingSystemIdOrNull( BPartnerId.ofRepoId(ic.getBill_BPartner_ID()), SOTrx.ofBoolean(ic.isSOTrx())); ic.setM_PricingSystem_ID(PricingSystemId.toRepoId(pricingSysId)); } @CalloutMethod(columnNames = I_C_Invoice_Candidate.COLUMNNAME_QualityDiscountPercent_Override) public void onQualityDiscountPercentOverride(final I_C_Invoice_Candidate icRecord, final ICalloutField field) { icRecord.setIsInDispute(false); } @CalloutMethod(columnNames = I_C_Invoice_Candidate.COLUMNNAME_GroupCompensationPercentage) public void onGroupCompensationPercentageChanged(final I_C_Invoice_Candidate ic)
{ final InvoiceCandidateGroupRepository groupsRepo = SpringContextHolder.instance.getBean(InvoiceCandidateGroupRepository.class); final Group group = groupsRepo.createPartialGroupFromCompensationLine(ic); group.updateAllCompensationLines(); final InvoiceCandidatesStorage orderLinesStorage = groupsRepo.createNotSaveableSingleOrderLineStorage(ic); groupsRepo.saveGroup(group, orderLinesStorage); } @CalloutMethod(columnNames = I_C_Invoice_Candidate.COLUMNNAME_DateInvoiced ) public void updateFromDateInvoiced(final I_C_Invoice_Candidate invoice, final ICalloutField field) { invoice.setDateAcct(invoice.getDateInvoiced()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\callout\C_Invoice_Candidate.java
1
请在Spring Boot框架中完成以下Java代码
public Binding demo02Binding() { return BindingBuilder.bind(demo02Queue()).to(demo02Exchange()).with(Demo02Message.ROUTING_KEY); } } /** * Fanout Exchange 示例的配置类 */ public static class FanoutExchangeDemoConfiguration { // 创建 Queue A @Bean public Queue demo03QueueA() { return new Queue(Demo03Message.QUEUE_A, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Queue B @Bean public Queue demo03QueueB() { return new Queue(Demo03Message.QUEUE_B, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Fanout Exchange @Bean public FanoutExchange demo03Exchange() { return new FanoutExchange(Demo03Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding A // Exchange:Demo03Message.EXCHANGE // Queue:Demo03Message.QUEUE_A @Bean public Binding demo03BindingA() { return BindingBuilder.bind(demo03QueueA()).to(demo03Exchange()); } // 创建 Binding B // Exchange:Demo03Message.EXCHANGE
// Queue:Demo03Message.QUEUE_B @Bean public Binding demo03BindingB() { return BindingBuilder.bind(demo03QueueB()).to(demo03Exchange()); } } /** * Headers Exchange 示例的配置类 */ public static class HeadersExchangeDemoConfiguration { // 创建 Queue @Bean public Queue demo04Queue() { return new Queue(Demo04Message.QUEUE, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Headers Exchange @Bean public HeadersExchange demo04Exchange() { return new HeadersExchange(Demo04Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding // Exchange:Demo04Message.EXCHANGE // Queue:Demo04Message.QUEUE // Headers: Demo04Message.HEADER_KEY + Demo04Message.HEADER_VALUE @Bean public Binding demo4Binding() { return BindingBuilder.bind(demo04Queue()).to(demo04Exchange()) .where(Demo04Message.HEADER_KEY).matches(Demo04Message.HEADER_VALUE); // 配置 Headers 匹配 } } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请完成以下Java代码
public class CreateIncidentCmd implements Command<Incident> { protected String incidentType; protected String executionId; protected String configuration; protected String message; public CreateIncidentCmd(String incidentType, String executionId, String configuration, String message) { this.incidentType = incidentType; this.executionId = executionId; this.configuration = configuration; this.message = message; } @Override public Incident execute(CommandContext commandContext) { EnsureUtil.ensureNotNull(BadUserRequestException.class, "Execution id cannot be null", "executionId", executionId); EnsureUtil.ensureNotNull(BadUserRequestException.class, "incidentType", incidentType); ExecutionEntity execution = commandContext.getExecutionManager().findExecutionById(executionId); EnsureUtil.ensureNotNull(BadUserRequestException.class, "Cannot find an execution with executionId '" + executionId + "'", "execution", execution); EnsureUtil.ensureNotNull(BadUserRequestException.class, "Execution must be related to an activity", "activity",
execution.getActivity()); for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessInstance(execution); } List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange("incidentType", null, incidentType)); propertyChanges.add(new PropertyChange("configuration", null, configuration)); commandContext.getOperationLogManager().logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_CREATE_INCIDENT, execution.getProcessInstanceId(), execution.getProcessDefinitionId(), null, propertyChanges); return execution.createIncident(incidentType, configuration, message); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CreateIncidentCmd.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsCountGroupedByActivity(this); } public List<ActivityStatistics> executeList( CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsGroupedByActivity(this, page); } public ActivityStatisticsQuery includeFailedJobs() { includeFailedJobs = true; return this; } public ActivityStatisticsQuery includeIncidents() { includeIncidents = true; return this; } public ActivityStatisticsQuery includeIncidentsForType(String incidentType) { this.includeIncidentsForType = incidentType; return this; } public boolean isFailedJobsToInclude() { return includeFailedJobs; } public boolean isIncidentsToInclude() { return includeIncidents || includeIncidentsForType != null; } public String getProcessDefinitionId() { return processDefinitionId; } protected void checkQueryOk() {
super.checkQueryOk(); ensureNotNull("No valid process definition id supplied", "processDefinitionId", processDefinitionId); if (includeIncidents && includeIncidentsForType != null) { throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeIncidentForType() to execute one query."); } } // getter/setter for authorization check public List<PermissionCheck> getProcessInstancePermissionChecks() { return processInstancePermissionChecks; } public void setProcessInstancePermissionChecks(List<PermissionCheck> processInstancePermissionChecks) { this.processInstancePermissionChecks = processInstancePermissionChecks; } public void addProcessInstancePermissionCheck(List<PermissionCheck> permissionChecks) { processInstancePermissionChecks.addAll(permissionChecks); } public List<PermissionCheck> getJobPermissionChecks() { return jobPermissionChecks; } public void setJobPermissionChecks(List<PermissionCheck> jobPermissionChecks) { this.jobPermissionChecks = jobPermissionChecks; } public void addJobPermissionCheck(List<PermissionCheck> permissionChecks) { jobPermissionChecks.addAll(permissionChecks); } public List<PermissionCheck> getIncidentPermissionChecks() { return incidentPermissionChecks; } public void setIncidentPermissionChecks(List<PermissionCheck> incidentPermissionChecks) { this.incidentPermissionChecks = incidentPermissionChecks; } public void addIncidentPermissionCheck(List<PermissionCheck> permissionChecks) { incidentPermissionChecks.addAll(permissionChecks); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ActivityStatisticsQueryImpl.java
1
请完成以下Java代码
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); }
@Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_Value (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Line.java
1
请在Spring Boot框架中完成以下Java代码
protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException { String redirectUri = config.getContextPath(request) + "/callback"; String authorizeUrl = authenticationController.buildAuthorizeUrl(request, response, redirectUri) .withScope("openid email") .build(); response.sendRedirect(authorizeUrl); } @GetMapping(value="/callback") public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException, IdentityVerificationException { Tokens tokens = authenticationController.handle(request, response); DecodedJWT jwt = JWT.decode(tokens.getIdToken()); TestingAuthenticationToken authToken2 = new TestingAuthenticationToken(jwt.getSubject(), jwt.getToken()); authToken2.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(authToken2); response.sendRedirect(config.getContextPath(request) + "/"); }
public String getManagementApiToken() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); JSONObject requestBody = new JSONObject(); requestBody.put("client_id", config.getManagementApiClientId()); requestBody.put("client_secret", config.getManagementApiClientSecret()); requestBody.put("audience", "https://dev-example.auth0.com/api/v2/"); requestBody.put("grant_type", config.getGrantType()); HttpEntity<String> request = new HttpEntity<String>(requestBody.toString(), headers); RestTemplate restTemplate = new RestTemplate(); HashMap<String, String> result = restTemplate.postForObject(AUTH0_TOKEN_URL, request, HashMap.class); return result.get("access_token"); } }
repos\tutorials-master\spring-security-modules\spring-security-auth0\src\main\java\com\baeldung\auth0\controller\AuthController.java
2