Java Code Examples for net.sf.json.JSONObject

The following examples show how to use net.sf.json.JSONObject. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: benten   Source File: JiraConverter.java    License: MIT License 8 votes vote down vote up
public static List<JSONObject> getRequiredFields(JSONObject fields){
    List<JSONObject> requiredFields = new ArrayList<>();

    Iterator<?> iterator = fields.keys();
    while (iterator.hasNext()) {
        String key = (String)iterator.next();
        JSONObject jsonChildObject = fields.getJSONObject(key);

        boolean required = jsonChildObject.getBoolean("required");
        if(required) {
            if(!key.startsWith("customfield")) {
                if ("Project".equals(jsonChildObject.getString("name")) || "Issue Type".equals(jsonChildObject.getString("name"))
                        || "Summary".equals(jsonChildObject.getString("name")))
                    continue;
            }
            jsonChildObject.put("key", key);
            requiredFields.add(jsonChildObject);

        }

    }
    return requiredFields;
}
 
Example 2
Source Project: gerrit-events   Source File: GerritJsonEventFactory.java    License: MIT License 6 votes vote down vote up
/**
 * Tries to parse the provided string into a JSONObject and returns it if it is interesting and usable.
 * If it is interesting is determined by:
 * <ol>
 *  <li>The object contains a String field named type</li>
 *  <li>The String returns a non null GerritEventType from
 *      {@link GerritEventType#findByTypeValue(java.lang.String) }</li>
 *  <li>The property {@link GerritEventType#isInteresting() } == true</li>
 * </ol>
 * It is usable if the type's {@link GerritEventType#getEventRepresentative() } is not null.
 * @param jsonString the string to parse.
 * @return an interesting and usable JSONObject, or null if it is not.
 */
public static JSONObject getJsonObjectIfInterestingAndUsable(String jsonString) {
    logger.trace("finding event for jsonString: {}", jsonString);
    if (jsonString == null || jsonString.length() <= 0) {
        return null;
    }
    try {
        JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(jsonString);
        logger.debug("Parsed a JSONObject");
        if (isInterestingAndUsable(jsonObject)) {
            return jsonObject;
        }
    } catch (Exception ex) {
        logger.warn("Unanticipated error when examining JSON String", ex);
    }
    return null;
}
 
Example 3
Source Project: jeecg   Source File: QueryParamUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将结果集转化为列表json格式(不含分页信息)
 * @param result 结果集
 * @param size 总大小
 * @return 处理好的json格式
 */
@SuppressWarnings("unchecked")
public static String getJson(List<Map<String, Object>> result){
	JSONArray rows = new JSONArray();
	for(Map m:result){
		JSONObject item = new JSONObject();
		Iterator  it =m.keySet().iterator();
		while(it.hasNext()){
			String key = (String) it.next();
			String value =String.valueOf(m.get(key));
			key = key.toLowerCase();
			if(key.contains("time")||key.contains("date")){
				value = datatimeFormat(value);
			}
			item.put(key,value );
		}
		rows.add(item);
	}
	return rows.toString();
}
 
Example 4
Source Project: TrackRay   Source File: Awvs.java    License: GNU General Public License v3.0 6 votes vote down vote up
public List<Vulnerabilities> vulns(String sessionId,String scanId){
    ArrayList<Vulnerabilities> obj = new ArrayList<>();
    JSONObject jsonObject = vulnsJSON(sessionId, scanId);
    if (jsonObject.containsKey("vulnerabilities")){
        JSONArray vulnerabilities = jsonObject.getJSONArray("vulnerabilities");
        for (int i = 0; i < vulnerabilities.size(); i++) {
            JSONObject vul = vulnerabilities.getJSONObject(i);
            try {
                Vulnerabilities vulnbean = toBean(vul.toString(), Vulnerabilities. class);
                /*Vulndetail vulndetail = vuln(scanId, sessionId, vulnbean.getVulnId());
                vulnbean.getVuln().add(vulndetail);*/
                obj.add(vulnbean);
            } catch (IOException e) {
                continue;
            }
        }
    }
    return obj;
}
 
