Java 类org.apache.commons.collections.map.HashedMap 实例源码

项目:movie-recommender    文件:SparkModule.java   
@Provides
JavaInputDStream<ConsumerRecord<String, RawRating>> providesKafkaInputStream(JavaStreamingContext streamingContext) {
    Map<String, Object> kafkaParams = new HashedMap();
    kafkaParams.put("bootstrap.servers", "localhost:9092");
    kafkaParams.put("key.deserializer", StringDeserializer.class);
    kafkaParams.put("value.deserializer", JsonDeserializer.class);
    kafkaParams.put("serializedClass", RawRating.class);
    kafkaParams.put("group.id", "rating_stream");
    kafkaParams.put("auto.offset.reset", "latest");
    kafkaParams.put("enable.auto.commit", false);
    Collection<String> topics = Arrays.asList("topicA", "topicB");

    return KafkaUtils.createDirectStream(
            streamingContext,
            LocationStrategies.PreferConsistent(),
            ConsumerStrategies.<String, RawRating>Subscribe(topics, kafkaParams)
    );
}
项目:LoginCrawler    文件:JinShanYouXiProcessor.java   
@Override
public void setLoginEntity(LoginEntity loginEntity) {
    Map<String, Object> params = new HashedMap();
    params.put("user", "fc7kj");
    params.put("pwd", MD5Utils.digest("zhang520"));
    params.put("service", "http://i.wan.liebao.cn/login?go=http://wan.liebao.cn/game_frame/play_1087.php?sid=22&supplier_id=2");
    params.put("rm", "1");
    params.put("cn", "a6742619ae9d91bfb87b0f9507c8d0ad");
    loginEntity.setParams(params);
    loginEntity.setLoginUrl("https://login.ijinshan.com/webgame/w/loginpage.html");
    loginEntity.setActionUrl("https://login.ijinshan.com/login");
    loginEntity.setCodeUrl("https://login.ijinshan.com/imgCode?_dc=" + (System.currentTimeMillis()) + "&cn=a6742619ae9d91bfb87b0f9507c8d0ad");
    loginEntity.setCharset("UTF-8");
    loginEntity.setUnEscape(true);
    loginEntity.setMark("用户名或密码错误;验证错误;验证码错误;登录失败;");
}
项目:LoginCrawler    文件:JinShanProcessor.java   
@Override
public void setLoginEntity(LoginEntity loginEntity) {
    Map<String, Object> params = new HashedMap();
    params.put("user", "fc7kj");
    params.put("pwd", MD5Utils.digest("zhang520"));
    params.put("service", "");
    params.put("rm", "1");
    params.put("cn", "b06aa38e7641826933720e37f481ac7c");
    loginEntity.setParams(params);
    loginEntity.setLoginUrl("https://login.ijinshan.com/login.html");
    loginEntity.setActionUrl("https://login.ijinshan.com/login");
    loginEntity.setCodeUrl("https://login.ijinshan.com/imgCode?_dc=" + (System.currentTimeMillis()) + "&cn=b06aa38e7641826933720e37f481ac7c");
    loginEntity.setCharset("UTF-8");
    loginEntity.setUnEscape(true);
    loginEntity.setMark("用户名或密码错误;验证错误;验证码错误;登录失败;");
    loginEntity.setActionUrl("https://login.ijinshan.com/login");
}
项目:cjs_ssms    文件:SelectController.java   
/**
 * 数据表grid查询 It's not good enough
 * @param pageIndex
 * @param pageSize
 * @param paramsMap 给criteria添加参数使用
 * @return
 */
private Map<String, Object> getGrids(int pageIndex, int pageSize, HashMap<String, String> paramsMap) {
  PageRowBounds rowBounds = new PageRowBounds(pageIndex+1, pageSize);
  SqlSession sqlSession = MybatisHelper.getSqlSession();
  Mapper mapper = (Mapper) sqlSession.getMapper(UUserMapper.class);
  Example example = new Example(UUser.class);
  Example.Criteria criteria = example.createCriteria();
  /*criteria增加条件...*/
  List<UUser> users = (List<UUser>) mapper.selectByExampleAndRowBounds(example, rowBounds);

  /*4.构造适合miniui_grid展示的map*/
  Map<String, Object> map_grid = new HashedMap();
  map_grid.put("total", users.size());
  map_grid.put("data", users);

  return map_grid;
}
项目:cjs_ssms    文件:UserFrontController.java   
/**
 * 注册
 * JavaBean: User这种的bean会自动返回给前端
 *
 * @param user
 * @param model
 * @param response
 */
