我想快速删除最后一个对象ArrayList.
我知道remove(Object O)接受O(n)一个ArrayList,但我想知道是否有可能在恒定时间内这样做,因为我只想删除最后一个对象?
我想将表单中的文件上传到Spring Boot API端点.
UI是用React编写的:
export function createExpense(formData) {
return dispatch => {
axios.post(ENDPOINT,
formData,
headers: {
'Authorization': //...,
'Content-Type': 'application/json'
}
).then(({data}) => {
//...
})
.catch(({response}) => {
//...
});
};
}
_onSubmit = values => {
let formData = new FormData();
formData.append('title', values.title);
formData.append('description', values.description);
formData.append('amount', values.amount);
formData.append('image', values.image[0]);
this.props.createExpense(formData);
}
Run Code Online (Sandbox Code Playgroud)
这是java端代码:
@RequestMapping(path = "/{groupId}", method = RequestMethod.POST)
public ExpenseSnippetGetDto create(@RequestBody ExpensePostDto expenseDto, @PathVariable long groupId, Principal principal, BindingResult result) throws IOException {
//..
}
Run Code Online (Sandbox Code Playgroud)
但是我在java方面得到了这个例外:
org.springframework.web.HttpMediaTypeNotSupportedException: Content …Run Code Online (Sandbox Code Playgroud) 我正在为我的Spring启动应用程序Rest控制器编写集成测试.
当我用@Transactional它注释测试类时,它没有按预期工作,当我删除注释时,它传递正常.
@Transactional在测试类上使用是否意味着什么都没有写入db?我的其他测试工作正常!他们或多或少地做同样的工作.他们写/更新/读取,但此测试测试删除端点.
如果使用@Transactional注释测试类意味着无法控制数据持久性,为什么人们甚至在测试中使用它?我注入实体管理器测试类,并呼吁flush和clear,它并没有帮助.
即使数据没有写入数据库,它们仍然存在,对吧?不调用repository.delete应该从持久化上下文中删除该项吗?
不影响db(delete)的代码位于Service层.它是在Controller中调用的,我正在测试,而不是测试类.无论测试类是否注释,我都希望它能够正常工作@Transacational.
注意服务层是@Transactional
它位于服务层中,由控制器调用.它不是测试中的形式.
public void delete(long groupId, String username) {
Group group = this.loadById(groupId);
User user = userService.loadByUsername(username);
groupRepository.delete(groupId);
}
Run Code Online (Sandbox Code Playgroud)
编辑1
失败的测试代码:
/*
* Deleting a group shouldn't delete the members of that group
*/
@Test
public void testDeleteGroupWithMembers() throws Exception {
Principal mockPrincipal = Mockito.mock(Principal.class);
Mockito.when(mockPrincipal.getName()).thenReturn(DUMMY_USERNAME);
User admin = userTestingUtil.createUser(DUMMY_USERNAME, DUMMY_USER_NAME, null, null);
Group group = groupTestingUtil.createGroup(DUMMY_GROUP_NAME, DUMMY_GROUP_DESCRIPTION, DUMMY_IMAGE_ID, admin);
User …Run Code Online (Sandbox Code Playgroud) 我正在为Spring boot Rest控制器编写测试.此休止控制器将一些值写入db.
我想使用Spring为此测试提供的内存数据库.根据这个文档,我必须使用注释测试类@DataJpaTest,这会导致此错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
Run Code Online (Sandbox Code Playgroud)
在错误堆栈跟踪中,我看到引发了以下异常:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoconfigureTestDatabase. …
作为我的 bash 脚本的一部分,我想以非交互模式安装和卸载我在文件中具有它们名称的 pip 依赖项。我能够搜索并找到这些命令:
pip3 uninstall --yes -r host-requirements.txt
pip3 install --no-input -r host-requirements.txt
Run Code Online (Sandbox Code Playgroud)
我无法在 pip 的帮助文档中找到--yes&--no-input选项,我不确定它们是否得到官方支持。
我正在为Rest API控制器编写测试.无需任何授权即可访问此端点:
@EnableWebSecurity
@Configuration
@Import(AppConfig.class)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsRepository accountRepository;
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Autowired
private JWTAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.anyRequest().authenticated().and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
/*
* Apparently, permitAll() doesn't work for custom filters, therefore we ignore the signup and login endpoints
* here
*/
@Override
public void configure(WebSecurity web)
throws Exception {
web.ignoring()
.antMatchers(HttpMethod.POST, "/login")
.antMatchers(HttpMethod.POST, "/signup");
}
/*
* set user details services and …Run Code Online (Sandbox Code Playgroud) 在我的Spring启动应用程序中,我有很多端点/api/**.以下是我的App配置:
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
private class PushStateResourceResolver implements ResourceResolver {
private Resource index = new ClassPathResource("/public/index.html");
private List<String> handledExtensions = Arrays.asList("html", "js",
"json", "csv", "css", "png", "svg", "eot", "ttf", "woff",
"appcache", "jpg", "jpeg", "gif", "ico");
private List<String> ignoredPaths = Arrays.asList("^api\\/.*$");
@Override
public Resource resolveResource(HttpServletRequest request,
String requestPath, List<? extends Resource> locations,
ResourceResolverChain chain) {
return resolve(requestPath, locations);
}
@Override
public String resolveUrlPath(String resourcePath,
List<? extends Resource> locations, ResourceResolverChain chain) {
Resource resolvedResource = resolve(resourcePath, …Run Code Online (Sandbox Code Playgroud) 在我的Spring启动应用程序中,我有以下两个类:
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// TODO re-enable csrf after dev is done
.csrf()
.disable()
// we must specify ordering for our custom filter, otherwise it
// doesn't work
.addFilterAfter(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class)
// we don't need Session, as we are using jwt instead. Sessions
// are harder to scale and manage
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
} …Run Code Online (Sandbox Code Playgroud) 我为模型映射器配置了以下配置,以将User类的实例转换为实例ExtendedGetUserDto.
public ExtendedGetUserDto convertToExtendedDto(User user) {
PropertyMap<User, ExtendedGetUserDto> userMap = new PropertyMap<User, ExtendedGetUserDto>() {
protected void configure() {
map().setDescription(source.getDescription());
map().setId(source.getId());
// map().setReceivedExpenses(
// source.getReceivedExpenses()
// .stream()
// .map(expense -> expenseDtoConverter.convertToDto(expense))
// .collect(Collectors.toSet())
// );
Set<GetInvitationDto> result = new HashSet<GetInvitationDto>();
for (Invitation inv: source.getReceivedInvitations()) {
System.out.println("HELLO");
//result.add(null);
}
//map().setReceivedInvitations(result);
}
};
modelMapper.addMappings(userMap);
return modelMapper.map(user, ExtendedGetUserDto.class);
}
Run Code Online (Sandbox Code Playgroud)
在评论之前setReceivedExpense我收到了这个错误:
org.modelmapper.ConfigurationException: ModelMapper configuration errors:
1) Invalid source method java.util.stream.Stream.map(). Ensure that method has zero parameters and does not …Run Code Online (Sandbox Code Playgroud) java ×8
spring ×5
spring-boot ×4
arraylist ×1
flux ×1
hibernate ×1
javascript ×1
modelmapper ×1
pip ×1
python ×1
reactjs ×1
security ×1
testing ×1