Example 5
Source Project: wangmarket   Source File: ImServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void updateIMServer(boolean haveImSet, Im im) {
	if(im == null){
		im = new Im();
	}
	
	JSONObject json = new JSONObject();
	json.put("autoReply", im.getAutoReply() == null ? "":im.getAutoReply());
	json.put("email", im.getEmail() == null ? "":im.getEmail());
	json.put("haveImSet", haveImSet);
	json.put("useOffLineEmail", im.getUseOffLineEmail() == null ? Im.USE_FALSE : im.getUseOffLineEmail()-Im.USE_TRUE==0);
	json.put("userid", im.getUserid());
	
	if(Global.kefuMNSUtil != null){
		Global.kefuMNSUtil.putMessage(Global.kefuMNSUtil_queueName, json.toString());
	}
}
 
Example 6
Source Project: jeewx   Source File: NewsTemplateController.java    License: Apache License 2.0 6 votes vote down vote up
/***
 * 图片上传微信服务器
 * @param realpath 图片路径
 * @param accountid 微信账号id
 * @param request
 * @return
 */
public String uploadPhoto(String realpath, String accountid, HttpServletRequest request) {
	String media_id ="";
	String accessToken =  this.weixinAccountService.getAccessToken(accountid,false);
	String url = request.getSession().getServletContext().getRealPath("")+System.getProperty("file.separator")+realpath;
	JSONObject jsonObj = WeixinUtilOsc.sendMedia("image",url,accessToken);
	if(jsonObj!=null){
		if(jsonObj.containsKey("errcode")){
			String errcode = jsonObj.getString("errcode");
			String errmsg = jsonObj.getString("errmsg");
			org.jeecgframework.core.util.LogUtil.info("图片同步微信服务器失败【errcode="+errcode+"】【errmsg="+errmsg+"】");
		}else{
			org.jeecgframework.core.util.LogUtil.info("图片素材同步微信服务器成功");
			media_id = jsonObj.getString("media_id");
		}
	}
	return media_id;
}
 
Example 7
Source Project: jeewx   Source File: Dispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 进入事件执行器
 * 
 * @param bizContentJson
 * @return
 */
private static ActionExecutor getEnterEventTypeExecutor(JSONObject bizContentJson) {
    try {

        JSONObject param = JSONObject.fromObject(bizContentJson.get("ActionParam"));
        JSONObject scene = JSONObject.fromObject(param.get("scene"));

        if (!StringUtils.isEmpty(scene.getString("sceneId"))) {

            //自定义场景参数进入服务窗事件
            return new InAlipayDIYQRCodeEnterExecutor(bizContentJson);
        } else {

            //普通进入服务窗事件
            return new InAlipayEnterExecutor(bizContentJson);
        }
    } catch (Exception exception) {
        //无法解析sceneId的情况作为普通进入服务窗事件
        return new InAlipayEnterExecutor(bizContentJson);
    }
}
 
Example 8
Source Project: cloudbreak   Source File: ModelConverterUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<>();

    Iterator<String> keysItr = object.keys();
    while (keysItr.hasNext()) {
        Object key = keysItr.next();
        Object value = object.get(key);
        if (value instanceof JSONArray) {
            value = toList((JSONArray) value);
        } else if (value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }
        if (key.toString().contains(SEGMENT_CHARACTER)) {
            String[] split = key.toString().split(ESCAPED_SEGMENT_CHARACTER);
            value = toMap(replaceFirstSegmentOfKey(key.toString()), value);
            Map<String, Object> result = new HashMap<>();
            result.put(split[0], value);
            map = deepMerge(map, result);
        } else {
            map.put(key.toString(), value);
        }
    }
    return map;
}
 
Example 9
Source Project: marathon-plugin   Source File: MarathonRecorderTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test that Labels are properly put through replace macro.
 *
 * @throws Exception
 */