@RequestMapping("/register")
public void register(UUser user, Model model, HttpServletResponse response) {
  Map<String, Object> remap = new HashedMap();
  try {
    boolean b = userFService.registerUser(user);
    if (b) {
      log.info("注册普通用户" + user.getUsername() + "成功。");
      remap.put("msg", "恭喜您," + user.getUsername() + "注册成功。");
      HttpRespUtil.respJson(StatusEnum.SUCCESS, remap, response);
    } else {
      remap.put("msg", "用户名已存在。");
      HttpRespUtil.respJson(StatusEnum.SUCCESS, remap, response);
    }

  } catch (Exception e) {
    log.debug("注册普通用户" + user.getUsername() + "异常");
    remap.put("msg","注册普通用户异常");
    HttpRespUtil.respJson(StatusEnum.FAIL, remap, response);
    e.printStackTrace();
  }
}
项目:blueweave    文件:TimeseriesClassifierNetwork.java   
private  Map<Integer,Map<String,Object>> makeFeatureModelForTesting(DateSeriesDataSetModel ds) {

        Map<Integer,Map<String,Object>> items = new HashMap<>();

        //make a copy
        INDArray features = ds.getDataSet().copy().getFeatureMatrix();

        try {
            List<List<Double>> rows = NDArrayUtils.makeRowsFromNDArray(features,6);
            for (int i = 0; i < rows.size(); i++) {
                List<Double> row = rows.get(i);
                Map<String,Object> itemModel = new HashedMap();
                itemModel.put("seriesNumber",i);
                itemModel.put("seriesData",row);
                itemModel.put("seriesName", ds.getSeriesNames().get(i));
                items.put(i,itemModel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return items;
    }
项目:cosmic    文件:HostResponseTest.java   
@Test
public void testSetDetailsWithRootCredentials() {

    final HostResponse hostResponse = new HostResponse();
    final Map details = new HashMap<>();

    details.put(VALID_KEY, VALID_VALUE);
    details.put("username", "test");
    details.put("password", "password");

    final Map expectedDetails = new HashedMap();
    expectedDetails.put(VALID_KEY, VALID_VALUE);

    hostResponse.setDetails(details);
    final Map actualDetails = hostResponse.getDetails();

    assertTrue(details != actualDetails);
    assertEquals(expectedDetails, actualDetails);
}
项目:cosmic    文件:HostResponseTest.java   
@Test
public void testSetDetailsWithoutRootCredentials() {

    final HostResponse hostResponse = new HostResponse();
    final Map details = new HashMap<>();

    details.put(VALID_KEY, VALID_VALUE);

    final Map expectedDetails = new HashedMap();
    expectedDetails.put(VALID_KEY, VALID_VALUE);

    hostResponse.setDetails(details);
    final Map actualDetails = hostResponse.getDetails();

    assertTrue(details != actualDetails);
    assertEquals(expectedDetails, actualDetails);
}
项目:geeCommerce-Java-Shop-Software-and-PIM    文件:ContentController.java   
@Request("page/{id}")
public Result getPage(@PathParam("id") Id id, @Context HttpServletRequest request,
    @Context HttpServletResponse response) {
    Content content = contents.findById(Content.class, id);

    app.setViewPath("page/content/view_" + id.str());
    app.setActionURI(request.getRequestURI());


    Map<String, Object> params = new HashedMap();
    if (content.getPreviewProductId() != null) {
        params.put("product", productService.getProduct(content.getPreviewProductId()));
    }

    Result result = freemarkerTemplateStream(content.getTemplate(), params, "3h");
    if (content.getPreviewProductId() != null) {
        result.bind("product", productService.getProduct(content.getPreviewProductId()));
    }
    return result;
}
项目:geeCommerce-Java-Shop-Software-and-PIM    文件:ContentController.java   
@Request("product/{id}")
public Result getProductPage(@PathParam("id") Id id, @Context HttpServletRequest request,
                      @Context HttpServletResponse response) {

    Product product = productService.getProduct(id);
    Content content = contents.findById(Content.class, product.getTemplateId());

    app.setViewPath("page/content/view_" + content.getId().str() + "_" + product.getId());
    app.setActionURI(request.getRequestURI());

    Map<String, Object> params = new HashedMap();
    params.put("product", product);

    Result result = freemarkerTemplateStream(content.getTemplate(),params, "3h");
    result.bind("product", product);
    return result;
}
项目:oncokb    文件:SummaryUtils.java   
private static String alterationsToString(Collection<Alteration> alterations) {
    Map<Gene, Set<String>> mapGeneVariants = new HashedMap();
    for (Alteration alteration : alterations) {
        Gene gene = alteration.getGene();
        Set<String> variants = mapGeneVariants.get(gene);
        if (variants == null) {
            variants = new HashSet<>();
            mapGeneVariants.put(gene, variants);
        }
        variants.add(alteration.getName());
    }

    List<String> list = new ArrayList<>();
    for (Map.Entry<Gene, Set<String>> entry : mapGeneVariants.entrySet()) {
        for (String variant : entry.getValue()) {
            list.add(getGeneMutationNameInVariantSummary(alterations.iterator().next().getGene(), variant));
        }
    }

    String ret = MainUtils.listToString(list, " or ");

    return ret;
}
项目:sakai    文件:GbGradebookData.java   
private Map<String, Object> serializeSettings() {
    final Map<String, Object> result = new HashedMap();

    result.put("isCourseLetterGradeDisplayed", settings.isCourseLetterGradeDisplayed());
    result.put("isCourseAverageDisplayed", settings.isCourseAverageDisplayed());
    result.put("isCoursePointsDisplayed", settings.isCoursePointsDisplayed());
    result.put("isPointsGradeEntry", GradingType.valueOf(settings.getGradeType()).equals(GradingType.POINTS));
    result.put("isPercentageGradeEntry", GradingType.valueOf(settings.getGradeType()).equals(GradingType.PERCENTAGE));
    result.put("isCategoriesEnabled", GbCategoryType.valueOf(settings.getCategoryType()) != GbCategoryType.NO_CATEGORY);
    result.put("isCategoryTypeWeighted", GbCategoryType.valueOf(settings.getCategoryType()) == GbCategoryType.WEIGHTED_CATEGORY);
    result.put("isStudentOrderedByLastName", uiSettings.getNameSortOrder() == GbStudentNameSortOrder.LAST_NAME);
    result.put("isStudentOrderedByFirstName", uiSettings.getNameSortOrder() == GbStudentNameSortOrder.FIRST_NAME);
    result.put("isGroupedByCategory", uiSettings.isGroupedByCategory());
    result.put("isCourseGradeReleased", settings.isCourseGradeDisplayed());
    result.put("showPoints", uiSettings.getShowPoints());
    result.put("instructor", isInstructor());
    result.put("isStudentNumberVisible", this.isStudentNumberVisible);

    return result;
}
项目:spring-auto-restdocs    文件:HumanReadableConstraintResolverTest.java   
@Test
public void testHumanReadable() {
    // setup
    Map<String, Object> configuration = new HashedMap();
    configuration.put("primitive", 1);
    configuration.put("wrapper", 1);
    configuration.put("object", new CustomObj("Peter"));
    configuration.put("array", new Object[]{"value1", "value2"});
    configuration.put("class", CustomConstraint.class);
    configuration.put("groups", new Class<?>[]{Update.class});
    configuration.put("payload", new Class<?>[0]);
    Constraint constraint = new Constraint("Custom", configuration);

    when(delegate.resolveForProperty("prop", this.getClass()))
            .thenReturn(singletonList(constraint));
    when(delegate.resolveForParameter(any(MethodParameter.class)))
            .thenReturn(singletonList(constraint));

    List<Constraint> constraints = resolver.resolveForProperty("prop", this.getClass());
    assertConstraints(constraints);

    constraints = resolver.resolveForParameter(Mockito.mock(MethodParameter.class));
    assertConstraints(constraints);
}
项目:wikit    文件:EspmClassify.java   
/**
 * fold: 表示十折交叉验证的第几个
 */
public void doFullTest(File rawCorpusDir, File miningDir, boolean raw, boolean esa, boolean espm, boolean espmesa, int fold) {

    Map<String, Double> results = new HashedMap();

    StringBuilder sb = new StringBuilder();
    if (raw) {
        runTask("BoW", rawCorpusDir, miningDir, fold, MyPipe.Type.PURE_BOW);
    }

    if (esa) {
        runTask("ESA", rawCorpusDir, miningDir, fold, MyPipe.Type.PURE_ESA);
        runTask("BoW+ESA", rawCorpusDir, miningDir, fold, MyPipe.Type.BOW_ESA);
    }

    if (espm) {
        runTask("ESPM", rawCorpusDir, miningDir, fold, MyPipe.Type.PURE_ESPM);
        runTask("BoW+ESPM", rawCorpusDir, miningDir, fold, MyPipe.Type.BOW_ESPM);
    }


    if (espmesa) {
        runTask("ESPM+ESA", rawCorpusDir, miningDir, fold, MyPipe.Type.PURE_ESPM_ESA);
        runTask("BoW+ESPM+ESA", rawCorpusDir, miningDir, fold, MyPipe.Type.BOW_ESPM_ESA);
    }
}
项目:astor    文件:GramProcessor.java   
@Deprecated
public Map<String, NGrams> calculateByPackage(List<CtType<?>> all) throws JSAPException {

    Map<String, NGrams> result = new HashedMap();
    IngredientProcessor ingp = new IngredientProcessor<>(ingredientProcessor);
    int allElements = 0;

    for (CtType<?> ctType : all) {
        NGrams ns = new NGrams();
        CtPackage parent = (CtPackage) ctType.getParent(CtPackage.class);
        if (!result.containsKey(parent.getQualifiedName())) {
            allElements += getNGramsFromCodeElements(parent, ns, ingp);
            result.put(parent.getQualifiedName(), ns);
        }
    }
    logger.debug("allElements " + allElements);
    return result;
}
项目:sakai    文件:GbGradebookData.java   
private Map<String, Object> serializeSettings() {
    final Map<String, Object> result = new HashedMap();

    result.put("isCourseLetterGradeDisplayed", settings.isCourseLetterGradeDisplayed());
    result.put("isCourseAverageDisplayed", settings.isCourseAverageDisplayed());
    result.put("isCoursePointsDisplayed", settings.isCoursePointsDisplayed());
    result.put("isPointsGradeEntry", GradingType.valueOf(settings.getGradeType()).equals(GradingType.POINTS));
    result.put("isPercentageGradeEntry", GradingType.valueOf(settings.getGradeType()).equals(GradingType.PERCENTAGE));
    result.put("isCategoriesEnabled", GbCategoryType.valueOf(settings.getCategoryType()) != GbCategoryType.NO_CATEGORY);
    result.put("isCategoryTypeWeighted", GbCategoryType.valueOf(settings.getCategoryType()) == GbCategoryType.WEIGHTED_CATEGORY);
    result.put("isStudentOrderedByLastName", uiSettings.getNameSortOrder() == GbStudentNameSortOrder.LAST_NAME);
    result.put("isStudentOrderedByFirstName", uiSettings.getNameSortOrder() == GbStudentNameSortOrder.FIRST_NAME);
    result.put("isGroupedByCategory", uiSettings.isGroupedByCategory());
    result.put("isCourseGradeReleased", settings.isCourseGradeDisplayed());
    result.put("showPoints", uiSettings.getShowPoints());
    result.put("instructor", isInstructor());
    result.put("isStudentNumberVisible", this.isStudentNumberVisible);

    return result;
}
项目:gocd    文件:AuthorizationMessageConverterV1.java   
private List<Map<String, Object>> getRoleConfigs(List<PluginRoleConfig> roleConfigs) {
    List<Map<String, Object>> configs = new ArrayList<>();

    if (roleConfigs == null) {
        return configs;
    }

    for (PluginRoleConfig roleConfig : roleConfigs) {
        Map<String, Object> config = new HashedMap();
        config.put("name", roleConfig.getName().toString());
        config.put("auth_config_id", roleConfig.getAuthConfigId());
        config.put("configuration", roleConfig.getConfigurationAsMap(true));
        configs.add(config);
    }
    return configs;
}
项目:cloudstack    文件:HostResponseTest.java   
@Test
public void testSetDetailsWithRootCredentials() {

    final HostResponse hostResponse = new HostResponse();
    final Map details = new HashMap<>();

    details.put(VALID_KEY, VALID_VALUE);
    details.put("username", "test");
    details.put("password", "password");

    final Map expectedDetails = new HashedMap();
    expectedDetails.put(VALID_KEY, VALID_VALUE);

    hostResponse.setDetails(details);
    final Map actualDetails = hostResponse.getDetails();

    assertTrue(details != actualDetails);
    assertEquals(expectedDetails, actualDetails);

}
项目:Crawer    文件:Parser.java   
/**
     * 抽取主方法:抽取分为这样几个步骤
     * 1、定位抽取,,,,这个部分主要就是根据抽取规则得到一个大概的字段数据
     * 比如,我要抽取标题:Element el = doc.select(PropertyUtil.get("title"));
     * 
     * 2、字段过滤
     * 比如抽取出来的title:<b>我爱你中国【特价书籍】</b>
     * 过滤之后应该得到:我爱你中国特价书籍 或者 我爱你中国【特价书籍】
     * 
     * 3、数据持久化
     * 调用集成接口
     * 
     */
    public void parser(String filepath) throws ExtractException{
        //抽取
        Map<String, String> map = new HashedMap();
        try {
            map = getElementsInfo(filepath);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
//      //没有抓到书名或者isbn的,都不再进行后续操作
        /*if(map.get(PropertyUtil.BOOKNAME) == null || map.get(PropertyUtil.ISBN) == null){
            throw new ExtractException();
        }*/
        //过滤,精确抽取
        BookDetail bookDetail = fieldFilter(map);
        if(bookDetail.getBookName() == null || bookDetail.getIsbn() == null || bookDetail.getBookName() == "" || bookDetail.getIsbn() == ""){
            throw new ExtractException();
        }
        //数据持久化

        getIntegratedDao().integrated(bookDetail);
    }
项目:beaker-notebook-archive    文件:EvaluatorManagerTest.java   
@Test
public void setShellOptions_callEvaluatorToStartWorker() throws Exception {
  evaluator.clearStartWorkerFlag();
  //when
  evaluatorManager.setShellOptions(new KernelParameters(new HashedMap()));
  //then
  Assertions.assertThat(evaluator.isCallStartWorker()).isTrue();
}
项目:esup-sgc    文件:ManagerCardController.java   
@ModelAttribute("userPrefs")
public HashedMap getuserPrefs() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String eppn = auth.getName();
    HashedMap mapPrefs= new HashedMap();
    mapPrefs.put("editable", preferencesService.getPrefValue(eppn, "EDITABLE"));
    mapPrefs.put("ownOrFreeCard", preferencesService.getPrefValue(eppn, "OWNORFREECARD"));
    return mapPrefs;
}
项目:Automekanik    文件:ShikoKonsumatoret.java   
private void raporti(){
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                JasperReport jreport = JasperCompileManager.compileReport(raporti);
                JasperPrint jprint = JasperFillManager.fillReport(jreport, new HashedMap(), conn);
                JasperViewer.viewReport(jprint, false);
                conn.close();
            }catch (Exception ex){ex.printStackTrace();}
        }
    });
    btnRaport.setOnAction(e -> t.start());
}
项目:alfresco-remote-api    文件:CMISHttpServletRequest.java   
@SuppressWarnings("unchecked")
@Override
public Map getParameterMap()
{
    Map map = httpReq.getParameterMap();
    Map ret = new HashedMap(map);
    if(networkId != null)
    {
        ret.put(Constants.PARAM_REPOSITORY_ID, new String[] { networkId });
    }
    return ret;
}
项目:UtilsMaven    文件:TestBeanToMap.java   
@Test
public void test3() throws Exception {
    Map<String, Object> map = new HashedMap();
    map.put("name", "nn");
    map.put("sex", 12);
    map.put("error", "error");
    map.put("birth", new Date());
    User user = CommonUtils.toBean(map, User.class);
    System.out.println(user);
}
项目:LoginCrawler    文件:ZhiHuProcessor.java   
@Override
public void setLoginEntity(LoginEntity loginEntity) {
    Map<String, Object> params = new HashedMap();
    params.put("phone_num", "15918726361");
    params.put("password", "2011626504");
    loginEntity.setParams(params);
    loginEntity.setLoginUrl("https://www.zhihu.com/");
    loginEntity.setActionUrl("https://www.zhihu.com/login/phone_num");
    loginEntity.setCharset("UTF-8");
    loginEntity.setUnEscape(true);
    loginEntity.setMark("账号或密码错误;不存在;密码错误;登录过于频繁;");
}
项目:LoginCrawler    文件:RenRenWangProcessor.java   
@Override
public void setLoginEntity(LoginEntity loginEntity) {
    Map<String, Object> params = new HashedMap();
    params.put("email", "15918726361");
    params.put("password", "2011626504");
    loginEntity.setParams(params);
    loginEntity.setLoginUrl("http://www.renren.com/");
    loginEntity.setActionUrl("http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2017202025800");
    loginEntity.setCharset("UTF-8");
    loginEntity.setCodeUrl("http://icode.renren.com/getcode.do?t=web_login&rnd=Math.random()");
    loginEntity.setMark("您的用户名和密码不匹配;验证码不正确;");
}
项目:melon    文件:IndexController.java   
/***
 * 欢迎页面
 * @param request
 * @return json
 */
