小编Arm*_*ine的帖子

如何断言String不为空

断言jun中的a string不是空的,可以通过以下方式完成:

 assertTrue(!string.isEmpty());
 assertFalse(string.isEmpty());
 assertThat(string.toCharArray(), is(not(emptyArray())); // (although this didn't compile)
Run Code Online (Sandbox Code Playgroud)

我的问题是:有没有更好的方法来检查这个 - 比如:

assertThat(string, is(not(empty()))

java junit unit-testing hamcrest

26
推荐指数
3
解决办法
4万
查看次数

无法使用applet中的ucanaccess方法连接或插入数据库

使用jdbc:ucanaccess方法将一个applet连接到Access DB时,出现以下错误:

Firstdb.java:44: error: unreported exception SQLException; 
must be caught or declared to be thrown
stmt.executeUpdate(sql);   
                  ^
Run Code Online (Sandbox Code Playgroud)

我用于applet的代码如下(add()setBounds()从中删除init()):

public class Firstdb extends Applet implements ActionListener {
    TextField t1, t2;
    Label l1;
    Button b1, b2;
    Connection con;
    Statement stmt;

    public void init() {
        try {
            con = DriverManager.getConnection("jdbc:ucanaccess://H:/test/db.mdb");
            stmt = con.createStatement();
        } catch (Exception e) {
        }
    }

    public void actionPerformed(ActionEvent ae) {
        String sql;

        if (ae.getSource() == b1) {
            sql = "insert into user …
Run Code Online (Sandbox Code Playgroud)

java ms-access applet jdbc ucanaccess

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

如何在JPA中构造插入查询

我试图将数据插入到具有表列(名称,值)

Query query = em.createQuery("INSERT INTO TestDataEntity (NAME, VALUE) VALUES (:name, :value)");
query.setParameter("name", name);
query.setParameter("value", value);
query.executeUpdate();
Run Code Online (Sandbox Code Playgroud)

并获得以下异常:

ERROR org.hibernate.hql.internal.ast.ErrorCounter - line 1:42: unexpected token: VALUES 
Run Code Online (Sandbox Code Playgroud)

此外,我无法使用本机查询插入记录:

Query query = em.createNativeQuery("INSERT INTO TEST_DATA (NAME, VALUE) VALUES (:name, :value);");
query.setParameter("name", name);
query.setParameter("value", value);
query.executeUpdate();
Run Code Online (Sandbox Code Playgroud)

另一个例外是抛出:

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
Run Code Online (Sandbox Code Playgroud)

问题是:

  • 查询字符串有什么问题?

非常感谢.

java entity hibernate jpa

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

Log4j2:没有可用的log4j-web模块

我试图将配置的状态级别设置为"info",但我得到以下输出:

INFO Log4j appears to be running in a Servlet environment, but there's no log4j-web module available. If you want better web container support, please add the log4j-web JAR to your web archive or server lib directory.
Run Code Online (Sandbox Code Playgroud)

我的log4j2.xml有以下内容

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" packages="org.graylog2.log4j2">
    <Properties>
        <Property name="default_pattern">%d{MM/dd/yyyy hh:mm:ss} %5p %c{1} - %m%n</Property>
    </Properties>

    <!--  LOG4J2 APPENDERS -->
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="${default_pattern}"/>
        </Console>
        <Console name="com.sum.exam" target="SYSTEM_OUT">
            <PatternLayout pattern="${default_pattern}"/>                            
        </Console>
        <Console name="auth" target="SYSTEM_OUT">
            <PatternLayout pattern="${default_pattern}"/>                            
        </Console>
        <Console name="com.d.e" target="SYSTEM_OUT">
            <PatternLayout …
Run Code Online (Sandbox Code Playgroud)

java log4j log4j2

5
推荐指数
2
解决办法
9674
查看次数

可以在指定WSDL文件时使用XSD断言

我有一个WSDL文件,其中还包含其中使用的所有类型(通过<wsdl:types> 标记).在定义类型时,我有这样的事情:

<wsdl:definitions name="service"
        targetNamespace="http://www.xxx.yyy/reg/definitions" xmlns="http://schemas.xmlsoap.org/wsdl/"
        xmlns:tax="http://www.xxx.yyy/reg/definitions" xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
    .............
    <xs:complexType name="CompanyName">
        <xs:sequence>
            <xs:element name="Name" type="xs:string" />
            <xs:element name="ShortName" type="xs:string" minOccurs="0" />
        </xs:sequence>
        <xs:attribute name="Language" type="tax:LanguageType" use="required"/>
        <xs:assert test="ShortName or @Language != 'Language1'"/>
    </xs:complexType>
    .............
</wsdl:definitions>
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我尝试在Tomcat上启动应用程序时,它无法提供以下异常:

javax.xml.ws.WebServiceException: org.xml.sax.SAXParseException; s4s-elt-invalid-content.1: The content of 'CompanyName' is invalid.  Element 'assert' is invalid, misplaced, or occurs too often.
Run Code Online (Sandbox Code Playgroud)

WSDL版本是1.2,我不知道在其中描述类型时它使用哪个版本的xsd,所以我不知道它是xsd版本(1.0对1.1)问题还是别的.

有人可以帮助我找到真正的问题吗?

编辑:我添加了wsdl的标题.我已将version attribute(version="1.1")添加到<xs:schema> 定义中,但这也没有帮助:

<xs:schema targetNamespace="http://www.xxx.yyy/reg/definitions" elementFormDefault="qualified" version="1.1">
Run Code Online (Sandbox Code Playgroud)

java xsd tomcat wsdl web-services

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

异常:org.springframework.core.convert.ConverterNotFoundException:找不到能够从类型转换的转换器

我正在尝试使用本机查询从数据库中选择一些条件为 true 的列。当我收到邮递员的请求时,我收到上述错误。下面包含完整的日志。我正在 java 8 上运行 spring-boot 应用程序,Db 是 PostgreSQL。请指出出了什么问题以及如何解决。

错误日志 -

2020-01-17 14:12:23.281 ERROR 26528 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.mastercard.ptsAmericas.QualityScore.models.ScoreCardForSummary]] with root cause

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.mastercard.ptsAmericas.QualityScore.models.ScoreCardForSummary]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321) ~[spring-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194) ~[spring-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174) ~[spring-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:297) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:217) …
Run Code Online (Sandbox Code Playgroud)

