小编Ayu*_*lik的帖子

当Spring不在方法签名中时,Spring MockMVC会注入mockHttpServletRequest

鉴于我已经继承了一些带有签名的Spring MVC控制器代码

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView upload(HttpServletRequest request, HttpServletResponse response) {

  String remoteAddress = request.getRemotedAddr();
  auditService.logAddress(remoteAddress);

  // do work...

  return mav;
}
Run Code Online (Sandbox Code Playgroud)

我有一个执行测试的Spring MockMvc测试

public void someTest() {
    mockMvc().perform(fileUpload("/upload").file(FileFactory.stringContent("myFile")));

    // do work...
    verify(auditService.logAddress("123456"));
}
Run Code Online (Sandbox Code Playgroud)

我需要在传递给我的上传控制器方法的HttpServletRequest对象上将远程地址设置为"12345",这样我就可以在测试中验证对模拟auditService的调用.

我可以创建一个MockHttpServletRequest对象并调用setRemoteAddr()方法,但是如何将这个模拟请求对象传递给mockMvc()方法调用?

spring integration-testing controller mocking spring-mvc

14
推荐指数
1
解决办法
7451
查看次数

在函数名称之前使用下划线来转换struct标记

我正在使用go,特别是QT绑定.但是我不明白在下面的结构中使用前导下划线.我知道一般使用下划线但不是这个具体的例子.

type CustomLabel struct {
    core.QObject

    _ func() `constructor:"init"`
    _ string `property:"text"`
}
Run Code Online (Sandbox Code Playgroud)

它与struct标签有关吗?

struct naming-conventions go

12
推荐指数
2
解决办法
674
查看次数

Spring Security Java Config不生成logout url

我使用的是Spring 4.0.5.RELEASE和Spring Security 3.2.4.

我正在尝试使用java配置创建一个简单的示例应用程序(基于Spring示例).应用程序启动并且身份验证正常运行,也就是说,在访问受保护的url / settings/profile时,我被重定向到登录表单

但是没有/ logout url生成?如果我点击localhost:8080/logout我得到404.

我在之前的项目中使用了类似的代码,所以可能与版本有关?