@ResponseBody
@RequestMapping(value = {"", "/index"})
public Object index(HttpServletRequest request) {
    log.error("hello world");
    HashedMap map = new HashedMap();
    map.put("hashCode", this.hashCode());
    map.put("thread", Thread.currentThread().getName());
    map.put("msg", "welcome message");
    Person person = new Person("xjt", 2, 22);
    map.put("author", person);
    return map;
}
项目:herddb    文件:Transaction.java   
public LockHandle lookupLock(String tableName, Bytes key) {
    HashedMap ll = locks.get(tableName);
    if (ll == null || ll.isEmpty()) {
        return null;
    }
    return (LockHandle) ll.get(key);
}
项目:Fitoscanner_Backend    文件:EspecieService.java   
@Transactional
@Deprecated
public void saveWith4Images(String name, Boolean isCrop, Boolean isPlague,
        String scientificName, String desc, String im1, String base64_1,
        String im2, String base64_2, String im3, String base64_3,
        String im4, String base64_4) {

    HashedMap images = new HashedMap(); 
    images.put(im1, base64_1);
    images.put(im2, base64_2);
    images.put(im3, base64_3);
    images.put(im3, base64_4);

    saveWithNImages(name, isCrop, isPlague, scientificName, desc, images);
}
项目:Fitoscanner_Backend    文件:MuestraRest.java   
@POST
@Path("/save/{quant}")
@Consumes("application/x-www-form-urlencoded")
public Response saveSample(@PathParam("quant")Integer quantity  ,
        MultivaluedMap<String, String> FormValues,
        @FormParam("date") String date,
        @FormParam("isAnon")Boolean isAnon,
        @FormParam("imei")String imei,
        @FormParam("lat")String lat,
        @FormParam("lon")String lon,
        @FormParam("images_hash")String hash) {
    DateTime parsedDate = DateHelper.formatStringDate(date);
    System.out.println("Se intentara guardar muestra de "+quantity+ " imagenes");

    HashedMap imagenes = new HashedMap();
    int total = quantity;
    while(total >0){
        if(!FormValues.containsKey("sample_image_"+total+"_base64")){
            //http 417 Expectation failed
            return Response.status(417)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("There are sample images missing","*")
                    .build();
        }

        //Armar mapa titulo =>base64
        imagenes.put(FormValues.getFirst("sample_image_"+total+"_title"), FormValues.getFirst("sample_image_"+total+"_base64"));
        total--;
    }
    System.out.println("Imagenes obtenidas: "+ imagenes);

    muestraService.saveSample(parsedDate,isAnon,imei,lat,lon,
            FormValues.getFirst("sample_name"), imagenes,hash);
    return Response.ok().header("Access-Control-Allow-Origin", "*").build();
}
项目:yacop    文件:DockerEngine.java   
public ContainerLaunchContext buildContainerContext(Map<String, LocalResource> localResources, YacopConfig yacopConfig) {
  ContainerLaunchContext ctx = null;
  try {
    //env
    Map<String, String> env = new HashedMap();
    if (yacopConfig.getEngineType().equals("DOCKER")) {
      env.put("YARN_CONTAINER_RUNTIME_TYPE", "docker");
      env.put("YARN_CONTAINER_RUNTIME_DOCKER_IMAGE", yacopConfig.getEngineImage());
      if (yacopConfig.getVolumeConfigs() != null)
        env.put("YARN_CONTAINER_RUNTIME_DOCKER_LOCAL_RESOURCE_MOUNTS", getMountVolumePairList(yacopConfig));
      if (yacopConfig.getNetworkConfig() != null)
        env.put("YARN_CONTAINER_RUNTIME_DOCKER_CONTAINER_NETWORK", yacopConfig.getNetworkConfig().getName());
    }
    List<String> commands = new ArrayList<>();
    //cmd
    Vector<CharSequence> vargs = new Vector<>(5);
    vargs.add("(" + yacopConfig.getCmd() + ")");
    vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout");
    vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stderr");
    StringBuilder command = new StringBuilder();
    for (CharSequence str : vargs) {
      command.append(str).append(" ");
    }
    commands.add(command.toString());
    //tokens
    Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials();
    DataOutputBuffer dob = new DataOutputBuffer();
    credentials.writeTokenStorageToStream(dob);
    ByteBuffer allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
    //ctx
    ctx = ContainerLaunchContext.newInstance(
            localResources, env, commands, null, allTokens.duplicate(), null
    );
  } catch (IOException e) {
    e.printStackTrace();
  }
  return ctx;
}
项目:cosmic    文件:ResourceMetaDataManagerTest.java   
public void testAddResourceDetails() throws ResourceAllocationException {

        doReturn(1L).when(_taggedResourceMgr).getResourceId("1", ResourceTag.ResourceObjectType.Volume);
        //           _volumeDetailDao.removeDetails(id, key);

        doNothing().when(_volumeDetailDao).removeDetail(anyLong(), anyString());
        doNothing().when(_nicDetailDao).removeDetail(anyLong(), anyString());
        final Map<String, String> map = new HashedMap();
        map.put("key", "value");
        _resourceMetaDataMgr.addResourceMetaData("1", ResourceTag.ResourceObjectType.Volume, map, true);
    }