java spring-data-jpa spring-boot

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

多线程 Spring Boot 应用程序使 MySQL 进程处于睡眠状态

我有一个用于 cron 任务的 Spring Boot 应用程序。其中一个任务作为一组异步执行的多个线程来执行。每个线程都会在 MySQL 兼容的 AWS Aurora Serverless DB 中插入约 200K 数据。在任务完成之前,所有线程都在完成后关闭,但MySQL中相应的进程仍以“睡眠”状态保留在进程列表中。这是缩短的示例:

@SpringBootApplication
@EnableScheduling
public class ScheduledServiceApp implements SchedulingConfigurer {
    private static final int POOL_SIZE = 20;

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


    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
        threadPoolTaskScheduler.setThreadNamePrefix("scheduled-task-pool-");
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
     }
}


@Component
public class ScheduledTask {

    // .....

    @Scheduled(cron = "${task.cron.expression}", zone="UTC")
    // @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Transactional
    public void runTask() …
Run Code Online (Sandbox Code Playgroud)

java mysql multithreading amazon-web-services amazon-aurora

5
推荐指数
2
解决办法
943
查看次数

单位或整合测试可以有吸气剂和固定剂吗?

我正在尝试编写集成测试,并希望以最佳方式编写最佳实践,礼仪等.

首先,我有一个关于如何在另一个测试类中重用现有测试的问题,我在主题如何在另一个测试类中重用现有的JUnit测试中找到了答案

在将基本测试功能和相关成员字段移动到基类之后,我发现我需要使成员字段受到保护,或者我需要拥有适当的getter和setter,以便我可以在继承的测试类中使用它们.这是一个例子:

public abstract class BaseTests {

    private Class classObj;      // or protected without getter/setter?

    protected void somethingHelper() {
        // Test something
    }

    protected void somethingElseHelper() {
        // Test something for classObj
    }

    public Class getClassObj() {
        return classObj;
    }

    public void setClassObj(Class other) {
        classObj = other;
    }
}

public class TestClass1 extends BaseTests {
    @Test
    public void testSomething() {
        somethingHelper();
    }
}

public class TestClass2 extends BaseTests {
    @Test
    public void testSomethingAndSomethingElse() { …
Run Code Online (Sandbox Code Playgroud)

java junit unit-testing jboss-arquillian

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

java.lang.AbstractMethodError: 在 UserType.nullSafeSet()

我有自定义enum值要保留在数据库中。为此,我已经实现了StringValuedEnumStringValuedEnumTypeStingValuedEnumReflect以及我的enum实现StringValuedEnum

当我使用手动管理的 JPA 运行我的代码时,一切正常,并且我的枚举值保留在 DB 中。但是,一旦我使用容器管理的 JPA(Wildfly 8.2)运行应用程序,刷新实体管理器时就会出现以下错误:

Caused by: java.lang.AbstractMethodError: yyy.xxx.util.StringValuedEnumType.nullSafeSet(Ljava/sql/PreparedStatement;Ljava/lang/Object;ILorg/hibernate/engine/spi/SessionImplementor;)V
at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:158) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2843) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3121) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1335) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.jboss.as.jpa.container.AbstractEntityManager.flush(AbstractEntityManager.java:457) [wildfly-jpa-8.2.1.Final.jar:8.2.1.Final]
at zzz.ejb.facades.EntityManagerFacade.createObject(EntityManagerFacade.java:2024) [zzz-ejb.jar:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_66]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_66]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_66]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_66]
at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309) …
Run Code Online (Sandbox Code Playgroud)

java enums hibernate jpa usertype

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

parallelStream 中的线程大小大于 CPU 内核

默认情况下,parallelStream 中的 commonPool 的大小应该是cpu_cores - 1.

但是,在我的应用程序中,它总是大于硬件cpu_cores

VisualVM 截图:

在此处输入图片说明

很困惑,我已经在互联网上搜索了一半,但找不到答案。

我的配置:

Runtime.getRuntime().availableProcessors()=12

java.util.concurrent.ForkJoinPool.common.parallelism=null(默认设置)

我的代码:

            final CountDownLatch countDownLatch = new CountDownLatch(tempList.size());
            tempList.parallelStream().forEach(om -> {
                countDownLatch.countDown();
                redisReBloomService.add(config.getRedisKey(), om.getChannelNo());
            });
            countDownLatch.await();
Run Code Online (Sandbox Code Playgroud)

另外,我尝试过自定义池设置,但它也不起作用-

ForkJoinPool forkJoinPool = new ForkJoinPool(3);  
forkJoinPool.submit(() -> {  
    tempList.parallelStream().forEach(om -> {
        countDownLatch.countDown();
        redisReBloomService.add(config.getRedisKey(), om.getChannelNo());
    }).get();
});
Run Code Online (Sandbox Code Playgroud)

一些信息:https : //docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html Java 8 并行流中的自定义线程池

java

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