小编gab*_*uzo的帖子

用Java打印地图

我正在寻找一种漂亮的印刷方式Map.

map.toString() 给我: {key1=value1, key2=value2, key3=value3}

我希望在我的地图条目值中有更多的自由,我正在寻找更像这样的东西: key1="value1", key2="value2", key3="value3"

我写了这段小代码:

StringBuilder sb = new StringBuilder();
Iterator<Entry<String, String>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
    Entry<String, String> entry = iter.next();
    sb.append(entry.getKey());
    sb.append('=').append('"');
    sb.append(entry.getValue());
    sb.append('"');
    if (iter.hasNext()) {
        sb.append(',').append(' ');
    }
}
return sb.toString();
Run Code Online (Sandbox Code Playgroud)

但我确信有更优雅和简洁的方法来做到这一点.

java dictionary pretty-print

130
推荐指数
8
解决办法
14万
查看次数

Spring security oauth2和表单登录配置

我的项目包括两个不同的部分,一个JSF管理面板和一个RESTfull服务.我正在尝试设置spring security以使用不同的身份验证方法,具体取决于用户导航的URL.

要求是

  • 导航到JSF页面的用户获得一个登录屏幕,他们使用表单身份验证进行身份验证.
  • 导航到REST服务的用户使用OAuth2隐式身份验证和基本身份验证进行令牌授予.

单独的配置单独工作,问题是当我尝试在一个配置中组合它们时,在这种情况下,似乎REST提供程序阻碍并验证每个请求,即使请求转到管理URL(这从春季安全订购中记录).