@Test
public void testRecorderLabelsMacro() throws Exception {
    final List<MarathonLabel> labels           = new ArrayList<>(2);
    final MarathonRecorder    marathonRecorder = new MarathonRecorder(TestUtils.getHttpAddresss(httpServer));

    labels.add(new MarathonLabel("foo", "bar-${BUILD_NUMBER}"));
    labels.add(new MarathonLabel("fizz", "buzz-$BUILD_NUMBER"));
    marathonRecorder.setLabels(labels);

    final FreeStyleProject project = basicSetup(marathonRecorder);
    final FreeStyleBuild   build   = basicRunWithSuccess(project);

    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    final JSONObject jsonRequest = TestUtils.jsonFromRequest(httpServer);
    final JSONObject jsonLabel   = jsonRequest.getJSONObject("labels");
    final String     buildNumber = String.valueOf(build.getNumber());

    assertEquals("'foo' label failed", "bar-" + buildNumber, jsonLabel.getString("foo"));
    assertEquals("'fizz1' label failed", "buzz-" + buildNumber, jsonLabel.getString("fizz"));
}
 
Example 10
Source Project: mobi   Source File: CatalogRestTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getConflictsTest() {
    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI)
            + "/branches/" + encode(BRANCH_IRI) + "/conflicts")
            .queryParam("targetId", BRANCH_IRI).request().get();
    assertEquals(response.getStatus(), 200);
    verify(catalogManager, times(2)).getHeadCommit(vf.createIRI(LOCAL_IRI), vf.createIRI(RECORD_IRI), vf.createIRI(BRANCH_IRI));
    verify(catalogManager).getConflicts(vf.createIRI(COMMIT_IRIS[0]), vf.createIRI(COMMIT_IRIS[0]));
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 1);
        JSONObject outcome = JSONObject.fromObject(result.get(0));
        assertTrue(outcome.containsKey("left"));
        assertTrue(outcome.containsKey("right"));
        JSONObject left = JSONObject.fromObject(outcome.get("left"));
        JSONObject right = JSONObject.fromObject(outcome.get("right"));
        assertTrue(left.containsKey("additions"));
        assertTrue(left.containsKey("deletions"));
        assertTrue(right.containsKey("additions"));
        assertTrue(right.containsKey("deletions"));
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 11
Source Project: BotLibre   Source File: Telegram.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public String processMessage(JSONObject message, Network memory) {
	this.responseListener = new ResponseListener();
	checkMessage(message, 0, 0, memory);
	memory.save();
	String reply = null;
	synchronized (this.responseListener) {
		if (this.responseListener.reply == null) {
			try {
				this.responseListener.wait(MAX_WAIT);
			} catch (Exception exception) {
				log(exception);
				return "";
			}
		}
		reply = this.responseListener.reply;
		this.responseListener = null;
	}
	return reply;
}
 
Example 12
Source Project: jenkins-client-plugin   Source File: ResourceSelector.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ResourceSelector newInstance(StaplerRequest req,
        JSONObject formData) throws FormException {
    ResourceSelector s = super.newInstance(req, formData);

    String selectionType = formData.getString("selectionType");
    System.out.println("parms2: " + selectionType);

    if (SELECT_BY_KIND.equals(selectionType)) {
        s.names = null;
    }
    if (SELECT_BY_NAMES.equals(selectionType)) {
        s.kind = null;
        s.labels = null;
    }
    return s;
}
 
Example 13
private JSONObject mapToJson(final DeliveryInfo deliveryInfo) {
    final JSONObject entry = new JSONObject();

    entry.element("timestamp", DateUtilities.toLong(deliveryInfo.getTimestamp()));
    entry.element("dsn", deliveryInfo.getDsn());
    entry.element("status", deliveryInfo.getStatus());

    final String relay = deliveryInfo.getRelay();
    if(StringUtils.startsWith(relay, "[")){
        entry.element("relay", JSONUtils.quote(deliveryInfo.getRelay()));
    } else {
        entry.element("relay", deliveryInfo.getRelay());
    }

    return entry;
}
 
Example 14
Source Project: IPCInvoker   Source File: IPCInvokerAGContextExtension.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onPreInitialize(AGContext context, JSONObject initArgs) {
    Log.d(TAG, "onPreInitialize(%s)", context.hashCode());
    ArbitraryGenProcessor processor = context.getProcessor("javaCodeEngine");
    if (processor instanceof JavaCodeAGEngine) {
        JavaCodeAGEngine engine = (JavaCodeAGEngine) processor;
        AGAnnotationWrapper annWrapper = new AGAnnotationWrapper();
        annWrapper.addAnnotationProcessor(new IPCInvokeTaskProcessor());
        engine.addTypeDefWrapper(annWrapper);

        JSONObject javaCodeEngine = initArgs.getJSONObject("javaCodeEngine");
        if (javaCodeEngine != null) {
            if (!javaCodeEngine.containsKey("ruleFile") && !javaCodeEngine.containsKey("rule")) {
                javaCodeEngine.put("rule", "${project.projectDir}/src/main/java/*.java");
            }
        }
    }
}
 
