小编Ash*_*yan的帖子

机器Epsilon

我正在寻找一种简单的方法来近似Java中的Epsilon:

float machEps = 1.0f;

do
    machEps /= 2.0f;
while ((float) (1.0 + (machEps / 2.0)) != 1.0);

System.out.println( machEps);
Run Code Online (Sandbox Code Playgroud)

返回:

1.1920929E-7
Run Code Online (Sandbox Code Playgroud)

但是,当我floatwhile循环中删除转换时:

float machEps = 1.0f;

do
   machEps /= 2.0f;
while ( (1.0 + (machEps / 2.0)) != 1.0);

System.out.println( machEps);
Run Code Online (Sandbox Code Playgroud)

我明白了:

2.220446E-16
Run Code Online (Sandbox Code Playgroud)

我不太清楚为什么会这样....我的猜测是在第二种情况下Java尝试machEps从a 扩展float到a double.但是,我不确定这是否是一个准确的陈述,或者我还有另外一个原因可以得到两个不同的答案.

java precision

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

使用Spring JDBC调试SQL查询

我正在使用Spring Framework,我正在进行测试驱动的开发.我得到一个例外,但我不完全确定为什么所以我想看看查询jdbc实际上是在运行什么.尝试的查询如下:

public OrderEntity addOrderEntity(OrderEntity orderEntity) {
    String query = "INSERT INTO ORDERS(ID,REVISION,CONTRACT_ID,PROJECT_ID,WORKSITE_ID,DROPZONE_ID,DESCRIPTION_ID,MANAGER_ID,DELIVERY_DATE,VOLUME) VALUES(?,?,?,?,?,?,?,?,?,?)";
    String id = (orderEntity.get_id() != null) ? orderEntity.get_id() : UUID.randomUUID().toString();
    jdbcTemplate.update(id,1,orderEntity.getContractNo(),orderEntity.getProjectID(),orderEntity.getWorksiteID(),orderEntity.getDropzoneID(),orderEntity.getDescriptionID(),orderEntity.getManagerID(),orderEntity.getDeliveryDate(),orderEntity.getVolume());

    return getOrderEntityById(id);
}
Run Code Online (Sandbox Code Playgroud)

那么,查看JDBC运行的查询或获取一些有用信息的最佳方法是什么?它目前抛出org/springframework/dao/QueryTimeoutException(我发现无限无益)所以我真的不知道会出现什么问题.

编辑:现在添加了log4j但仍未获得有用的查询.属性文件如下:

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5t] %-5p %c - %m%n
log4j.rootLogger=trace, stdout

log4j.logger.org.springframework.jdbc.core=DEBUG
log4j.logger.org.springframework.jdbc.core.StatementCreatorUtils=DEBUG
Run Code Online (Sandbox Code Playgroud)

java spring jdbc

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

Http Outbound Gateway从pojo有效负载发送Json请求

我正在尝试向REST端点发送一个简单的POST请求.我有一个简单的pojo,我想在有效载荷中发送为JSON.这是pojo(请注意我使用Spring与Grails集成,因此pojo/service在Groovy中):

class Person implements Serializable {
    String name
}
Run Code Online (Sandbox Code Playgroud)

这是我的门户:

public interface PersonGateway {
    Person savePerson(Person person)
}
Run Code Online (Sandbox Code Playgroud)

以下是布线的重要部分:

<int:channel id="requestChannel" />
<int:channel id="responseChannel" />
<int:header-enricher input-channel="requestChannel">
    <int:header name="Content-Type" value="application/json" />
</int:header-enricher>

<int:gateway id="PersonGateway"
             service-interface="com.example.PersonGateway"
             default-request-channel="requestChannel"
             default-reply-channel="responseChannel">
    <int:method name="savePerson" />
</int:gateway>
<int-http:outbound-gateway url="http://127.0.0.1:8000/person"
                           http-method="POST"
                           message-converters="jsonConverter"
                           expected-response-type="com.example.Person"
                           request-channel="requestChannel"
                           extract-request-payload="false"/>
Run Code Online (Sandbox Code Playgroud)

此POST请求永远不会到达该服务,但不会抛出任何异常.当我记录所有级别时,我得到的唯一一个看起来像线索的是:

2014-03-30 16:35:07,313 [main] DEBUG outbound.HttpRequestExecutingMessageHandler - 无法尝试转换消息有效负载类型.组件'org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler#0'没有显式的ConversionService引用,并且上下文中没有'integrationConversionService'bean.

除此之外它不会给我太多.我一整天都在尝试一些小事情,似乎无处可去.有人看到我错过了吗?谢谢!

java spring spring-integration

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

没有块处理的Spring Batch步骤

我有一个从数据库读取的作业步骤,并将输出写入平面文件并创建报告.
如果步骤失败,我希望它重新启动,从顶部处理全部.我不想将任何恢复纳入此步骤.
实现Spring Batch的最佳方法是什么,因此这个tasklet不会在进程中间执行任何块处理和触发恢复?

java processing spring spring-batch

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

如何知道在spring项目中加载bean的资源.

我是Spring框架的新手.我想知道加载bean时引用的xml文件列表.

通过编写ApplicationContextAware类,我可以查看bean列表:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/sample-testcontext.xml")

public class SampleClass implements ApplicationContextAware {
    @Autowired
    ApplicationContext applicationContext;