我的示例配置如下所示:

  • 对于表单登录(JSF)

    @Override
    @Order(1)
    protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/templates/**").permitAll()
            .antMatchers("/401.html").permitAll()
            .antMatchers("/404.html").permitAll()
            .antMatchers("/500.html").permitAll()
            .antMatchers("/api/**").permitAll()
            .antMatchers("/ui/admin.xhtml").hasAnyAuthority("admin", "ADMIN")
            .antMatchers("/thymeleaf").hasAnyAuthority("admin", "ADMIN")
            //.anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/ui/index.xhtml")
            .failureUrl("/login?error=1")
            .permitAll()
            .and()
            .logout()
            .permitAll()
            .and()
            .rememberMe()
            .and().exceptionHandling().accessDeniedPage("/error/403");
    
    Run Code Online (Sandbox Code Playgroud)
  • OAuth2安全配置(REST)

    @EnableResourceServer
    @Order(2)
    public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Inject
        private UserRepository userRepository;
    
        @Inject
        private PasswordEncoder passwordEncoder;
    
        @Bean
        ApplicationListener<AbstractAuthorizationEvent> loggerBean() {
            return new AuthenticationLoggerListener();
        }
    
        @Bean
        AccessDeniedHandler accessDeniedHandler() {
            return new AccessDeniedExceptionHandler();
        }
    
        @Bean
        AuthenticationEntryPoint entryPointBean() { …
    Run Code Online (Sandbox Code Playgroud)

spring spring-security oauth-2.0 spring-java-config

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

Spring上的嵌套事务

我在使用嵌套的Spring事务时发现了一些奇怪的行为:当在同一个类中,一个注释为@Transactional调用的方法时,另一个注释为@Transactional第二个注释的方法也没有被使用.

我们考虑以下课程:

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        final Main main = context.getBean(Main.class);
        // First Op
        System.out.println("Single insert: " + main.singleInsert());
        // Second Op
        main.batchInsert();
        // Third Op
        main.noTransBatchInsert();
    }

    @PersistenceContext
    private EntityManager pm;

    @Transactional(propagation=Propagation.REQUIRED)
    public void batchInsert() {
        System.out.println("batchInsert");
        System.out.println("First insert: " + singleInsert());
        System.out.println("Second insert: " + singleInsert());
    }

    public void noTransBatchInsert() {
        System.out.println("noTransBatchInsert");
        System.out.println("First insert: " + singleInsert());
        System.out.println("Second insert: " + singleInsert());
    } …
Run Code Online (Sandbox Code Playgroud)

spring annotations transactions

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

JBoss Cache和Ehcache的性能

我正在考虑使用JBoss Cache或Ehcache来实现缓存.在查看这两个API后,我直觉认为JBoss可能比Ehcache更有效,因为它可以将原始对象放入缓存,而Ehcache需要将数据包装在Element对象中.

我设置了一个快速的工作台,在缓存中重复插入密钥,值元组.键和值类非常简单:

键:

public class Key implements Serializable {
    private static final long serialVersionUID = -2124973847139523943L;

    private final int key;

    public Key(int pValue) {
        this.key = pValue;
    }

    public int getValue() {
        return this.key;
    }

    @Override
    public String toString() {
        return "Key [key=" + this.key + "]";
    }
}
Run Code Online (Sandbox Code Playgroud)

值:

public class Value implements Serializable{

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -499278480347842883L;
}
Run Code Online (Sandbox Code Playgroud)

当将100000个对象的结果插入到内存中时,Ehcache使用13396个字节来存储对象,而JBoss使用5712个字节进行相同的操作(由于使用了ConcurrentHashMap5680字节的相同测试,因此很好).

然而,当我查看执行时间时,我有一个非常糟糕的惊喜:Ehcache需要300毫秒来执行测试,而JBossCache需要44秒才能执行相同操作.我很确定我的JBoss配置中有一些东西在解释这种差异.

Ehcache以编程方式初始化如下:

CacheConfiguration cacheConfiguration = …
Run Code Online (Sandbox Code Playgroud)

java performance ehcache jboss-cache

9
推荐指数
1
解决办法
9595
查看次数

JMeter和可选的SSL客户端证书

我正在使用涉及SSL客户端证书的JMeter 2.8设置测试计划.测试计划大致包括对server1和server2的两次https调用.

棘手的部分是对server1的调用不应该使用SSL客户端身份验证(尽管服务器正在请求一个),而对server2的调用必须使用SSL客户端身份验证.

目前,只要我向JMeter提供密钥库,所有https呼叫都会发送SSL证书,导致对server1的调用失败.

我目前尝试了两种方法:

  1. -Djava.net.ssl.keyStore=xxx从JMeter命令行中删除了它并使用BeanShell或BSH预处理器在调用server2之前设置它但它不起作用并且调用服务器2失败,就好像没有指定密钥库一样.
  2. 我尝试使用Keystore管理配置程序在调用server1之前指定一个不存在的键,但是当我将开始和结束索引放在商店中的最后一个证书之后时,JMeter仍然会在商店中发送第一个证书.

jmeter ssl-certificate

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

Spring-boot oauth2拆分授权服务器和资源服务器

我试图在spring-boot中将资源服务器从授权服务器中分离出来.我有两个不同的应用程序,我分开运行.在授权服务器中,我可以从oauth/token获取承载令牌,但是当我试图访问资源(在头部中发送令牌)时,我收到了无效的令牌错误.我的目的是使用InMemoryTokenStore和承载令牌.谁能告诉我我的代码有什么问题?

授权服务器:

@SpringBootApplication
public class AuthorizationServer extends WebMvcConfigurerAdapter {

  public static void main(String[] args) {
    SpringApplication.run(AuthorizationServer.class, args);
  }

  @Configuration
  @EnableAuthorizationServer
  protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

  private TokenStore tokenStore = new InMemoryTokenStore();

  @Autowired
  private AuthenticationManager authenticationManager;

  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints
        .authenticationManager(authenticationManager)
        .tokenStore(tokenStore);
  }

  @Override
  public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
      security.checkTokenAccess("hasAuthority('ROLE_USER')");
  }

  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      clients
          .inMemory()
            .withClient("user")
            .secret("password")
            .authorities("ROLE_USER")
            .authorizedGrantTypes("password")
            .scopes("read", "write")
            .accessTokenValiditySeconds(1800);
  }  
}
Run Code Online (Sandbox Code Playgroud)

资源服务器:

@SpringBootApplication …
Run Code Online (Sandbox Code Playgroud)

java oauth-2.0 spring-boot spring-security-oauth2

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