Example 15
Source Project: zap-extensions   Source File: ExtensionZest.java    License: Apache License 2.0 6 votes vote down vote up
private String getWindowHandle(
        JSONObject clientMessage, ScriptNode node, String windowId, String url) {
    String windowHandle = this.clientUrlToWindowHandle.get(url);
    if (windowHandle != null) {
        return windowHandle;
    }
    windowHandle = "WIN-" + recordingWinId++;
    if (startRecordingUrl != null && startRecordingUrl.equals(url)) {
        this.addWindowLaunch(node, windowHandle, url);
        startRecordingUrl = null;
    } else {
        this.addWindowHandle(node, windowHandle, url);
    }
    this.clientUrlToWindowHandle.put(url, windowHandle);
    return windowHandle;
}
 
Example 16
Source Project: TrackRay   Source File: Awvs.java    License: GNU General Public License v3.0 6 votes vote down vote up
public String startScan(String targetId){
    String data = "{\"target_id\": \"\", \"profile_id\": \"11111111-1111-1111-1111-111111111111\",\n" +
            "                \"schedule\": {\"disable\": false, \"start_date\": null, \"time_sensitive\": false}}";
    JSONObject jsondata = JSONObject.fromObject(data);

    jsondata.put("target_id",targetId);

    String resp = send("/api/v1/scans", jsondata.toString(), HttpMethod.POST);

    JSONObject respJson = JSONObject.fromObject(resp);
    /**
     * {
     "schedule": {
     "start_date": null,
     "disable": false,
     "time_sensitive": false
     },
     "ui_session_id": null,
     "target_id": "01a1bb0a-0cc9-4e62-a653-bcb3beda208d",
     "profile_id": "11111111-1111-1111-1111-111111111111"
     }
     */
    return respJson.getString("target_id");
}
 
Example 17
Source Project: JavaWeb   Source File: ChartController.java    License: Apache License 2.0 6 votes vote down vote up
@OnOpen
public void onOpen(Session session,@PathParam("username") String username) {
	try{
		client.add(session);
		user.put(URLEncoder.encode(username, "UTF-8"),URLEncoder.encode(username, "UTF-8"));
		JSONObject jo = new JSONObject();
		JSONArray ja = new JSONArray();
		//获得在线用户列表
		Set<String> key = user.keySet();
		for (String u : key) {
			ja.add(u);
		}
		jo.put("onlineUser", ja);
		session.getBasicRemote().sendText(jo.toString());
	}catch(Exception e){
		//do nothing
	}
}
 
Example 18
/**
 * 发送短信验证码
 * 
 * @return
 */
@Action(value = "sendVerification")
public void sendVerification() throws Exception {
	String phone = getParameter("phone");
	System.out.println("CustomerAction.sendVerification()");
	// 1.生成验证码
	String verificationCode = MessageSend.getVerificationCode();
	try {
		JSONObject result = JSONObject
				.fromObject(MessageSend.sendDynamicVerification(
						verificationCode, phone));
		if ("OK".equals(result.get("msg"))) {
			session.clear();
			session.put("verificationCode", verificationCode);
			writeStringToResponse("【ok】");
		}
	} catch (Exception e) {
		log.error("发送验证码失败!");
		e.printStackTrace();
	}

}
 
Example 19
Source Project: jmeter-bzm-plugins   Source File: LoadosophiaClientTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of getQuantilesJSON method, of class LoadosophiaAggregator.
 */
@Test
public void testGetQuantilesJSON() {
    System.out.println("getQuantilesJSON");
    Long[] rtimes = new Long[0];
    JSONObject result = LoadosophiaClient.getQuantilesJSON(rtimes);
    assertNotNull(result);
}
 
