小编jwi*_*ner的帖子

用杰克逊对enum进行反序列化

我正在尝试并且没有用Jackson 2.5.4反序列化枚举,我在那里看不到我的情况.我的输入字符串是驼峰式的,我想简单地映射到标准的Enum约定.

@JsonFormat(shape = JsonFormat.Shape.STRING)
public enum Status {
    READY("ready"),
    NOT_READY("notReady"),
    NOT_READY_AT_ALL("notReadyAtAll");

    private static Map<String, Status> FORMAT_MAP = Stream
            .of(Status.values())
            .collect(toMap(s -> s.formatted, Function.<Status>identity()));

    private final String formatted;

    Status(String formatted) {
        this.formatted = formatted;
    }

    @JsonCreator
    public Status fromString(String string) {
        Status status = FORMAT_MAP.get(string);
        if (status == null) {
            throw new IllegalArgumentException(string + " has no corresponding value");
        }
        return status;
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过@JsonValue一个无用的吸气剂,这是我在别处看到的一个选项.他们都爆炸了:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of ...Status from String value 'ready': value not …
Run Code Online (Sandbox Code Playgroud)

java json jackson

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

Kafka消费者获取主题的元数据失败

我正在尝试为第三方的Kafka和ZooKeeper服务器编写Java客户端.我能够列出和描述主题,但是当我尝试阅读任何主题时,ClosedChannelException会引发a.我使用命令行客户端在这里重现它们.

$ bin/kafka-console-consumer.sh --zookeeper 255.255.255.255:2181 --topic eventbustopic
[2015-06-02 16:23:04,375] WARN Fetching topic metadata with correlation id 0 for topics [Set(eventbustopic)] from broker [id:1,host:SOME_HOST,port:9092] failed (kafka.client.ClientUtils$)
java.nio.channels.ClosedChannelException                                       
    at kafka.network.BlockingChannel.send(BlockingChannel.scala:100)           
    at kafka.producer.SyncProducer.liftedTree1$1(SyncProducer.scala:73)        
    at kafka.producer.SyncProducer.kafka$producer$SyncProducer$$doSend(SyncProducer.scala:72)
    at kafka.producer.SyncProducer.send(SyncProducer.scala:113)                
    at kafka.client.ClientUtils$.fetchTopicMetadata(ClientUtils.scala:58)        
    at kafka.client.ClientUtils$.fetchTopicMetadata(ClientUtils.scala:93)        
    at kafka.consumer.ConsumerFetcherManager$LeaderFinderThread.doWork(ConsumerFetcherManager.scala:66)
    at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:60)         
[2015-06-02 16:23:04,515] WARN Fetching topic metadata with correlation id 0 for topics [Set(eventbustopic)] from broker [id:0,host:SOME_HOST,port:9092] failed (kafka.client.ClientUtils$)
java.nio.channels.ClosedChannelException                                       
    at kafka.network.BlockingChannel.send(BlockingChannel.scala:100)           
    at kafka.producer.SyncProducer.liftedTree1$1(SyncProducer.scala:73)        
    at kafka.producer.SyncProducer.kafka$producer$SyncProducer$$doSend(SyncProducer.scala:72)
    at kafka.producer.SyncProducer.send(SyncProducer.scala:113)                
    at kafka.client.ClientUtils$.fetchTopicMetadata(ClientUtils.scala:58)        
    at kafka.client.ClientUtils$.fetchTopicMetadata(ClientUtils.scala:93)        
    at kafka.consumer.ConsumerFetcherManager$LeaderFinderThread.doWork(ConsumerFetcherManager.scala:66)
    at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:60)         
Run Code Online (Sandbox Code Playgroud)

备用命令成功: …

apache-kafka kafka-consumer-api

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

从@ComponentScan中排除测试类中的配置

我一直在遇到测试类的@ComponentScan问题@Configuration- 也就是说,在集成测试期间会@ComponentScan出现意外@Configuration情况.

例如,假设您有一些全局配置,src/main/java其中包含组件com.example.service,com.example.config.GlobalConfiguration:

package com.example.config;
...
@Configuration
@ComponentScan(basePackageClasses = ServiceA.class)
public class GlobalConfiguration {
    ...
}
Run Code Online (Sandbox Code Playgroud)

它旨在提供两个服务,com.example.services.ServiceAcom.example.services.ServiceB注释@Component@Profile("!test")(为简洁起见省略).

然后在src/test/java中,com.example.services.ServiceATest:

package com.example.services;
...
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ServiceATest.ServiceATestConfiguration.class)
public class ServiceATest {
    ...
    @Configuration
    public static class ServiceATestConfiguration {
         @Bean
         public ServiceA serviceA() {
             return ServiceA(somemocking...);
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

而且com.example.ServiceBIntegrationTest,GlobalConfiguration.class为了进行集成测试需要引入,但仍然避免使用@ActiveProfiles("test")以下方法引入危险的实现:

package com.example.services;
... …
Run Code Online (Sandbox Code Playgroud)

java junit spring unit-testing spring-java-config

8
推荐指数
1
解决办法
8866
查看次数

pandas.DataFrame.equals的合同

我有一个函数的简单测试用例,它返回一个可能包含NaN的df.我正在测试输出和预期输出是否相等.

>>> output
Out[1]: 
      r   t  ts  tt  ttct
0  2048  30   0  90     1
1  4096  90   1  30     1
2     0  70   2  65     1

[3 rows x 5 columns]
>>> expected
Out[2]: 
      r   t  ts  tt  ttct
0  2048  30   0  90     1
1  4096  90   1  30     1
2     0  70   2  65     1

[3 rows x 5 columns]
>>> output == expected
Out[3]: 
      r     t    ts    tt  ttct
0  True  True  True  True  True
1 …
Run Code Online (Sandbox Code Playgroud)

python pandas

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

使用Java流的一对一地图

使用Stream API获取一对一映射时遇到一些麻烦.基本上,说你上课了.

public class Item {
    private final String uuid;

    private Item(String uuid) {
        this.uuid = uuid;
    }

    /**
    * @return universally unique identifier
    */
    public String getUuid() {
        return uuid;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要一个Map<String, Item>容易的查找.但鉴于此Stream<Item>,似乎没有一种简单的方法可以实现Map<String, Item>.

显然,Map<String, List<Item>>不是没有的事情:

public static Map<String, List<Item>> streamToOneToMany(Stream<Item> itemStream) {
    return itemStream.collect(groupingBy(Item::getUuid));
}
Run Code Online (Sandbox Code Playgroud)

这是更安全更普遍的情况,但在这种情况下我们确实知道只会​​有一对一的情况.我找不到任何可编译的东西 - 我特意试图将downstream参数设置为muck Collectors.groupingBy.就像是:

// DOESN'T COMPILE
public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) {
    return itemStream.collect(groupingBy(Item::getUuid, Function.identity()));
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

java java-8 java-stream

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

findFirst 在流上&lt;可选&lt;T&gt;&gt;

假设您有一个流Optional<T>,您想要触发一个Consumer<T>流(如果存在)。

处理这个问题最优雅的方法是什么?

我可以通过过滤Optional::isPresent和映射来进行管理Optional::isGet,但这看起来很“hacky”并且不符合以下精神Optional

Stream.of(a, b, c, d)
   .filter(Optional::isPresent)
   .map(Optional::get)
   .findFirst()
   .ifPresent(s -> System.out.println("This was cumbersome: " + s));
Run Code Online (Sandbox Code Playgroud)

java java-stream option-type

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

按价值锁定

我有一个多线程Java应用程序附加到动态生成的路径上的各种文件(大数 - 超过100k).我想防止并发写入.因为这是JVM中的争用,所以我不能使用FileLocks.

相反,我一直在尝试Path按如下方式对对象进行同步(PathLocker是单例).

 public class PathLocker {
    private final ConcurrentMap<Path, ReentrantLock> pathLockMap = new ConcurrentHashMap<>();

    public void lock(Path path) {
        pathLockMap.computeIfAbsent(path, p -> new ReentrantLock()).lock();
    }

    public void unlock(Path path) {
        ReentrantLock reentrantLock = pathLockMap.get(path);
        if (!reentrantLock.hasQueuedThreads()) { // NPE OCCURS HERE
            pathLockMap.remove(path);
        }
        reentrantLock.unlock();
    }
}
Run Code Online (Sandbox Code Playgroud)

唯一的客户端代码如下所示:

Path path = findPath(directory, dataType, bucketEnd, referenceId);
pathLocker.lock(path);
try {
    try (FileWriter fileWriter = new FileWriter(path.toFile(), true)) {
        fileWriter.write(string);
    }
} finally {
    pathLocker.unlock(path);
} …
Run Code Online (Sandbox Code Playgroud)

java multithreading

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

Spring Integration的动态配置

从RabbitMQ连接规范列表到发布订阅频道上的一系列消费者的正确方法是什么?

也就是说,我说兔子配置如下:

rabbits:
    - hostname: blahblah
      vhost: blahlbah
      username: blahlbah
      password: blahlbalh
      exchange: blahblah
    - hostname: blahblah1
      vhost: blahlbah1
      username: blahlbah1
      password: blahlbalh1
      exchange: blahblah1
    ...
Run Code Online (Sandbox Code Playgroud)

我将这些编组成一个@NestedConfigurationProperty List<RabbitConfiguration>.我可以写一个@Bean方法,让我AmqpTemplate从其中一个List<RabbitConfiguration>,如下:

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public AmqpTemplate amqpTemplate(RabbitConfiguration rabbitConfiguration) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后,我可以基本上将其映射到IntegrationFlow:

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public IntegrationFlow integrationFlow(AmqpTemplate amqpTemplate) {
    return IntegrationFlows.from(inboundPubSubChannel()).handle(Amqp.outboundAdapter(amqpTemplate)).get();
}
Run Code Online (Sandbox Code Playgroud)

然而,正是这样做的正确方法是什么,并由Spring处理List<RabbitConfiguration>结果List<IntegrationFlow>?当然不仅仅是:

@Bean
public List<IntegrationFlow> integrationFlows(List<RabbitConfiguration> rabbitConfigurations) {
    return rabbitConfigurations.stream()
        .map(this::amqpTemplate)
        .map(this::integrationFlow)
        .collect(toList())
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-integration rabbitmq spring-java-config

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

Spring Security OAuth Java配置

我有一个Spring应用程序 - 而不是 Spring Boot应用程序 - 我正在尝试将API的一部分声明为使用Spring Security保护的OAuth2.当我http在XML中定义元素时,我的授权和一般资源访问配置很有效,但是当我尝试使用ResourceServerConfigureAdapter#configure(HttpSecurity)- 完成@EnableResourceServer等等来实现资源访问块时,该configure方法甚至不会触发(端到端测试也会失败).示例Java配置如下:

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.resourceId("oauth2/control");
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**")
                .authorizeRequests().anyRequest().hasRole("OAUTH_USER").and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // before=PRE_AUTH_FILTER
                .addFilterBefore(oAuth2AuthenticationProcessingFilter, AbstractPreAuthenticatedProcessingFilter.class)
                .csrf().disable()
                .anonymous().disable()
                .exceptionHandling()
                .accessDeniedHandler(oAuth2AccessDeniedHandler)
                .authenticationEntryPoint(loginUrlAuthenticationEntryPoint);
        }
Run Code Online (Sandbox Code Playgroud)

我已经尝试声明了一些影响配置的不同方法,但没有骰子.也就是说,我已经尝试过两个顶级@Configuration类扩展ResourceServerConfigurerAdapter和bean方法返回,ResourceServerConfigurationDave Syer的例子 ; 我也试过Ordered.HIGHEST_PRECEDENCE在适当的bean上明确设置顺序.

值得注意的是,大多数应用程序的遗留安全配置都是通过上述XML元素定义的.关于我的配置的另一个可能的红色标志 - 为了让令牌端点对基本的auth client_id进行身份验证:client_secret我必须连接自己的BasicAuthFilter(ProviderManager(DaoAuthProvider(ClientUserDetailsService(clientDetailsService)))))时候,因为它是验证令牌端点的vanilla和'right'方式,我是期望spring config默认为它.

无论如何,在任何情况下我都ResourceServerConfigureAdapter#configure(HttpSecurity)无法开火.我的理论是:

  • 关于前面的XML HTTP块的一些事情阻止了我的 configure方法甚至被调用

  • 这只是一个Spring Boot功能 - 尽管我没有看到这种效果的语言

  • 直上有一个在应用程序上下文对象的一些我失踪(再一次,我在工作的执行注释-除了明显 …

java spring spring-mvc spring-security spring-oauth2

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

'致命错误调用私有方法'但方法受到保护

第一次在PHP中扩展一个类,我遇到一个致命的错误,说该方法是私有的,而不是.我确信这是一些基本的东西,但我已经研究过书籍和论坛,而且我无法确定我为完成此错误所做的工作.任何帮助非常感谢.详情如下:

错误信息:

致命错误:在第726行的/root/includes/classes/testprinter.php中从上下文'testprinter'调用私有方法testgiver :: dbConnect()

testprinter的第726行代码如下:

private function buildquestionarray()
{
  $query = "etc etc";
  **$conn = $this->dbConnect('read');
  $result = $conn->query($query);
  ...
Run Code Online (Sandbox Code Playgroud)

Testprinter扩展了testgiver.这是类的扩展:

require_once('testgiver.php');

class testprinter extends testgiver
{...
Run Code Online (Sandbox Code Playgroud)

并在testgiver中声明方法:

protected function dbConnect($userconnecttype)
{...
Run Code Online (Sandbox Code Playgroud)

再次感谢!

php oop

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

pandas dataframe.where行为不端

我正在尝试实现一个函数,该函数在数据帧或系列的每个位置返回最大值,从而最小化NaN.

In [217]: a
Out[217]: 
   0  1
0  4  1
1  6  0

[2 rows x 2 columns]

In [218]: b
Out[218]: 
    0   1
0 NaN   3
1   3 NaN

[2 rows x 2 columns]


In [219]: do_not_replace = b.isnull() | (a > b)

In [220]: do_not_replace
Out[220]: 
      0      1
0  True  False
1  True   True

[2 rows x 2 columns]


In [221]: a.where(do_not_replace, b)
Out[221]: 
   0  1
0  4  3
1  1  0

[2 rows x 2 columns]


In …
Run Code Online (Sandbox Code Playgroud)

python numpy pandas

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