小编bra*_*orm的帖子

在Java中为自定义检查异常编写JUnit测试用例?

我正在为我的类编写一个测试用例,其中包含抛出异常的方法(包括checked和runtime).我已尝试过此链接中建议的不同可能的测试方法..看起来它们似乎只适用于运行时异常.对于Checked异常,我需要执行try/catch/assert,如下面的代码所示.有没有替代尝试/ catch /断言/.你会注意到testmethod2() and testmethod2_1()显示编译错误,但testmethod2_2()没有显示使用try/catch的编译错误.

class MyException extends Exception {

    public MyException(String message){
        super(message);
    }
}


public class UsualStuff {

    public void method1(int i) throws IllegalArgumentException{
        if (i<0)
           throw new IllegalArgumentException("value cannot be negative");
        System.out.println("The positive value is " + i );
    }

    public void method2(int i) throws MyException {
        if (i<10)
            throw new MyException("value is less than 10");
        System.out.println("The value is "+ i);
    }

    }
Run Code Online (Sandbox Code Playgroud)

测试类:

import static org.junit.Assert.*;

import org.junit.Before; …
Run Code Online (Sandbox Code Playgroud)

java exception try-catch junit4 checked-exceptions

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

将列表复制回数组的时间复杂度是多少,反之亦然?

我想知道什么是时间复杂的大O(n)符号]的 ArrayListArray转换:

ArrayList assetTradingList = new ArrayList();
assetTradingList.add("Stocks trading");
assetTradingList.add("futures and option trading");
assetTradingList.add("electronic trading");
assetTradingList.add("forex trading");
assetTradingList.add("gold trading");
assetTradingList.add("fixed income bond trading");
String [] assetTradingArray = new String[assetTradingList.size()];
assetTradingArray.toArray(assetTradingArray);
Run Code Online (Sandbox Code Playgroud)

类似地,数组以下列方式列出的时间复杂度是多少:

方法1使用Arrays.asList:

String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed
    income", "futures", "options"};
List assetList = Arrays.asList(asset);
Run Code Online (Sandbox Code Playgroud)