项目:fksm    文件:BaseRedisWindowBolt.java   
/**
 *
 * @param key
 * @param start
 * @param end
 */
protected Map<String, String> getRedisValueByScoreRange(String key, Long start, Long end){
    Set<Tuple> data = redisUtil.zrangeByScoreWithScores(key, start.toString(), end.toString());
    //score count
    Map<String, String> res = new HashedMap(data.size());
    Iterator<Tuple> datas = data.iterator();
    while (datas.hasNext()){
        Tuple d = datas.next();
        String v = d.getElement();
        String k = Double.toString(d.getScore());
        res.put(k, v);
    }
    return res;
}
项目:OnlineCourse    文件:RootControllerTest.java   
/**
 * 修改密码,用户密码错误,应该返回403
 */
@Test
public void shouldReturn403WhenChangePwd() {
    url = "http://localhost:"+port+"/user";

    //创建body
    Map<String,Object> body = new HashMap();
    body.put("old","123");
    body.put("new","321");

    //创建headers
    MultiValueMap<String,String> requestHeaders = new LinkedMultiValueMap<>();
    //设置headers
    requestHeaders.add("Content-Type","application/json; charset=UTF-8");
    //头部登录信息
    requestHeaders.add("Authentication","123asd");

    //设置http请求数据
    HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

    //解码返回的用户信息
    Map<String,Object> auth = new HashedMap();
    auth.put("id",1);
    //Mock jwt,解码json web token
    when(jwt.decode(any())).thenReturn(auth);

    //查找用户,返回用户信息
    User user = new User();
    user.setPassword("abc");    //密码错误
    //Mock userService,获取用户信息
    when(userService.findByID(1)).thenReturn(user);

    //发起请求
    ResponseEntity response = this.restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class );

    //返回状态码应该等于403
    assertEquals(403,response.getStatusCode().value());
}
项目:OnlineCourse    文件:RootControllerTest.java   
/**
 * 修改密码,修改失败,应该返回500
 */