Example 20
/**
 * ホストグループ情報を削除します。<br/>
 * groupidパラメータを必ず指定する必要があります。<br/>
 * 存在しないgroupidを指定した場合、例外をスローします。<br/>
 *
 * @param groupids 削除するホストグループのIDのリスト
 * @return 削除したホストグループ情報のhostgroupidのリスト
 */
@SuppressWarnings("unchecked")
public List<String> delete(List<String> groupids) {
    if (groupids == null || groupids.isEmpty()) {
        throw new IllegalArgumentException("groupid is required.");
    }

    JSONArray params;
    if (accessor.checkVersion("2.0") < 0) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (String groupid : groupids) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("groupid", groupid);
            list.add(map);
        }
        params = JSONArray.fromObject(list, defaultConfig);
    } else {
        params = JSONArray.fromObject(groupids, defaultConfig);
    }

    JSONObject result = (JSONObject) accessor.execute("hostgroup.delete", params);

    JSONArray hostgroupids = result.getJSONArray("groupids");
    JsonConfig config = defaultConfig.copy();
    config.setCollectionType(List.class);
    config.setRootClass(String.class);
    return (List<String>) JSONArray.toCollection(hostgroupids, config);
}
 
Example 21
Source Project: sonar-quality-gates-plugin   Source File: GlobalConfig.java    License: MIT License 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {

    listOfGlobalConfigData = globalConfigurationService.instantiateGlobalConfigData(json);
    save();

    return true;
}
 
Example 22
Source Project: jenkins-plugin   Source File: OpenShiftDeleterList.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject formData)
        throws FormException {
    // To persist global configuration information,
    // pull info from formData, set appropriate instance field (which
    // should have a getter), and call save().
    save();
    return super.configure(req, formData);
}
 
Example 23
Source Project: marathon-plugin   Source File: MarathonBuilderImplTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test that a JSON configuration without any URIs does not throw an error.
 */
@Test
public void testNoUris() throws IOException {
    final String     jsonString = TestUtils.loadFixture("idonly.json");
    final JSONObject json       = JSONObject.fromObject(jsonString);
    final MockConfig config     = new MockConfig();

    MarathonBuilder builder = new MarathonBuilderImpl(config).setJson(json).build();
    assertNull("URIs should be null if none were in the JSON config", builder.getApp().getUris());
}
 
Example 24
Source Project: xnx3   Source File: JSONUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 从 JSONObject 对象中取一个字符串。操作的是 json-lib-2.4-jdk15.jar
 * @param json 要取数据的json对象
 * @param key 要取的字符串在json中的key
 * @return 若有值,能正常取到,返回其值。若取不到,或者json中本来就没有这个key,那么返回空字符串""
 */
public static String getJsonString(JSONObject json, String key){
	if(json.get(key) != null){
		return json.getString(key);
	}else{
		return "";
	}
}
 
Example 25
Source Project: phabricator-jenkins-plugin   Source File: BuildIntegrationTest.java    License: MIT License 5 votes vote down vote up
protected void assertConduitRequest(JSONObject expectedRequestParams, String actualRequestBody) throws IOException,
        ConduitAPIException {
    String conduitTestServerAddress = TestUtils.getTestServerAddress(conduit.getServer());
    ConduitAPIClient conduitTestClient = new ConduitAPIClient(conduitTestServerAddress,
            TestUtils.TEST_CONDUIT_TOKEN);
    HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) conduitTestClient.createRequest("",
            expectedRequestParams);
    String expectedRequestBody = EntityUtils.toString(request.getEntity());

    assertEquals(expectedRequestBody, actualRequestBody);
}
 
Example 26
@Test
public void testBuildValidSuccess() throws Exception {
    JSONObject commentResponse = new JSONObject();
    FreeStyleBuild build = buildWithConduit(getFetchDiffResponse(), commentResponse, null, true);

    assertEquals(Result.SUCCESS, build.getResult());
    PhabricatorPostbuildSummaryAction action = build.getAction(PhabricatorPostbuildSummaryAction.class);
    assertNotNull(action);
    assertEquals("[email protected]", action.getAuthorEmail());
    assertEquals("aiden", action.getAuthorName());
    assertEquals("commit message", action.getCommitMessage());
    assertNotNull(action.getIconPath());
}
 