方法2使用collections.addAll:

    List assetList = new ArrayList();
    String[] asset = {"equity", "stocks", "gold", "foreign exchange", "fixed
        income", "futures", "options"};
    Collections.addAll(assetList, asset);
Run Code Online (Sandbox Code Playgroud)

方法3 addAll:

     ArrayList …
Run Code Online (Sandbox Code Playgroud)

java arrays copy list arraylist

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

完美的平方算法 - 实现的解释

这个问题是在后一个后续这里:确定一个整数的平方根是一个整数的最快方法,什么是好的算法,以确定是否输入是一个完美的正方形?.

其中一个帖子有这个解决方案来查找给定的数字是否是perfect square:

public final static boolean isPerfectSquare(long n)
    {
        if (n < 0)
            return false;

        switch((int)(n & 0xF))
        {
        case 0: case 1: case 4: case 9:
            long tst = (long)Math.sqrt(n);
            return tst*tst == n;

        default:
            return false;
        }
    } 
Run Code Online (Sandbox Code Playgroud)

这是一个简洁的解决方案,完美无缺.但是没有详细解释它是如何工作的,或者更重要的是如何得出这个解决方案.我想如何推导出这个解决方案.

algorithm integer perfect-square square-root

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

使用User.objects.get_or_create()在django中提供无效的密码格式?

python manage.py shell

>>> from django.contrib.auth.models import User
>>> u=User.objects.get_or_create(username="testuser2",password="123")
>>> u
(<User: testuser2>, True)
Run Code Online (Sandbox Code Playgroud)

似乎它创造了User正确.但当我登录管理员时 http://127.0.0.1:8000/admin/auth/user/3/,我看到此消息的密码 Invalid password format or unknown hashing algorithm.

屏幕截图也附上了.为什么会这样,以及如何User objects从shell 创建.我实际上正在编写一个填充脚本,为我的项目创建多个用户?

在此输入图像描述

django django-admin django-users

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

django中SITE_ID设置的用途是什么?

当我在做平面教程时,我因SITE_ID没有设置而收到错误.我插入SITE_ID=1设置文件,一切正常.但我不知道这究竟意味着什么.

我读完了django docs.但我并不完全清楚它的用途.我什么时候会使用类似SITE_ID = 2的东西.

同样,我在代码中使用了以下代码片段而实际上并不知道它的作用:

current_site=Site.objects.get_current()
Run Code Online (Sandbox Code Playgroud)

我认为这与某些事情有关,SITE_ID但可能不是.

一些示例来说明哪里SITE_ID可能采用不同于1的值会有所帮助.

django django-sites

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

mapreduce作业的map阶段输出总是排序?

我对从Mapper获得的输出有点困惑.

例如,当我运行一个简单的wordcount程序时,使用此输入文本:

hello world
Hadoop programming
mapreduce wordcount
lets see if this works
12345678
hello world
mapreduce wordcount
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

12345678    1
Hadoop  1
hello   1
hello   1
if  1
lets    1
mapreduce   1
mapreduce   1
programming 1
see 1
this    1
wordcount   1
wordcount   1
works   1
world   1
world   1
Run Code Online (Sandbox Code Playgroud)

如您所见,mapper的输出已经排序.我根本没跑Reducer.但我发现在另一个项目中,mapper的输出没有排序.所以我对此完全清楚..

我的问题是:

  1. 映射器的输出总是排序吗?
  2. 排序阶段是否已经集成到映射器阶段,以便映射阶段的输出已经在中间数据中排序?
  3. 有没有办法从sort and shuffle阶段收集数据并在它进入Reducer之前保留它?减速器带有一个键和一个迭代列表.有没有办法,我可以保留这些数据吗?

hadoop mapreduce hadoop2

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

由于facebook范围,无法获得spring-social-showcase-boot工作?

我按照这里提供的说明在我的本地运行spring-social-showcase-boot.

这是我尝试使用Facebook进行身份验证时出现的错误.错误很明显,read_stream范围无效.

在此输入图像描述

但我无法确定示例中scope配置的位置spring-social-showcase-boot.

任何帮助解决这个问题将非常感激.

spring spring-social spring-social-facebook

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

如何在spring应用程序的servlet过滤器中自动装配bean?

我有一个spring-boot申请.

我的项目中没有ApplicationContext.xml或没有web.xml文件.我更喜欢避免使用它们并在Java代码中配置所有内容.

我已经阅读了以下有关servlet过滤器中bean注入的帖子.

  1. 如何在servlet过滤器中获取Spring bean?

  2. http://www.deadcoderising.com/2015-05-04-dependency-injection-into-filters-using-delegatingfilterproxy/

  3. servlet过滤器中的弹簧注入

读完之后,我开始使用了DelegatingFilterProxy.

我的问题是如何autowire将bean转换为过滤器并避免使用xml文件,尤其是DelegatingFilterProxy配置.

剪切的代码可以从github中托管的第二篇文章中获得.

public class AuditHandler {

    public void auditRequest(String appName, ServletRequest request) {
        System.out.println(appName + ": Received request from " + request.getRemoteAddr() );
    }
}

public class AuditFilter implements Filter {

    private final AuditHandler auditHandler;
    private String appName;

    public AuditFilter(AuditHandler auditHandler) {
        this.auditHandler = auditHandler;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException …
Run Code Online (Sandbox Code Playgroud)

spring dependency-injection spring-mvc autowired spring-boot

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

如何根据spring-rest-oauth中的oauth范围限制方法访问?

如何根据范围限制对方法的访问?例如,在下面的curl中,我获得了只有"read"范围的访问令牌.也就是说,用户已授权客户端应用程序具有对资源的只读访问权限

curl -X POST -vu clientapp:12334 http://localhost:9001/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read"

但Note客户端在auth服务器上注册了两个范围 - read and write.

现在,假设资源服务器有两个端点

/users/update - 此端点是POST请求.只有在用户批准"写入"范围时才应该公开.

users/getInfo - 此端点是GET请求.这应该公开,因为用户已授予具有读取范围的客户端访问权限

我的问题是我们如何在方法级别控制这些访问

@RestController
@RequestMapping("/users")
public class UserController {

    private static final String template = "Hello, %s!";

    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/update",  method = RequestMethod.POST)
    public UserProfile update(@AuthenticationPrincipal User user) {

          ///update userProfile 
         return userProfile;
    }

      @RequestMapping("/getInfo",  method = RequestMethod.GET)
    public UserProfile getProfile(@AuthenticationPrincipal User user) {

            //get the userData from database
            return userProfile;
    } …
Run Code Online (Sandbox Code Playgroud)

spring spring-security spring-security-oauth2

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

如何在Java配置中使用delegatingFilterproxy?

DelegatingFilterProxy有两个我可以在我的应用程序中使用的构造函数

new DelegatingFilterProxy(String beanName);
new DelegatingFilterProxy(Filter delegate);
Run Code Online (Sandbox Code Playgroud)

在我webappIntializer,我有以下.(请参阅下面的完整代码).

servletContext.addFilter("counterMetricsFilter", new DelegatingFilterProxy("counterMetricsFilter").addMappingForUrlPatterns(null,
                false, MAPPING_URL);
Run Code Online (Sandbox Code Playgroud)

我不确定DelegatingFilterProxy我的情况是否正常运作.

Controller

@Controller
@RequestMapping("/counter")
public class CounterController {

@Autowired
CounterManager manager;

 @RequestMapping(value = "/counterMetrics", method = RequestMethod.GET)
    @ResponseBody
    public Map getFeatureStatus(final HttpServletResponse response) {
        System.out.println("returning feautre status");
        return manager.getQueryCounts();
    }
}
Run Code Online (Sandbox Code Playgroud)

Manager

@Service
public class CounterManager {

private Map<String,Integer> queryCounts =
            new ConcurrentHashMap<String,Integer>(1000);

int threshold;
long timestamp;

 @Autowired
  public CounterManager(@Value("${healthThreshold: 10}")
                                 int threshold) {
      this.threshold = threshold * MEGABYTES;
      this.timestamp = System.currentTimeMillis();
  } …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc servlet-filters

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