@Test
public void shouldReturn500WhenChangePwd() {
    url = "http://localhost:"+port+"/user";

    //创建body
    Map<String,Object> body = new HashMap();
    body.put("old","123");
    body.put("new","321");

    //创建headers
    MultiValueMap<String,String> requestHeaders = new LinkedMultiValueMap<>();
    //设置headers
    requestHeaders.add("Content-Type","application/json; charset=UTF-8");
    //头部登录信息
    requestHeaders.add("Authentication","123asd");

    //设置http请求数据
    HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

    //解码返回的用户信息
    Map<String,Object> auth = new HashedMap();
    auth.put("id",1);
    //Mock jwt,解码json web token
    when(jwt.decode(any())).thenReturn(auth);

    //查找用户,返回用户信息
    User user = new User();
    user.setPassword("123");
    //Mock userService,获取用户信息
    when(userService.findByID(1)).thenReturn(user);
    when(userService.update(any())).thenReturn(0);  //更新失败

    //发起请求
    ResponseEntity response = this.restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class );

    //返回状态码应该等于500
    assertEquals(500,response.getStatusCode().value());
}
项目:OnlineCourse    文件:RootControllerTest.java   
/**
 * 永久封号,登录用户不是管理员,应该返回403
 */
@Test
public void shouldReturn403WhenDeleteUser() {
    url = "http://localhost:"+port+"/user/12";

    //创建body
    Map<String,Object> body = new HashMap();

    //创建headers
    MultiValueMap<String,String> requestHeaders = new LinkedMultiValueMap<>();
    //设置headers
    requestHeaders.add("Content-Type","application/json; charset=UTF-8");
    //头部登录信息
    requestHeaders.add("Authentication","123asd");

    //设置http请求数据
    HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

    //解码返回的用户信息
    Map<String,Object> auth = new HashedMap();
    auth.put("userStatus","teacher");   //不是管理员
    //Mock jwt,解码json web token
    when(jwt.decode(any())).thenReturn(auth);

    //发起请求
    ResponseEntity response = this.restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class );

    //返回状态码应该等于403
    assertEquals(403,response.getStatusCode().value());
}
项目:OnlineCourse    文件:RootControllerTest.java   
/**
 * 永久封号,登录用户是管理员,封号用户不存在,应该返回404
 */