    @Test
    public void testMethod() {

        for (String beanName : applicationContext.getBeanDefinitionNames()) {
            System.out.println("BeanName " + beanName);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我想知道bean的加载配置文件.

说"sample-testcontext.xml"包含

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">


    <beans:import resource="classpath*:spring/sample-testOneMorecontext.xml"/>
</beans:beans>
Run Code Online (Sandbox Code Playgroud)

我想知道加载bean的文件名列表为"sample-testOneMorecontext.xml"和"sample-testcontext.xml".

java spring

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

语句关闭后不允许进行任何操作

我在No operations allowed after statement closed.尝试将值插入数据库的 Java 代码中收到带有签名的异常。错误签名表示我的 Statement 对象已关闭,我正在尝试在我的代码中再次使用它,但我很难理解为什么会发生这种情况,因为我没有关闭代码中任何地方的任何连接。

这是Java代码。

public class DataBaseAccessUtils {

    private static String jdbcUrl = 
            AppConfig.findMap("BXRequestTracker").get("jdbcUrl").toString();
    private static Connection connection = null;
    private static Statement statement = null;

    public static void insertHostname(String hostname, String rid, String fleet, String locale)
    {
        locale.toUpperCase();
        String sql = "UPDATE " + locale + "REQUESTTRACKER SET " + fleet 
                + "='" + hostname + "' WHERE RID='" + rid + "'";
        try {
            statement.execute(sql);
        }
        catch (SQLException e) …
Run Code Online (Sandbox Code Playgroud)

java mysql mysql-error-1064

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

Tomcat自定义错误处理程序未捕获Spring MVC Interceptor错误响应

在我的Spring MVC应用程序(servlet 3.0)中,我在web.xml中定义了一个自定义错误处理程序:

<error-page>
    <location>/error</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

映射到Controller:

@Controller
class CustomErrorController {

 @RequestMapping("error")
 public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {
...
 }
}
Run Code Online (Sandbox Code Playgroud)

这适用于大多数错误,例如404错误.但是,我还定义了一个Interceptor,如果没有经过身份验证的用户,它会返回403响应:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HttpSession httpSession = request.getSession();
    ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_FORBIDDEN);
    return false;
}
Run Code Online (Sandbox Code Playgroud)

自定义错误处理程序没有捕获403响应- 浏览器没有响应,错误代码为403.

我认为这是因为我在拦截器中做错了 - 我应该如何更改拦截器中的代码以便正常的错误处理工作?

java spring spring-mvc tomcat6 servlet-3.0

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

如何在EntityListeners中注入EntityManager

我需要在EntityListener类中注入EntityManager,以便我可以对它执行CRUD操作.

POJO:

@Entity
@EntityListner(AuditLogging.class)
class User
{
      //Getter / setter of properties
}
Run Code Online (Sandbox Code Playgroud)

AuditLogging(Listner类)

public class AuditInterceptor
{

  @PersistenceContext
  EntityManager entityManager;

  public void setEntityManager(EntityManager entityManager)
  {
    this.entityManager = entityManager;
  }

  @PrePersist
  public void prePersist(Object obj)
  {
     // Here I want to use ENTITY manager object so that I can perform CRUD operation
     // with prePersist coming object.

      entityManager.unwrap(Session.class).save(obj);

     // But I am getting NULL POINTER EXCEPTION for entity manager object 
   }
Run Code Online (Sandbox Code Playgroud)

}

JDBC-config.xml中

<bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" /> …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate spring-mvc spring-data-jpa

4
推荐指数
2
解决办法
4711
查看次数

为什么我的位图排序不比我的mergesort快得多?

我正在编写Peals编程,第一篇论文涉及在已知范围内对数字进行排序.作为一种智能解决方案,他们提供实现位图,将输入文件中的所有数字设置为位图中的一个,然后简单地迭代它以打印结果.假设这应该比更传统的排序算法(如quicksort或mergesort)快得多.

为了测试这个,我用Java编写了自己的位图排序.当我发现使用合并排序的Unix排序命令仍然快得多时,我并不感到惊讶.我把它归结为它用C语言编写的事实,并且可能由一些非常聪明的人高度优化.

所以,然后我用Java编写了自己的合并排序.令我惊讶的是,我的BitmapSort速度更快,但只是略有增加.使用非常大的输入文件(+ -800000整数),bitmapsort只会快30%左右.

这是我的位图排序和位图实现:

import java.util.Scanner;
import java.io.FileReader;
import java.io.File;

class BitmapSort {
    Scanner sc;

    BitmapSort() throws Exception {
        sc = new Scanner(new File("numbers.txt"));
    }

    void start() {
        BitMap map = new BitMap(3000000);
        while (sc.hasNextInt()) {
            map.set(sc.nextInt());
        }
        for (int i = 0; i < 3000000; i++) {
            if (map.isSet(i)) {
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new BitmapSort().start();
    }
}


class BitMap {

    byte[] bits;
    int size;


    BitMap(int n) {
        size = …
Run Code Online (Sandbox Code Playgroud)

java algorithm big-o mergesort bitmap

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

Spring MVC测试框架 - 不支持的媒体类型

我正在使用spring test mvc框架为控制器编写测试.我正在尝试测试一个post请求,它会产生JSON.实际代码正在运行但测试失败.

我得到错误状态预期200但得到415这意味着不支持的媒体类型.我检查网上的所有例子,似乎我的实现是正确的.请帮帮我.

MyTestcase TestStringPost()运行成功,但TestJSONPost失败.

我使用的是Spring 3.2

我的控制器

@Controller
public class HomeController {


@RequestMapping(value = "/v1/checkstringvalue", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody void testStringPost(@RequestBody String value) {
    logger.info("Welcome home! The client locale is {}.");
}

@RequestMapping(value = "/v1/checkjsonvalue", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody String testJSONPost(@RequestBody Map<String, String> userMap) {
    System.out.println("Inside test jsonpost controller");
    logger.info("Welcome home! The client locale is {}.");
    return "Success";
 }
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试控制器

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class HomeControllerTest {


@Autowired
private …
Run Code Online (Sandbox Code Playgroud)

java spring spring-test-mvc

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