RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-260756

invzbl3's questions

Martin Hope
invzbl3
Asked: 2024-06-03 23:15:25 +0000 UTC

自动向H2数据库填充数据时,如何修复错误:“类型“BINARY(255)”和“CHARACTER VARYING(255)”的值不可比较”?

  • 5

在处理Java该项目时,使用以下技术:

<properties>
    <java.version>11</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <!-- Spring Boot Starter Web for building web, including RESTful, applications using Spring MVC -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Boot Starter Data JPA for Spring Data JPA and Hibernate -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <!--<version>2.7.18</version>-->
    </dependency>
    <!-- Spring Boot Starter Test for testing Spring Boot applications -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <!-- H2 Database for in-memory database (for testing purposes) -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.1.214</version> <!--Values of types "BINARY(255)" and "CHARACTER VARYING(255)" are not comparable-->
        <scope>runtime</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>
    <!-- Jackson for JSON processing -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <!-- Spring Boot Maven Plugin for packaging Spring Boot applications -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>

        <!-- Lombok Maven Plugin for delombok process -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>1.18.24</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

使用该文件时application.properties:

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:schema.sql
spring.sql.init.data-locations=classpath:import.sql
server.port=8081
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE
spring.h2.console.path=/h2-console

我收到运行时错误:

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Values of types "BINARY(255)" and "CHARACTER VARYING(255)" are not comparable; SQL statement:
alter table backlog_item_tasks add constraint FKigou96u26bqhftbug6ba1akfa foreign key (tasks_id) references task [90110-214]

...

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Values of types "BINARY(255)" and "CHARACTER VARYING(255)" are not comparable; SQL statement:
alter table backlog_item_tasks add constraint FK1jlaqd1fh1t60yjn2mu179ra1 foreign key (backlog_item_id) references backlog_item [90110-214]

...

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Values of types "BINARY(255)" and "CHARACTER VARYING(255)" are not comparable; SQL statement:
alter table estimation_log_entry add constraint FK4qne2wpk2c906qwlb0qt17k7s foreign key (task_id) references task [90110-214]

我尝试过的:

h2我尝试使用预先准备的SQL脚本(例如 import.sql( ))向数据库填充所需的数据DML скрипт:

INSERT INTO backlog (id, name, description)
VALUES ('uuid-1', 'Backlog 1', 'Description for backlog 1');
INSERT INTO backlog_item (id, status, story, story_points, summary, type, product_id, release_id, sprint_id, backlog_id)
VALUES ('uuid-2', 'Open', 'Story 1', 5, 'Summary for story 1', 'Feature', 'uuid-product', 'uuid-release', 'uuid-sprint',
        'uuid-1');
INSERT INTO task (id, name, description, hours_remaining, volunteer, backlog_item_id)
VALUES ('uuid-3', 'Task 1', 'Description for task 1', 10, 'Volunteer 1', 'uuid-2');

相应地,schema.sql( DDL скрипт):

CREATE TABLE backlog
(
    id          VARCHAR(255) PRIMARY KEY,
    name        VARCHAR(255) NOT NULL,
    description TEXT
);

CREATE TABLE backlog_item
(
    id           VARCHAR(255) PRIMARY KEY,
    status       VARCHAR(255),
    story        TEXT,
    story_points INT,
    summary      TEXT,
    type         VARCHAR(255),
    product_id   VARCHAR(255),
    release_id   VARCHAR(255),
    sprint_id    VARCHAR(255),
    backlog_id   VARCHAR(255),
    FOREIGN KEY (backlog_id) REFERENCES backlog (id)
);

CREATE TABLE task
(
    id              VARCHAR(255) PRIMARY KEY,
    name            VARCHAR(255) NOT NULL,
    description     TEXT,
    hours_remaining INT,
    volunteer       VARCHAR(255),
    backlog_item_id VARCHAR(255),
    FOREIGN KEY (backlog_item_id) REFERENCES backlog_item (id)
);

配置application.properties如下:

1. Simple In-Memory Database
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE

上述模式仅在使用的浏览器中显示http://localhost:8081/h2-console/。


和:

3. Persistent Database in File
spring.datasource.url=jdbc:h2:file:./data/mydb`

ошибки выполнения按以下格式播放中间件:

Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is org.h2.jdbc.JdbcSQLNonTransientConnectionException: Unsupported database file version or invalid file header in file "E:/IdeaProject/PDP1/data/mydb.mv.db" [90048-214]

...

Caused by: org.h2.jdbc.JdbcSQLNonTransientConnectionException: Unsupported database file version or invalid file header in file "E:/IdeaProject/PDP1/data/mydb.mv.db"

...

Caused by: org.h2.mvstore.MVStoreException: The write format 3 is larger than the supported format 2 [2.1.214/5]

更新:

application.properties具有以下jdbc:h2:file选项:

spring.datasource.url=jdbc:h2:file:./data/mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE

由于mydb.mv.db文件被锁定,也无法正常工作。

预期的:

预计在IDEA (Intellij IDEA)中收到以下格式的内容H2 бд:

在此输入图像描述

java
  • 1 个回答
  • 18 Views
Martin Hope
invzbl3
Asked: 2024-05-14 23:26:14 +0000 UTC

如果运行 scp -r 命令时文件不在目标文件夹中,如何正确地将文件从远程服务器传输到本地?

  • 5

我正在努力从远程服务器传输文件:

[login@alma ~]$ pwd

/home/login

到本地:

E:\University\Parallel Computing\assignment2。

位于本地目录:

E:\University\Parallel Computing

通过执行cmd以下格式的命令:

invzbl3@WIN... /e/University/Parallel Computing
$ scp -r assignment2 login@host:/home/login

我希望在将密码输入本地目录后从远程服务器接收文件。

结果,我的文件夹仍然是空的。

之后,我又尝试了三个命令,例如:

  1. 例如:
invzbl3@WIN... /e/University/Parallel Computing
$ scp -r login@host:/home/login/assignment2/ assignment2/

sub- 文件夹已创建,但文件仍然不存在。

  1. scp -r login@host:/home/login/assignment2/* assignment2

sub- 文件夹已创建E:\University\Parallel Computing\assignment2\assignment2,但没有文件。

  1. scp -r login@host:/home/login/assignment2/* assignment2/

和前两个一样。文件夹已创建,但文件未从服务器上传。

对此,我有以下疑问:

在将文件从远程服务器上传到本地服务器的过程中我可能会缺少什么?

预先感谢您对我的问题提供任何有用的建议。

如果我有决定,我会把它们写下来。

如果需要任何其他信息,我愿意听取合理的建设性反馈(如果有)。

预先感谢您对我的问题的帮助。

为了确定:

UPD #1:

在此输入图像描述

我正在上传.zip文件。

UPD #2:

cmd我刚刚澄清了我的误解,我认为我可以使用命令从平台上传文件,就像我使用via -ing.zip上的选项一样,但是,事实证明,我不能这样做,因为在远程server - ,.我没有任何文件,我需要从提供给我使用的教育平台手动下载-文件,将其上传到服务器,然后使用.Githubpullalma.zipAlmaVisual Studio Code

UPD #3:

我单独检查了以下格式的命令:

scp -r assignment2/ login@host:/home/login

适应login自己host,并考虑以下建议,将文件夹名称从“ Parallel Computing”更改为“ ParallelComputing”,删除多余的空格。

结果是一样的:

该文件夹是空的。

在此输入图像描述

cmd
  • 1 个回答
  • 46 Views
Martin Hope
invzbl3
Asked: 2022-12-26 08:39:53 +0000 UTC

如何在渲染时处理 JSP 中的 CSS 样式以修复对齐?

  • 5

测试文件时JSP,由于对齐,我在屏幕上显示有问题:

在此处输入图像描述

这是我的示例文件JSP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <%@include file="/includes/head.jsp"%>
    <style type="text/css">
        body {
            background-color: rgba(26, 35, 115, 0.47);
            color: #fff;
        }
    </style>
</head>
<body class="text-center vsc-initialized">
<%@include file="/includes/header.jsp"%>
<div class="cover-container d-flex h-100 p-3 mx-auto flex-column">
    <main role="main" class="inner cover">
        <h1 class="cover-heading">Welcome</h1>
        <h1 class="cover-heading">to</h1>
        <h1 class="cover-heading">Project Management</h1>
        <h1 class="cover-heading">System</h1>
    </main></div>
<%@include file="/includes/footer.jsp"%>
</body>
</html>

我需要得到这样的结果:

在此处输入图像描述

这样文本居中对齐,顶部没有配置标题。

CSS如果这是一个问题或JSP一般情况,任何人都可以告诉我吗?我是否需要修复某些JSP内容以获得不同的显示结果?

如果需要更多信息,我愿意更新这个问题。

我感谢这里的任何建议/想法。

css
  • 1 个回答
  • 18 Views
Martin Hope
invzbl3
Asked: 2022-12-24 10:07:28 +0000 UTC

如何解决问题:如果在脚本中正确指定了某些字段,则“无法解析列”?

  • 5

我有以下脚本:

/*==============================================================*/
/* Table: Employees                                             */
/*==============================================================*/
insert into Employees (firstName, lastName, phoneNumber, email, salary, role, password, username)
values ('Christiano', 'Ronaldo', '+421905123456', 'test@gmail.com', 50000.00, 'TEAM_LEADER', 'testPassword', 'C7'),
       ('John', 'Smith', '+421905123480', 'test2@gmail.com', 40000.00, 'PM', 'testPassword2', 'Jo'),
       ('Michael', 'Jackson', '+421905123400', 'test3@gmail.com', 30000.00, 'DEVELOPER', 'testPassword3', 'Mike'),
       ('Leonardo', 'DiCaprio', '+421905123450', 'test4@gmail.com', 20000.00, 'SCIENTIST', 'testPassword4', 'Leo'),
       ('Brad', 'Pitt', '+421905123455', 'test5@gmail.com', 10000.00, 'ENGINEER', 'testPassword5', 'Brad');

有一个实体:

import com.test.application.data.enums.Role;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.List;

/**
 * @author invzbl3 on 12/16/2022
 * @project RestApiApplication
 */
@Data
@ToString
@EqualsAndHashCode
@Entity(name = "employee_entity")
@Table(name = "employees")
public class Employee implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String firstName;
    private String lastName;
    private String phoneNumber;
    private String email;
    private double salary;
    @Enumerated(EnumType.STRING)
    private Role role;
    private String password;
    private String username;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return List.of(() -> "USER");
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

我检查了一个类似的问题,但对我来说它看起来不一样,因为我在那里正确检查了一些字段。

考虑到这一点,我有一个问题:

我该如何解决这个问题?

如果您需要随时提供任何其他信息。

在此先感谢您对此事的任何想法。

java
  • 1 个回答
  • 36 Views
Martin Hope
invzbl3
Asked: 2022-12-23 11:38:54 +0000 UTC

如何在服务实现中重构 getAllProjects() 方法?

  • 6

我有以下服务,在一个项目中有一个实现:

@Service
public class ProjectServiceImpl implements ProjectService {
    
    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private ProjectAdaptor projectAdaptor;

    @Override
    public List<Project> getAll() {
        return projectRepository.findAll();
    }

    @Override
    public List<Project> getAllProjects(Long companyId) {
        return projectRepository.getAll().stream()
                .filter(project -> project.getId() == companyId).findAny().orElse(null);
    }

    @Override
    public Project save(Project project) {
        return projectRepository.save(project);
    }

    @Override
    public List<ProjectDTO> findAllProducts() {
        List<Project> project = projectRepository.findAll();
        return projectAdaptor.databaseModelToUiDtoList(project);
    }
}

其中有一个方法 getAll():

@Override
public List<Project> getAll() { 
 return projectRepository.findAll();    
} 

并相应地getAllProjects():

@Override 
public List<Project> getAllProjects(Long companyId) { 
  return projectRepository
   .getAll() 
   .stream() 
   .filter(project -> project.getId() == companyId) 
   .findAny() 
   .orElse(null); 
}

在这方面,问题是如何重构上述方法,它重现了与类型相关的编译错误Object:

无法解析中的方法getId。Object

在此处输入图像描述

我的实体Project具有以下结构:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "project_entity")
@Table(name = "projects")
public class Project {

    public Project(ProjectDTO projectDTO) {
        this.name = projectDTO.getName();
        this.abbreviation = projectDTO.getAbbreviation();
        this.customer = projectDTO.getCustomer();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "project_id")
    private Integer id;

    private String name;

    private String abbreviation;

    private String customer;
}

我是否需要Lombok在实体上添加额外的注释来解决这个问题,或者有没有办法以更正确的方式将两种方法合二为一?

我将非常感谢你在这件事上的帮助。

java
  • 2 个回答
  • 30 Views
Martin Hope
invzbl3
Asked: 2022-12-23 01:05:09 +0000 UTC

如何在不使用 Liquibase 的情况下摆脱与 Liquibase 相关的“找不到变更日志”错误?

  • 5

我正在使用具有以下依赖项的项目:POM

<dependencies>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
        <version>2.3.2.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.liquibase/liquibase-core -->
    <dependency>
        <groupId>org.liquibase</groupId>
        <artifactId>liquibase-core</artifactId>
        <version>4.16.1</version>
    </dependency>

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.4.4</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jooq</artifactId>
        <version>2.7.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>jakarta.servlet.jsp.jstl</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.jooq/jooq -->
    <dependency>
        <groupId>org.jooq</groupId>
        <artifactId>jooq</artifactId>
        <version>3.15.0</version>
    </dependency>
</dependencies>

在运行项目的当前版本时,出现以下错误:

Liquibase failed to start because no changelog could be found at 'classpath:/db/changelog/db.changelog-master.yaml'.

在研究了各种英文答案之后Stackoverflow:

  1. https://stackoverflow.com/a/63227085/8370915
  2. https://stackoverflow.com/q/68883660/8370915
  3. https://stackoverflow.com/q/46810712/8370915

得出的结论是,为了解决它,您需要添加以下类型的其他文件db.changelog-master.yaml:

liquibase.exception.ChangeLogParseException: classpath:/db/changelog/db.changelog-master.yaml does not exist

在这方面,我有一个问题,我可以在不使用原则上Liquibase作为工具的情况下消除这个错误吗?

如果是,我该怎么做?

之所以这样问是因为在删除依赖项的情况下liquibase-core:

<dependency>
  <groupId>org.liquibase</groupId>
  <artifactId>liquibase-core</artifactId>
  <version>4.16.1</version>
</dependency>

我收到另一个错误:

Caused by: java.lang.ClassNotFoundException: liquibase.exception.ChangeLogParseException

这只能通过添加依赖 Liquibase项来解决。

java
  • 1 个回答
  • 27 Views
Martin Hope
invzbl3
Asked: 2022-12-22 06:56:27 +0000 UTC

如何重构控制器的 add() 方法?

  • 6

ProjectController我使用下面编写的类的逻辑:

@RestController
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    ProjectRepository projectRepository;

    @Autowired
    ProjectService projectService;

    ProjectAdaptor projectAdaptor = new ProjectAdaptor();

    /**
     * Logger declaration for knowing the flow of execution for debugging
     */
    private static final Logger logger = LoggerFactory.getLogger(ProjectController.class);

    @GetMapping("/projects")
    @Operation(summary = "Get list of all projects")
    public ResponseEntity<List<ProjectDTO>> findAllProjects() {
        logger.info("findAllProjects() is calling...");

        List<ProjectDTO> projectList = projectService.findAllProducts();
        if (projectList.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(projectList, HttpStatus.OK);
    }

    @GetMapping(value = "/{companyId}")
    @Operation(summary = "Get list of projects from database based on companyId")
    public @ResponseBody List<ProjectDTO> findAllProjects(@PathVariable("companyId") String companyId,
                                     HttpServletRequest req) throws ErrorHandling {
        logger.info("findAllProjects() is calling : ");
        Long longCompanyId = Long.parseLong(companyId);
        List<Project> projectList = projectService.getAllProjects(longCompanyId);
        logger.info("findAllProjects ProjectList : " + projectList);

        if (projectList != null && !projectList.isEmpty()) {
            return projectAdaptor.databaseModelToUiDtoList(projectList);
        } else {
            throw new ErrorHandling("Project data not present.");
        }
    }

    @PostMapping
    @Operation(summary = "Add new project")
    public ResponseEntity<ProjectDTO> addProject(@RequestBody Project project) {
        logger.info("addProject() is calling...");

        if (project != null) {
            ProjectDTO projectDTO = projectAdaptor.databaseModelToUiDto(project);
            Project entity = projectRepository.save(projectDTO);
            return new ResponseEntity<>(entity, HttpStatus.OK);
        }
        return new ResponseEntity<>(new ProjectDTO("","",""), HttpStatus.BAD_REQUEST);
    }

    @PutMapping
    @Operation(summary = "Updating project")
    public ResponseEntity<ProjectDTO> updateById(@RequestBody Project project) {
        logger.info("updateById() is calling...");

        if (project != null) {
            projectRepository.save(project);
            return new ResponseEntity<>("Updated successfully.", HttpStatus.OK);
        }
        return new ResponseEntity<>(new ProjectDTO("","",""), HttpStatus.BAD_REQUEST);
    }

    @DeleteMapping
    @Operation(summary = "Deleting project")
    public ResponseEntity<ProjectDTO> deleteById(@PathVariable("id") Long id) {
        logger.info("deleteById() is calling...");

        Optional<Project> project = projectRepository.findById(id);
        if (project.isPresent()) {
            projectRepository.deleteById(id);
            return new ResponseEntity<>("Successfully deleted.", HttpStatus.OK);
        }
        return new ResponseEntity<>(new ProjectDTO("","",""), HttpStatus.BAD_REQUEST);
    }
}

如何重构 add 方法时出现问题:

@PostMapping
@Operation(summary = "Add new project")
public ResponseEntity<ProjectDTO> addProject(@RequestBody Project project) {
    logger.info("addProject() is calling...");

    if (project != null) {
        ProjectDTO projectDTO = projectAdaptor.databaseModelToUiDto(project);
        Project entity = projectRepository.save(projectDTO);
        return new ResponseEntity<>(entity, HttpStatus.OK);
    }
    return new ResponseEntity<>(new ProjectDTO("","",""), HttpStatus.BAD_REQUEST);
}

问题是在保存Entity到DTO. 如果是这样,将它放在输入参数中会不会有问题,Entity还是为此重写逻辑更好?

在此处输入图像描述

我将非常感谢你在这件事上的帮助。

如有必要,我也准备提供任何有助于解决此问题的其他信息。

java
  • 1 个回答
  • 32 Views
Martin Hope
invzbl3
Asked: 2020-03-22 09:44:29 +0000 UTC

Spring Security:为 id “null”映射的 PasswordEncoder

  • 1

我正在使用 Spring 2.2.5.RELEASE

使用用户名和密码发送 GET 请求时,我收到如下错误:

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
    at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:250) ~[spring-security-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:198) ~[spring-security-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration$LazyPasswordEncoder.matches(AuthenticationConfiguration.java:312) ~[spring-security-config-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:90) ~[spring-security-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:175) ~[spring-security-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:195) ~[spring-security-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]

配置是这样写的:

@Configuration
public class SpringSecurityConfiguration_InMemory extends WebSecurityConfigurerAdapter {
    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().
                withUser("user").password("password")
                .roles("USER");
        auth.
                inMemoryAuthentication().withUser("admin").
                password("password")
                .roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic().and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/user/")
                .hasRole("USER")
                .antMatchers(HttpMethod.POST, "/api/user/")
                .hasRole("USER")
                .antMatchers(HttpMethod.PUT, "/api/user/**")
                .hasRole("USER")
                .antMatchers(HttpMethod.DELETE, "/api/user/**")
                .hasRole("ADMIN")
                .and()
                .csrf()
                .disable();
    }
}

如何纠正错误?

java
  • 1 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-10-04 04:42:56 +0000 UTC

主进程中发生 JavaScript 错误:指南针

  • 0

当我运行 mongoDB 客户端应用程序 Compass 1.13.1 时,出现错误:在此处输入图像描述

如何解决这个问题呢?

mongodb
  • 1 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-10-04 04:14:17 +0000 UTC

如何在 mongoDB 中使用 Java Driver 3.4+ 删除 Prematurely达到流异常结束?(插入时)

  • 0

我将文档插入到capped collection中,我这样写:

           // получить документ с необходимыми полями
            Document found = collection.find().first();
            String getTitle = (String) found.get("title");
            String getUrl = (String) found.get("url");
            String getImg = (String) found.get("img");
            String getPrice = (String) found.get("price");

            // документ, который мне нужно получить в новом виде
            Document doc = collection.find(new Document("title", getTitle)
                    .append("url", getUrl)
                    .append("img", getImg)
                    .append("price", getPrice)
                    .append("sent", true)).first();

            // если документ не существует, я вставляю как новый
            if (doc == null) {
             collection.insertOne(new Document("title", getTitle)
                   .append("url", getUrl)
                   .append("img", getImg)
                   .append("price", getPrice)
                   .append("sent", true));
        }

这称为覆盖文档。我正在插入带有额外字段的新文档,而不是没有一个字段的旧文档。也就是说,一个文档在集合的开头被删除,一个新的文档出现在集合的末尾。

我要替换的文档如下所示: 在此处输入图像描述

相反,我以这种形式插入一个新的: 在此处输入图像描述

插入新文档而不是旧文档的过程正常进行,直到抛出异常:

com.mongodb.MongoSocketReadException: Prematurely reached end of stream
    at com.mongodb.connection.SocketStream.read(SocketStream.java:88)
    at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:491)
    at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:221)
    at com.mongodb.connection.CommandHelper.receiveReply(CommandHelper.java:134)
    at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:121)
    at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
    at com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83)
    at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
    at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46)
    at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:381)
    at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:96)
    at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:82)
    at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:72)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86)
    at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:237)
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:212)
    at com.mongodb.operation.FindOperation.execute(FindOperation.java:482)
    at com.mongodb.operation.FindOperation.execute(FindOperation.java:79)
    at com.mongodb.Mongo.execute(Mongo.java:772)
    at com.mongodb.Mongo$2.execute(Mongo.java:759)
    at com.mongodb.FindIterableImpl$FindOperationIterable.first(FindIterableImpl.java:207)
    at com.mongodb.FindIterableImpl.first(FindIterableImpl.java:148)
    at project.Bot.onUpdateReceived(Bot.java:347)

我猜错误就在这条线上:

Document found = collection.find().first();

我尝试使用此代码段解决问题(我有一个免费的 Tier M0 集群):

 List<ServerAddress> List = new ArrayList<>();
            List.add(new ServerAddress("cluster0-shard-00-00-ox90k.mongodb.net", 27017));
            List.add(new ServerAddress("cluster0-shard-00-01-ox90k.mongodb.net", 27017));
            List.add(new ServerAddress("cluster0-shard-00-02-ox90k.mongodb.net", 27017));

            char[] password = "mypassword".toCharArray();
            List<MongoCredential> cred = new ArrayList<>();
            cred.add(MongoCredential.createCredential("user", "db_feed", password));
            MongoClientOptions optionsBuilder = MongoClientOptions.builder()
                    .readPreference(ReadPreference.primaryPreferred())
                    .requiredReplicaSetName("Cluster0-shard-0")
                    .maxConnectionIdleTime(60000)
                    .build();

            MongoClient mongoClient = new MongoClient(List, cred, optionsBuilder);

但在这种情况下,我得到另一个例外:

 com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primaryPreferred}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=cluster0-shard-00-00-ox90k.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadException: Prematurely reached end of stream}}, {address=cluster0-shard-00-01-ox90k.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadException: Prematurely reached end of stream}}, {address=cluster0-shard-00-02-ox90k.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadException: Prematurely reached end of stream}}]
        at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:369)
        at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
        at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
        at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
        at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)
        at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:210)
        at com.mongodb.operation.FindOperation.execute(FindOperation.java:482)
        at com.mongodb.operation.FindOperation.execute(FindOperation.java:79)
        at com.mongodb.Mongo.execute(Mongo.java:772)
        at com.mongodb.Mongo$2.execute(Mongo.java:759)
        at com.mongodb.FindIterableImpl$FindOperationIterable.first(FindIterableImpl.java:207)
        at com.mongodb.FindIterableImpl.first(FindIterableImpl.java:148)
        at project.Bot.onUpdateReceived(Bot.java:347)

从这个异常发生的时间来看,这似乎是由于连接的行的格式,因为我在连接驱动程序版本 3.6 和更高版本时已经出现了这样的错误。(一切都依赖于+srv前缀,这不允许使用 3.6 及更高版本的新版本的驱动程序正常工作)。我注意到在其他语言中,比如 Python,他们通过+srv连接一个单独的. 我不知道如何在 Java 中实现它,因为 看起来像拐杖。

顺便说一句,当我连接 Java 3.4 驱动程序版本com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting时,它会自行消失:

MongoClientURI connectionString = new MongoClientURI("mongodb://admin1:mypassword@cluster0-shard-00-00-ox90k.mongodb.net:27017,cluster0-shard-00-01-ox90k.mongodb.net:27017,cluster0-shard-00-02-ox90k.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true");
MongoClient mongoClient = new MongoClient(connectionString);

我很想听听关于我的问题的意见,在此先感谢。


一个类似的问题已经在英文堆栈上被问过。

java
  • 1 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-08-05 09:57:36 +0000 UTC

java.rmi.ConnectException:连接拒绝托管

  • 0

使用 RMI 机制启动客户端-服务器应用程序时,会引发异常java.rmi.ConnectException: Connection refused to host。

该程序本身使用四个源文件:

AddServerIntf.java

import java.rmi.Remote;
import java.rmi.RemoteException;

interface AddServerIntf extends Remote {
    double add(double d1, double d2) throws RemoteException;
}

AddServerImpl.java

import java.rmi.*;
import java.rmi.server.*;

public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf {

    public AddServerImpl() throws RemoteException {
    }

    public double add(double d1, double d2) throws RemoteException {
        return d1 + d2;
    }
}

AddServer.java

import java.rmi.*;

public class AddServer {
    public static void main(String args[]) {
        try {
            AddServerImpl addServerImpl = new AddServerImpl();
            Naming.rebind("AddServer", addServerImpl);
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

添加客户端.java

import java.rmi.*;

public class AddClient {
    public static void main(String args[]) {
        try {
            String addServerURL = "rmi://" + args[0] + "/AddServer";
            AddServerIntf addServerIntf = (AddServerIntf) Naming.lookup(addServerURL);
            System.out.println("The first number is: " + args[1]);
            double d1 = Double.valueOf(args[1]).doubleValue();
            System.out.println("The second number is: " + args[2]);

            double d2 = Double.valueOf(args[2]).doubleValue();
            System.out.println("The sum is: " + addServerIntf.add(d1, d2));
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

如何解决这个问题呢?

java
  • 1 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-08-05 09:37:35 +0000 UTC

java.time.format.DateTimeParseException:无法在索引 0 处解析文本

  • 2

运行使用类实现日期和时间解析的程序时LocaleDateTime:

// Parse a date and time. 
import java.time.*; 
import java.time.format.*; 

class DateTimeDemo4 { 
  public static void main(String args[]) { 

    // Obtain a LocalDateTime object by parsing a date and time string. 
    LocalDateTime curDateTime = 
         LocalDateTime.parse("June 21, 2014 12:01 AM", 
                  DateTimeFormatter.ofPattern("MMMM d',' yyyy hh':'mm a")); 

     // Now, display the parsed date and time. 
    System.out.println(curDateTime.format( 
               DateTimeFormatter.ofPattern("MMMM d',' yyyy h':'mm a"))); 
  } 
}

不断抛出异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'June 21, 2014 12:01 AM' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at DateTimeDemo4.DateTimeDemo4.main(DateTimeDemo4.java:12)

怎么修?

java
  • 1 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-07-23 05:55:53 +0000 UTC

国际化 Java 应用程序时出错

  • 3

我正在研究一个使用类ResourceBundle和ListResourceBundle.

该示例演示了如何使用名为 SampleRB 的资源包。

编译后我不断收到错误:

Английская версия программы: 
Exception in thread "main" java.lang.NullPointerException
    at java.util.ListResourceBundle.loadLookup(ListResourceBundle.java:202)
    at java.util.ListResourceBundle.handleGetObject(ListResourceBundle.java:130)
    at java.util.ResourceBundle.getObject(ResourceBundle.java:441)
    at java.util.ResourceBundle.getString(ResourceBundle.java:407)
    at LRBDemo.LRBDemo.main(LRBDemo.java:12)

该程序本身由LRBDemo类和主启动方法组成:

public class LRBDemo {
    public static void main(String[] args) {
        // загрузить комплект ресурсов по умолчанию
        ResourceBundle rd = ResourceBundle.getBundle("LRBDemo.SampleRB");

        System.out.println("Английская версия программы: ");
        System.out.println("Строка по ключу Title: " + rd.getString("title"));
        System.out.println("Строка по ключу StopText: " + rd.getString("StopText"));
        System.out.println("Строка по ключу StartText: " + rd.getString("StartText"));

        // загрузить комплект ресурсов для поддержки немецкого языка
        rd = ResourceBundle.getBundle("LRBDemo.SampleRBde", Locale.GERMAN);

        System.out.println("\nНемецкая версия программы: ");
        System.out.println("Строка для ключа Title: " + rd.getString("title"));
        System.out.println("Строка по ключу StopText: " + rd.getString("StopText"));
        System.out.println("Строка по ключу StartText: " + rd.getString("StartText"));
    }
}

具有英语语言支持的SampleRB类:

public class SampleRB extends ListResourceBundle {
    protected Object[][] getContents() {
        Object[][]  resources = new Object[3][2];

        resources[0][0] = "title";
        resources[0][1] = "MyProgram";

        resources[1][0] = "StopText";
        resources[1][1] = "Stop";

        resources[1][0] = "StartText";
        resources[2][1] = "Start";

        return resources;
    }
}

以及具有德语支持的SampleRBde类:

public class SampleRBde extends ListResourceBundle {
    protected Object[][] getContents() {
        Object[][] resources = new Object[3][2];

        resources[0][0] = "title";
        resources[0][1] = "Mein Programm";

        resources[1][0] = "StopText";
        resources[1][1] = "Anschlag";

        resources[2][0] = "StartText";
        resources[2][1] = "Anfang";

        return resources;
    }
}

代码本身不会显示错误,但是如果我在LRBDemoResourceBundle rd = ResourceBundle.getBundle("LRBDemo.SampleRB")类中以这种方式ResourceBundle rd = ResourceBundle.getBundle("SampleRB")而不是字符串而不是rd = ResourceBundle.getBundle("LRBDemo.SampleRBde", Locale.GERMAN);这样编写rd = ResourceBundle.getBundle("SampleRBde", Locale.GERMAN);,也就是说,我删除了类包,那么我得到了输出:

Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name SampleRB, locale ru_RU
    at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1564)
    at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1387)
    at java.util.ResourceBundle.getBundle(ResourceBundle.java:773)
    at LRBDemo.LRBDemo.main(LRBDemo.java:9)

我的项目结构:

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

对于如何消除错误并最终显示结果的建议,我将不胜感激。

java
  • 1 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-06-20 06:25:36 +0000 UTC

如何连接到 Atlas M0(免费层)MongoDB 集群?

  • 0

我正在尝试使用 Java 驱动程序MongoDB version 3.6连接到 Atlas 集群。

我写了这段代码:

  MongoClientURI uri = new MongoClientURI("mongodb+srv://admin1:mypassword@cluster0-ox90k.mongodb.net/test?retryWrites=true");
  MongoClient mongoClient = new MongoClient(uri);

我收到有关修复的错误mongodb+srv:

java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with 'mongodb://'
    at com.mongodb.ConnectionString.<init>(ConnectionString.java:203)
    at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:176)
    at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:158)
    at project.Bot.check(Bot.java:30)
    at project.Bot.onUpdateReceived(Bot.java:104)
    at java.util.ArrayList.forEach(ArrayList.java:1249)
    at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:309)

虽然 POM 文件中列出了驱动程序版本:

<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.6.0</version>
        </dependency> 

然后我这样写,使用 MongoDB 3.6 版(同时删除+srv前缀):

 MongoClientURI uri = new MongoClientURI("mongodb://admin1:mypassword@cluster0-ox90k.mongodb.net/test?retryWrites=true");
 MongoClient mongoClient = new MongoClient(uri);

结果,IDE 报告如下错误: 在此处输入图像描述

com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=cluster0.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: cluster0.mongodb.net}, caused by {java.net.UnknownHostException: cluster0.mongodb.net}}]
    at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:369)
    at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
    at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:201)
    at com.mongodb.operation.CountOperation.execute(CountOperation.java:206)
    at com.mongodb.operation.CountOperation.execute(CountOperation.java:53)
    at com.mongodb.Mongo.execute(Mongo.java:772)
    at com.mongodb.Mongo$2.execute(Mongo.java:759)
    at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:185)
    at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:170)
    at project.Bot.check(Bot.java:36)
    at project.Bot.onUpdateReceived(Bot.java:103)
    at java.util.ArrayList.forEach(ArrayList.java:1249)
    at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:309)

当我开始这个过程时,mongo我的数据库被添加到 address mongodb://127.0.0.1:27017,虽然我想将数据库添加到集群本身。我在文档中读到您需要运行该命令mongos,但我无法完全理解如何正确编写它。

集群当然有一个带密码的管理员用户。我可以通过 Compass 客户端和 shell shell 连接到集群本身,但没有添加基础本身(我在程序中添加的)。mongod推出。从描述来看,这里也出现了类似的问题。

请告诉我在编写代码时需要修复什么。(如有需要,我可以提供程序的完整代码。)

java
  • 2 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-06-10 05:21:33 +0000 UTC

MongoDB 中的示例问题

  • 0

集合中文档的结构如下:

{
        "_id" : ObjectId("569190cd24de1e0ce2dfcd62"),
        "title" : "Star Trek II: The Wrath of Khan",
        "year" : 1982,
        "rated" : "PG",
        "released" : ISODate("1982-06-04T04:00:00Z"),
        "runtime" : 113,
        "countries" : [
                "USA"
        ],
        "awards" : {
                "wins" : 2,
                "nominations" : 9,
                "text" : "2 wins & 9 nominations."
        }
}

我正在尝试使用投影并添加几个附加参数来获取特定字段的内容。我想使用这些键title, year,rated和awards指定的值。(_id 已删除)

我 db.movieDetails.find( {}, {title: 1, year: 2013, rated: "PG-13", _id: 0, "awards.wins": 1 }).pretty()以获取具有值的字段的方式对其进行了规定,但在控制台中它的显示不一致:

{
        "title" : "Once Upon a Time in the West",
        "year" : 1968,
        "rated" : "PG-13",
        "awards" : {
                "wins" : 4
        }
}
{
        "title" : "A Million Ways to Die in the West",
        "year" : 2014,
        "rated" : "R",
        "awards" : {
                "wins" : 0
        }
}
{
        "title" : "Wild Wild West",
        "year" : 1999,
        "rated" : "PG-13",
        "awards" : {
                "wins" : 10
        }
}

我想要这个:

 {
            "title" : "Once Upon a Time in the West",
            "year" : 2013,
            "rated" : "PG-13",
            "awards" : {
                    "wins" : 0
            }
    }
    {
            "title" : "A Million Ways to Die in the West",
            "year" : 2013,
            "rated" : "PG-13",
            "awards" : {
                    "wins" : 0
            }
    }
    {
            "title" : "Wild Wild West",
            "year" : 2013,
            "rated" : "PG-13",
            "awards" : {
                    "wins" : 0
            }
    }

请告诉我,请求中需要更正哪些内容才能根据我的要求输出?

mongodb
  • 1 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-04-02 01:05:09 +0000 UTC

为什么不处理 IOException?

  • 0

给出了一个示例程序,其中声明了 IOException 但未处理。throws使用关键字而不使用的原因是什么try/catch?

阅读此处和此处的例外情况。我知道有已处理和未处理的异常,但在这种情况下, IOException 只是一个检查异常。那么为什么不需要处理。

在一个例子中“在方法签名中描述”就足够了吗?

public class TinyEdit {
    public static void main(String[] args) throws IOException{
        // создать поток ввода типа BufferedReader,
        // используя стандартный поток ввода System.in
        BufferedReader br = new BufferedReader(new
                InputStreamReader(System.in));
        String str[] = new String[100];
        System.out.println("Введите строки текста.");
        System.out.println("Введите 'стоп' для завершения.");
        for(int i=0; i<100; i++) {
            str[i] = br.readLine();
            if(str[i].equals("стоп")) break;
        }
        System.out.println("\n Содержимое вашего файла:");
        // вывести текстовые строки
        for(int i=0; i<100; i++) {
            if(str[i].equals("стоп")) break;
            System.out.println(str[i]);
        }
    }
}
java
  • 2 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-03-19 00:58:49 +0000 UTC

如何在 C/C++ 中实现按 Ctrl 和 Shift 键

  • 3

任务是这样的:

编写一个程序,显示有关鼠标坐标、控制键状态(ALT、CTRL、SHIFT)、扫描码和给定控制台位置按下键的 ASCII 码的信息。要显示结果,请使用SetConsoleCursorPosition,()、wsprintf()、WriteConsole() 函数。

我重新阅读了文档,查看了示例(最后一个太混乱了)。由于键是象征性的,您将不得不使用另一个函数来编写它们TranslateMessage。

关于击键执行的问题,最好的方法是什么。(突出显示问题所在的代码块)。

目前我有这个代码:

        #include "stdafx.h"
        #include <cstring>
        #include <iostream>
        #include <stdio.h>
        #include <conio.h>
        #include <windows.h>
        #include <winuser.h>


        #define  STR_SIZE 256
        #define BUFSIZE 65535
        #define SHIFTED 0x8000


        int main() {

            setlocale(LC_ALL, "rus");
            HANDLE hIn, hOut;
            DWORD size = STR_SIZE;
            char result[STR_SIZE];

            FreeConsole();
            AllocConsole();
            SetConsoleOutputCP(1251);

            hIn = GetStdHandle(STD_INPUT_HANDLE);
            hOut = GetStdHandle(STD_OUTPUT_HANDLE);

            GetDC(NULL); // дескриптор стола
            POINT p; // структура для координат
            COORD cord; // структура COORD, которая указывает позицию курсора

            cord.X = 0; // координата X структуры COORD
            cord.Y = 0; // координата Y структуры COORD

   //------------------------------------------------------------------


            HWND hwndMain;
            HACCEL haccl;
            UINT uMsg;
            UINT wParam;
            LONG lParam;
            HWND hwnd;
            MSG msg;

                    switch (wParam)
                    {
                    case 0x10:

                             /*SHIFT key.*/
                        printf("SHIFT pressed", wParam);

                            break;

                    case 0x11:

                             /*CTRL key.*/
                        printf("CTRL pressed", wParam);

                            break;
                    case 0x12:

                             /*ALT key. */
                        printf("ALT pressed", wParam);

                            break;
                    default:

                        printf("OTHER pressed", wParam);
                             /* Обработка воспроизводимых символов. */

                            break;
                    }

                    while (GetMessage(&msg, (HWND)NULL, 0, 0))
                    {
                        if (TranslateAccelerator(hwndMain, haccl, &msg) == 0)
                        {
                            TranslateMessage(&msg);
                            DispatchMessage(&msg);
                        }
                    }   
    //-----------------------------------------------------------------------------

            while (1) {
                wsprintf(result, "Позиция курсора: ");
                WriteConsole(hOut, result, strlen(result), nullptr, nullptr);
                GetCursorPos(&p);
                wsprintf(result, "x = %4ld, y = %4ld\r\n", p.x, p.y);
                WriteConsole(hOut, result, strlen(result), nullptr, nullptr);
                SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cord);
            }
            return 0;
        }

升级版:

#include "stdafx.h"
#include <stdlib.h>
#include <locale.h>  
#include <stdio.h>
#include <windows.h>
#include <tchar.h>

VOID ErrorExit(LPCSTR);
VOID KeyEventProc(KEY_EVENT_RECORD);
VOID MouseEventProc(MOUSE_EVENT_RECORD);

#define  STR_SIZE 256
#define BUFSIZE 65535
#define SHIFTED 0x8000

HANDLE hStdin;
HANDLE hOut;
DWORD fdwSaveOldMode;

DWORD scan = 0; //скан-код последней клавиши
wchar_t code = 0; //код символа последней клавиши
bool alt, ctrl, shift; //состояние управляющих клавиш

void PrintData() {
    DWORD size = STR_SIZE;
    char result[STR_SIZE];

    //GetDC(NULL); // дескриптор стола
    POINT p; // структура для координат
    COORD cord; // структура COORD, которая указывает позицию курсора

    cord.X = 0; // координата X структуры COORD
    cord.Y = 0; // координата Y структуры COORD

    SetConsoleCursorPosition(hOut, cord);
    wsprintf(result, "Позиция курсора: ");
    WriteConsole(hOut, result, strlen(result), nullptr, nullptr);
    GetCursorPos(&p);
    wsprintf(result, "x = %4ld, y = %4ld\r\n", p.x, p.y);
    WriteConsole(hOut, result, strlen(result), nullptr, nullptr);

    if (scan != 0) {
        wsprintf(result, "Последняя нажатая клавиша\nScan code: %4u\r\n", (UINT)scan);
        WriteConsole(hOut, result, strlen(result), nullptr, nullptr);

        wsprintf(result, "Character code: %4u\r\n", (UINT)code);
        WriteConsole(hOut, result, strlen(result), nullptr, nullptr);


        if (ctrl) wsprintf(result, "CTRL:(+) "); else  wsprintf(result, "CTRL:(-) ");
        WriteConsole(hOut, result, strlen(result), nullptr, nullptr);

        if (shift) wsprintf(result, "SHIFT:(+) "); else  wsprintf(result, "SHIFT:(-) ");
        WriteConsole(hOut, result, strlen(result), nullptr, nullptr);

        if (alt) wsprintf(result, "ALT:(+) "); else  wsprintf(result, "ALT:(-) ");
        WriteConsole(hOut, result, strlen(result), nullptr, nullptr);
    }
}

int main()
{
    //setlocale(LC_ALL, "Russian");
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    DWORD cNumRead, fdwMode, i;
    INPUT_RECORD irInBuf[128];

    // Get the standard input handle. 

    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    hOut = GetStdHandle(STD_OUTPUT_HANDLE);

    // Save the current input mode, to be restored on exit. 

    if (!GetConsoleMode(hStdin, &fdwSaveOldMode))
        ErrorExit("GetConsoleMode");

    // Enable the window and mouse input events. 

    fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
    if (!SetConsoleMode(hStdin, fdwMode))
        ErrorExit("SetConsoleMode");

    // Loop to read and handle input events. 

    while (1)
    {
        // Wait for the events. 

        if (!ReadConsoleInput(
            hStdin,      // input buffer handle 
            irInBuf,     // buffer to read into 
            128,         // size of read buffer 
            &cNumRead)) // number of records read 
            ErrorExit("ReadConsoleInput");

        // Dispatch the events to the appropriate handler. 

        for (i = 0; i < cNumRead; i++)
        {
            switch (irInBuf[i].EventType)
            {
            case KEY_EVENT: // keyboard input 
                KeyEventProc(irInBuf[i].Event.KeyEvent);
                break;

            case MOUSE_EVENT: // mouse input 
                MouseEventProc(irInBuf[i].Event.MouseEvent);
                break;

            case WINDOW_BUFFER_SIZE_EVENT:
            case FOCUS_EVENT:
            case MENU_EVENT:
                break;
            }
        }
    }

    // Restore input mode on exit.

    SetConsoleMode(hStdin, fdwSaveOldMode);

    return 0;
}


VOID KeyEventProc(KEY_EVENT_RECORD ker)
{

    if (ker.bKeyDown) {
        scan = ker.wVirtualScanCode;
        code = ker.uChar.UnicodeChar;

        if ((ker.dwControlKeyState & SHIFT_PRESSED) > 0) shift = true; else shift = false;

        if ((ker.dwControlKeyState & LEFT_ALT_PRESSED) > 0 ||
            (ker.dwControlKeyState & RIGHT_ALT_PRESSED) > 0) alt = true;
        else alt = false;

        if ((ker.dwControlKeyState & LEFT_CTRL_PRESSED) > 0 ||
            (ker.dwControlKeyState & RIGHT_CTRL_PRESSED) > 0) ctrl = true;
        else ctrl = false;

        PrintData();
    }

}

VOID MouseEventProc(MOUSE_EVENT_RECORD mer)
{
    if (mer.dwEventFlags == MOUSE_MOVED) {
        PrintData();
    }
}

VOID ErrorExit(LPCSTR lpszMessage)
{
    fprintf(stderr, "%s\n", lpszMessage);

    // Restore input mode on exit.
    SetConsoleMode(hStdin, fdwSaveOldMode);

    ExitProcess(0);
}
c++
  • 1 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-03-11 08:50:59 +0000 UTC

关于GetSysColor函数的问题

  • 2

我正在编写一个应该显示有关系统信息的程序。

任务是这样的:

编写程序以使用 Win32 API 函数获取系统信息:GetSystemInfo()、GetSysColor()、GetSystemMetrics()。提供从键盘输入命令。

使用GetSysColor()函数的颜色输出(在程序中的“系统颜色”部分)存在问题,因为程序应显示与指定显示元素的颜色相对应的数字。但是在编译时,总是使用 , 参数输出零,但它输出相同的一组数字。COLOR_DESKTOP (= 1)COLOR_WINDOWTEXT (= 8)COLOR_WINDOW (= 5)16777215

为了检查,我尝试在 PC 个性化中更改背景颜色,但程序继续显示相同的值。在阅读了此处的文档后,我发现了这个细微差别:

该函数返回给定元素的红、绿、蓝 (RGB) 颜色值。

如果 nIndex 参数超出范围,则返回值为零。因为零也是一个有效的 RGB 值,所以您不能使用 GetSysColor 来确定当前平台是否支持系统颜色。相反,请使用 GetSysColorBrush 函数,如果不支持该颜色,该函数将返回 NULL。

为了检查是否支持颜色,我决定在其他 PC 上进行检查,但结果保持不变。

为什么函数GetSysColor对不同的颜色返回相同的值?

代码本身:

#include "stdafx.h"
#include <stdlib.h>
#include "iostream"
#include <windows.h> 
#include <string>
#include <VersionHelpers.h>
#include <stdio.h>
#include <conio.h>
#pragma comment(lib, "user32.lib")


int main() {

    setlocale(LC_ALL, "rus");
    int count = 0;
    SYSTEM_INFO siSysInfo; // Скопировать информацию об оборудовании в структуру SYSTEM_INFO.
    GetSystemInfo(&siSysInfo); // Отображение содержимого структуры SYSTEM_INFO.

    printf("1.Информация о системе \n");
    printf("2.Системные метрики \n");
    printf("3.Системные цвета \n");

    printf("\n");
    printf("Введите число: ");
    scanf_s("%d", &count);
    printf("\n");
    system("cls");

    switch (count) {
    case 1:
        printf("Aппаратная информация: \n");
        printf("......................\n");
        printf("OEM-идентификатор: %u\n", siSysInfo.dwOemId);
        printf("Количество процессоров: %u\n",
            siSysInfo.dwNumberOfProcessors);
        printf("Размер страницы: %u\n", siSysInfo.dwPageSize);
        printf("Тип процессора: %u\n", siSysInfo.dwProcessorType);
        printf("Минимальный адрес приложения: %p\n",
            siSysInfo.lpMinimumApplicationAddress);
        printf("Максимальный адрес приложения: %p\n",
            siSysInfo.lpMaximumApplicationAddress);
        printf("Маска активного процессора: %u\n",
            siSysInfo.dwActiveProcessorMask);
        break;

    case 2:
        printf("Системные метрики: \n");
        printf("..................\n");
        printf("Разрешение экрана: %dx%d\n",
            GetSystemMetrics(0), GetSystemMetrics(1));
        printf("Ширина курсора в пикселях: %d\n",
            GetSystemMetrics(13));
        printf("Минимальная ширина окна в пикселях: %d\n",
            GetSystemMetrics(28));
        printf("Минимальная ширина окна в пикселях: %d\n",
            GetSystemMetrics(47));
        printf("Количество мониторов на рабочем столе: %d\n",
            GetSystemMetrics(80));
        break;

    case 3:
        printf("Системные цвета: \n");
        printf("................\n");
        printf("Цвет рабочего стола: %u\n",
            GetSysColor(1));
        printf("Текст в окнах: %u\n",
            GetSysColor(8));
        printf("Фон окна: %u\n",
            GetSysColor(5));
        printf("\n");
        printf("\n");
        printf("Значение цифр: \n");
        printf("0 — черный\n");
        printf("1 — синий\n");
        printf("2 — зеленый\n");
        printf("3 — голубой\n");
        printf("4 — красный\n");
        printf("5 — лиловый\n");
        printf("6 — желтый\n");
        printf("7 — белый\n");
        printf("8 — серый\n");
        printf("9 — свело-синий\n");
        printf("A — светло-зеленый\n");
        printf("B — светло-голубой\n");
        printf("С — светло-красный\n");
        printf("E — светло-желтый\n");
        printf("F — ярко-белый\n");
        break;
    default: {
        printf("Error");
    }
}
    _getch();
}
c
  • 2 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-01-03 07:46:34 +0000 UTC

如何正确地将整数数组转换为 ArrayList Java

  • 0

我正在研究 Bert Bates 和 Katya Sierra 关于 Java 的书。

使用 Java 标准库 (API) 中的 ArrayList 类实现游戏(基于海战原理)时,出现错误:

SimpleDotCom 类型中的方法 setLocationCells(ArrayList) 不适用于参数 (int[])

游戏本身是这样的:

          public class SimpleDotComTestDrive {

                public static void main(String[] args) {

                    //переменная для хранения количества ходов
                    int numOfGuesses = 0;
                    //специальный класс, который содержит метод для приема пользовательского ввода.
                    GameHelper helper = new GameHelper();

                    SimpleDotCom theDotCom = new SimpleDotCom();
                    //генерируем случайное число для первой ячейки и используем его для формирования массива ячеек.
                    int randomNum = (int) (Math.random() * 5);

                    // Создаем массив для местоположения (три последовательности числа из семи)
                     int[] locations = {randomNum, randomNum+1, randomNum+2};

                    //передаем местоположение ячеек(массив).

                    theDotCom.setLocationCells(locations);//В этой строчке ошибка с вызовом сеттера setLocationCells

                    //создаем булевую переменную, чтобы проверять в цикле, не закончилась ли игра
                    boolean isAlive = true;

                    while(isAlive == true) {    
                        //получаем строку вводимую пользователем
                        String guess = helper.getUserInput("Введите число");

                        //проверить полученные данные: сохраняем возвращенный результат в переменную типа String
                        String result = theDotCom.checkYourself(guess);

                        //Инкрементируем количество попыток
                        numOfGuesses++;



                        //Если да, то присваиваем isAlive значение false (так как не хотим продолжать цикл) и выводим на экран количество попыток
                        if (result.equals("Потопил")) {
                            isAlive = false;
                            System.out.println("Вам потребовалось " + numOfGuesses + " попыток(и)");
                        }
                    }
                }
            }


            public class SimpleDotCom {

                private ArrayList<Integer> locationCells;

                public void setLocationCells(ArrayList<Integer> loc) { //сеттер
                    locationCells = loc;
                }

                public String checkYourself(String stringGuess) {

                    // Создаем переменную для хранения результата, который будем возвращять.
                    // Присваиваем по умолчанию строковое значение "Мимо"(то есть подразумеваем
                    // промах).
                    String result = "Мимо";

                    //Проверяем содержится ли загаданная пользователем ячейка внутри ArrayList, запрашивая ее индекс.
                    //Если ее нет в списке, то indexOf() возвращает -1.
                    int index = locationCells.indexOf(stringGuess);

                    //Если индекс больше или равен нулю, то загаданная пользователем ячейка определенно
                    //находится в списке, поэтому удаляем ее.
                    if (index >= 0) {
                        locationCells.remove(index);

                        //Если список пустой, значит, это было попадание
                        if(locationCells.isEmpty()) {
                            result = "Потопил";
                        } else {
                            result = "Попал";
                        }
                    }
                    return result;
                }
            }


public class GameHelper {

    public String getUserInput(String prompt) {
        String inputLine = null;
        System.out.print(prompt + " ");
        try {
            BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
            inputLine = is.readLine();
            if (inputLine.length() == 0)
                return null;
        } catch (IOException e) {
            System.out.println("IOException:" + e);
        }
        return inputLine;
    }
}
java
  • 2 个回答
  • 10 Views
Martin Hope
invzbl3
Asked: 2020-11-28 04:07:27 +0000 UTC

通过1个Java字符实现循环右移方法的正确方法是什么?

  • 1

请显示使用逐字符交换(或替换)的方法的实现。

在任务中,需要实现循环右移1个字符(即最后一个字符到第一位)的方法。

最重要的是,我在程序中输入了一串字符,随后我移动了其中的元素。这个方法我试过了,但是编译后的结果不是你需要的。

public String row2(String row) { // сдвиг вправо на 1 элемент
    char[] m = row.toCharArray();
                int n = 1;
                String swappedString = "";
                for (int i = m.length-n; i >= 0; i--) {
                    if(i+n >= row.length()){
                        m[i+n-row.length()] = m[i];
                    }
                    else{
                        m[i+n] = m[i];
                        swappedString +=m[i];
                    }
                }
                return   swappedString;
        }

UPD:在实现中添加了方法

1)      public String swappedString(String row) { 
            String row3 = row.charAt(row.length() - 1) + row.substring(0, 
            row.length() - 1);
            return row3;
        }



2)      public String swappedString(String row) { 
                int cursor = row.length() - 1;    
                return row.substring(cursor) + row.substring(0, cursor);
                 }
java
  • 5 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5