@Test
public void shouldReturn404WhenDeleteUser() {
    url = "http://localhost:"+port+"/user/12";

    //创建body
    Map<String,Object> body = new HashMap();

    //创建headers
    MultiValueMap<String,String> requestHeaders = new LinkedMultiValueMap<>();
    //设置headers
    requestHeaders.add("Content-Type","application/json; charset=UTF-8");
    //头部登录信息
    requestHeaders.add("Authentication","123asd");

    //设置http请求数据
    HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

    //解码返回的用户信息
    Map<String,Object> auth = new HashedMap();
    auth.put("userStatus","admin");   //是管理员
    //Mock jwt,解码json web token
    when(jwt.decode(any())).thenReturn(auth);

    //Mock userService,获取用户信息
    when(userService.findByID(1)).thenReturn(null); //用户不存在

    //发起请求
    ResponseEntity response = this.restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class );

    //返回状态码应该等于404
    assertEquals(404,response.getStatusCode().value());
}
项目:OnlineCourse    文件:RootControllerTest.java   
/**
 * 永久封号,封号失败,应该返回500
 */
@Test
public void shouldReturn500WhenDeleteUser() {
    url = "http://localhost:"+port+"/user/12";

    //创建body
    Map<String,Object> body = new HashMap();
    body.put("infinity",true);

    //创建headers
    MultiValueMap<String,String> requestHeaders = new LinkedMultiValueMap<>();
    //设置headers
    requestHeaders.add("Content-Type","application/json; charset=UTF-8");
    //头部登录信息
    requestHeaders.add("Authentication","123asd");

    //设置http请求数据
    HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

    //解码返回的用户信息
    Map<String,Object> auth = new HashedMap();
    auth.put("userStatus","admin");   //是管理员
    //Mock jwt,解码json web token
    when(jwt.decode(any())).thenReturn(auth);

    //查找用户,返回用户信息
    User user = new User();
    //Mock userService,获取用户信息
    when(userService.findByID(12)).thenReturn(user); //用户存在

    //Mock userService,更新用户信息
    when(userService.update(any())).thenReturn(0);  //更新失败

    //发起请求
    ResponseEntity response = this.restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class );

    //返回状态码应该等于500
    assertEquals(500,response.getStatusCode().value());
}
项目:OnlineCourse    文件:ProfileControllerTest.java   
/**
 * 获取用户资料,用户不存在,应该返回404
 */
@Test
public void shouldReturn404WhenGetUserProfile() {
    url = "http://localhost:"+port+"/user/10/profile";

    //创建body
    Map<String,Object> body = new HashMap();

    //创建headers
    MultiValueMap<String,String> requestHeaders = new LinkedMultiValueMap<>();
    //设置headers
    requestHeaders.add("Content-Type","application/json; charset=UTF-8");
    //头部登录信息
    requestHeaders.add("Authentication","123asd");

    //设置http请求数据
    HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

    //解码返回的用户信息
    Map<String,Object> auth = new HashedMap();
    //Mock jwt,解码json web token
    when(jwt.decode(any())).thenReturn(auth);

    //Mock userService,获取用户信息
    when(userService.findByID(10)).thenReturn(null);

    //发起请求
    ResponseEntity response = this.restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class );

    //返回状态码应该等于404
    assertEquals(404,response.getStatusCode().value());
}