Example 27
Source Project: jeewx-boot   Source File: WeixinGzuserServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 调用微信接口获取关注用户信息,每次获取最多100条
 * @param user_list
 * @param accessToken
 * @return
 * @throws Exception
 */
public JSONObject batchGetGzUserInfoAPI(List<Map<String,String>> user_list,String accessToken) throws Exception{
	String requestUrl = batch_user_info_url.replace("ACCESS_TOKEN", accessToken);
	JSONObject obj = new JSONObject();
	obj.put("user_list", user_list);
	log.info("------------批量获取粉丝数据接口 调用前参数:  "+obj.toString());
	JSONObject jsonList = WeixinUtil.httpRequest(requestUrl, "POST", obj.toString());
	log.info("------------批量获取粉丝数据接口 调用后参数:  "+jsonList.toString());
	return jsonList;
}
 
Example 28
Source Project: blueocean-plugin   Source File: SigningPublicKey.java    License: MIT License 5 votes vote down vote up
/**
 * Renders the key as JSON in the JWK format.
 */
@WebMethod(name = "")
public JSONObject asJSON() {
    JSONObject jwk = new JSONObject();
    jwk.put("kty", "RSA");
    jwk.put("alg","RS256");
    jwk.put("kid",kid);
    jwk.put("use", "sig");
    jwk.put("key_ops", ImmutableList.of("verify"));
    jwk.put("n", Base64.encode(key.getModulus().toByteArray()));
    jwk.put("e", Base64.encode(key.getPublicExponent().toByteArray()));
    return jwk;
}
 
Example 29
Source Project: packer-plugin   Source File: PackerJenkinsPluginTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testPluginInJobPathExec() throws Exception {
    final String jsonText = "{ \"here\": \"i am\"}";
    PackerInstallation installation = new PackerInstallation(name, home,
            params, createTemplateModeJson(TemplateMode.TEXT, jsonText), emptyFileEntries, null);

    final String pluginHome = "bin";
    PackerPublisher placeHolder = new PackerPublisher(name,
            null, null, pluginHome, localParams, emptyFileEntries, false, null);

    PackerInstallation[] installations = new PackerInstallation[1];
    installations[0] = installation;

    placeHolder.getDescriptor().setInstallations(installations);

    StaplerRequest mockReq = mock(StaplerRequest.class);
    when(mockReq.bindJSON(any(Class.class), any(JSONObject.class))).thenReturn(placeHolder);

    JSONObject formJson = new JSONObject();
    formJson.put("templateMode", createTemplateModeJson(TemplateMode.TEXT, jsonText));
    PackerPublisher plugin = placeHolder.getDescriptor().newInstance(mockReq, formJson);

    assertEquals(pluginHome, plugin.getPackerHome());
    assertEquals(localParams, plugin.getParams());

    assertTrue(plugin.isTextTemplate());
    assertFalse(plugin.isFileTemplate());
    assertFalse(plugin.isGlobalTemplate());
    assertEquals(jsonText, plugin.getJsonTemplateText());

    FreeStyleProject project = jenkins.createFreeStyleProject();
    FreeStyleBuild build = project.scheduleBuild2(0).get();

    Launcher launcherMock = mock(Launcher.class);
    TaskListener listenerMock = mock(TaskListener.class);

    String exec = plugin.getRemotePackerExec(build, launcherMock, listenerMock);

    assertEquals(build.getWorkspace().getRemote() + "/" + pluginHome + "/packer", exec);
}
 
Example 30
Source Project: mobi   Source File: CatalogRestTest.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void updateUnversionedDistributionWithIncorrectPathTest() {
    // Setup:
    JSONObject distribution = new JSONObject().element("@id", DISTRIBUTION_IRI);
    doThrow(new IllegalArgumentException()).when(catalogManager).updateUnversionedDistribution(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(ERROR_IRI)), any(Distribution.class));

    Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(ERROR_IRI)
            + "/distributions/" + encode(DISTRIBUTION_IRI))
            .request().put(Entity.json(distribution.toString()));
    assertEquals(response.getStatus(), 400);
}