继承我的安全配置

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/settings/**").hasRole("ROLE_ADMIN")
                    .and()
                .formLogin()
                    .and()
                .logout()
                    .deleteCookies("remove")
                    .invalidateHttpSession(true)
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/logout-success")
                .permitAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的WebAppInitializer来引导应用程序

 public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { SecurityConfig.class , MvcConfig.class };
    }

    @Override
    protected Class<?>[] …
Run Code Online (Sandbox Code Playgroud)

java configuration spring spring-security spring-java-config

11
推荐指数
1
解决办法
2万
查看次数

Spring HandlerMethodArgumentResolver没有执行

我正在使用Spring MVC 3.2.2

我已经定义了这样的自定义HandlerMethodArgumentResolver类

public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {

  public CurrentUserArgumentResolver() {
    System.out.println("Ready");
  }

  @Override
  public boolean supportsParameter(MethodParameter parameter) {
    return parameter.hasParameterAnnotation(CurrentUser.class);
  }

  @Override
  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

      Principal principal = webRequest.getUserPrincipal();
      System.out.println("*** Principal ***: " + principal);
      return principal;
  }
}
Run Code Online (Sandbox Code Playgroud)

并将以下内容添加到我的app-servlet.xml中

<mvc:annotation-driven>
  <mvc:argument-resolvers>
    <beans:bean class="my.package.CurrentUserArgumentResolver" lazy-init="false"/>
  </mvc:argument-resolvers>
</mvc:annotation-driven>
Run Code Online (Sandbox Code Playgroud)

并为CurrentUser创建了一个注释

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUser {

}
Run Code Online (Sandbox Code Playgroud)

当我启动应用程序时,构造了类,因为我可以看到日志消息"Ready",但是当我注释控制器方法时(在具有@Controller注释的类中),解析器不会执行

@RequestMapping(method = RequestMethod.POST, value = "/update")
public ModelAndView update(@RequestParam MultipartFile background, …
Run Code Online (Sandbox Code Playgroud)

spring annotations spring-mvc

10
推荐指数
2
解决办法
1万
查看次数

JavaFx 2使用单列创建TableView

我正在尝试使用以下代码创建一个包含单个列的表:

TableView<String> table = new TableView<String>();
table.getColumns().clear();
table.getColumns().add(new TableColumn<String, String>("City Name"));
table.setItems(cityList);
Run Code Online (Sandbox Code Playgroud)

但是,我得到一个表格,其中包含"城市名称"列,后面是空白列

我是JavaFx的新手,所以可能有更好的方法.

java layout tableview javafx-2

7
推荐指数
1
解决办法
7019
查看次数

使用Maven运行JUnit测试时,Spring MockMvc WebApplicationContext为null

我有一个Spring mock-mvc JUnit测试类,它包含两个测试.当我在Eclipse IDE中运行测试时,两个测试都通过(我使用Eclipse Maven插件).

使用时从命令行运行测试

mvn test
Run Code Online (Sandbox Code Playgroud)

其中一个测试失败,因为@Autowired的WebApplicationContext 有时为 null.

这是我的测试课

@WebAppConfiguration
@ActiveProfiles({ "dev", "test" })
public class AddLinkEndpointMvcTest extends BaseMvc {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void before() {
        System.out.println("WAC = " + wac);
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void addLinkDoesNotSupportGet() throws Exception {
        mockMvc.perform(get("/myurl")).andExpect(status().is(HttpStatus.SC_METHOD_NOT_ALLOWED));
    }

    @Test
    public void addLinkBadRequestNoLinkAddress() throws Exception {
        mockMvc.perform(post("/myurl")).andExpect(status().is(HttpStatus.SC_BAD_REQUEST));
    }
}
Run Code Online (Sandbox Code Playgroud)

这是BaseMvc类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class BaseMvc {

    @Configuration
    @ComponentScan(basePackages = { "com.example.a", "com.example.b" })
    @Profile("test") …
Run Code Online (Sandbox Code Playgroud)

java testing junit spring-mvc maven

6
推荐指数
1
解决办法
1万
查看次数

带缓冲通道的 For 循环

我正在尝试 Go 通道,但遇到一个问题,下面的简单程序不会终止。

本质上我想发出一些异步 HTTP get 请求,然后等待它们全部完成。我正在使用缓冲通道,但我不确定这是惯用的方式。

func GetPrice(quotes chan string) {
    client := &http.Client{}
    req, _ := http.NewRequest("GET", "https://some/api", nil)
    req.Header.Set("Accept", "application/json")
    res, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    quotes <- string(body)
}

func main() {
    const max = 3
    quotes := make(chan string, max)
    for i := 0; i < max; i++ {
        go GetPrice(quotes)
    }

    for n := range quotes {
        fmt.Printf("\n%s", n) …
Run Code Online (Sandbox Code Playgroud)

for-loop channel go buffered

6
推荐指数
1
解决办法
2万
查看次数

Hibernate @SequenceGenerator不是全局的

我有两个使用生成值的实体类

@Entity
@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
public class Ent1 {
    @Id
    @GeneratedValue(generator = "idgen")
    private Long id;

    ...
}

@Entity
public class Ent2 {
    @Id
    @GeneratedValue(generator = "idgen")
    private Long id;

    ...
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果不放线

@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
Run Code Online (Sandbox Code Playgroud)

两个实体上我收到一个错误:

Caused by: org.hibernate.AnnotationException: Unknown Id.generator: idgen
Run Code Online (Sandbox Code Playgroud)

但JPA规范说@SequenceGenerator的范围是"全局的",可以跨实体重用.

我错过了什么?

annotations hibernate jpa sequence-generators

5
推荐指数
1
解决办法
1492
查看次数

Hazelcast 3.6.1“没有适合类型的反序列化器”异常

我正在使用 Hazelcast 3.6.1 从地图中读取。存储在地图中的对象类称为Schedule

我已经像这样在客户端配置了一个自定义序列化程序。

ClientConfig config = new ClientConfig();
SerializationConfig sc = config.getSerializationConfig();
sc.addSerializerConfig(add(new ScheduleSerializer(), Schedule.class));
...
private SerializerConfig add(Serializer serializer, Class<? extends Serializable> clazz) {
    SerializerConfig sc = new SerializerConfig();
    sc.setImplementation(serializer).setTypeClass(clazz);
    return sc;
}
Run Code Online (Sandbox Code Playgroud)

地图是这样创建的

private final IMap<String, Schedule> map = client.getMap("schedule");
Run Code Online (Sandbox Code Playgroud)

如果我使用 schedule id 作为键从地图中获取,则地图返回正确的值,例如

return map.get("zx81");
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用 SQL 谓词,例如

return new ArrayList<>(map.values(new SqlPredicate("statusActive")));
Run Code Online (Sandbox Code Playgroud)

然后我收到以下错误

Exception in thread "main" com.hazelcast.nio.serialization.HazelcastSerializationException: There is no suitable de-serializer for type 2. This exception is likely to …
Run Code Online (Sandbox Code Playgroud)

serialization client kryo hazelcast

5
推荐指数
1
解决办法
1万
查看次数

使用 cmd 和 pkg 布局构建项目 - 构建错误

我正在尝试使用 Go 项目布局中描述的布局构建Go 项目

我在 Ubuntu 上使用 go 1.9.2。我的项目布局如下

$GOPATH/src/github.com/ayubmalik/cleanprops
    /cmd
        /cleanprops
            /main.go
    /internal
        /pkg
            /readprops.go
Run Code Online (Sandbox Code Playgroud)

文件 cmd/cleanprops/main.go 指的是 cleanprops 包,即

package main

import (
    "fmt"
    "github.com/ayubmalik/cleanprops"
)

func main() {
    body := cleanprops.ReadProps("/tmp/hello.props")
    fmt.Println("%s", body)
}
Run Code Online (Sandbox Code Playgroud)

Internal/pkg/readprops.go 的内容是:

package cleanprops

import (
    "fmt"
    "io/ioutil"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func ReadProps(file string) string {
    body, err := ioutil.ReadFile(file)
    check(err)
    fmt.Println(string(body))
    return body
}
Run Code Online (Sandbox Code Playgroud)

但是,当我从目录 $GOPATH/src/github.com/ayubmalik/cleanprops 内部构建 cmd/cleanprops/main.go 时,使用命令:

go build …
Run Code Online (Sandbox Code Playgroud)

standards build go

5
推荐指数
1
解决办法
4097
查看次数

使用Maven插件设置JMeter属性

我正在使用JMeter的Maven插件(http://jmeter.lazerycode.com/).

在我的JMeter测试计划中,我定义了各种属性,例如hostName,threadCount等.

如果我从命令行使用标准的JMeter程序,我会指定如下属性:

jmeter -n -t mytest.jmx -JhostName=www.example.com -JthreadCount=5
Run Code Online (Sandbox Code Playgroud)

由于Maven JMeter插件是通过以下命令执行的:

mvn verify
Run Code Online (Sandbox Code Playgroud)

如何传递属性值?命令:

mvn verify -JhostName=www.example.com -JthreadCount=5
Run Code Online (Sandbox Code Playgroud)

似乎没有用.我一定错过了一些明显的东西

properties jmeter maven jmeter-maven-plugin

4
推荐指数
1
解决办法
7314
查看次数

Scala spray-client定义了AKKA ActorRefFactory的含义

我正在尝试使用Scala和spray-client编写一个简单的HTTP客户端.我的客户基于Spray文档上给出的示例.

我的问题是该示例是创建一个新的隐式 ActorSystem即

implicit val system = ActorSystem()
Run Code Online (Sandbox Code Playgroud)

但我希望我的客户端可以重用,而不是创建一个新的ActorSystem.

这是我的代码的要点.

trait WebClient {
  def get(url: String)(implicit system: ActorSystem): Future[String]
}

object SprayWebClient extends WebClient {
  val pipeline: HttpRequest => Future[HttpResponse] = sendReceive

  def get(url: String): Future[String] = {
    val r = pipeline (Get("http://some.url/"))
    r.map(_.entity.asString)
  }

}
Run Code Online (Sandbox Code Playgroud)

但我得到两个关于implicits的编译器错误

implicit ActorRefFactory required: if outside of an Actor you need an implicit ActorSystem, inside of an actor this should be the implicit ActorContext WebClient.scala ...
Run Code Online (Sandbox Code Playgroud)

not enough arguments for …
Run Code Online (Sandbox Code Playgroud)

scala actor akka implicits spray

3
推荐指数
1
解决办法
4276
查看次数

Akka Scala TestKit 测试 PoisonPill 消息

假设我有一个Supervisor注入了childActor 的 Actor,如何向孩子发送 PoisonPill 消息并使用 TestKit 进行测试?

这是我的主管。

class Supervisor(child: ActorRef) extends Actor {

  ...
  child ! "hello"
  child ! PoisonPill
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码

val probe = TestProbe()
val supervisor = system.actorOf(Props(classOf[Supervisor], probe.ref))
probe.expectMsg("hello")
probe.expectMsg(PoisonPill)
Run Code Online (Sandbox Code Playgroud)

问题是PoisonPill没有收到消息。可能是因为探测被PoisonPill消息终止了?

断言失败

java.lang.AssertionError: assertion failed: timeout (3 seconds) 
during expectMsg while waiting for PoisonPill
Run Code Online (Sandbox Code Playgroud)

testing scala akka testkit

3
推荐指数
1
解决办法
1036
查看次数