Java Code Examples for org.json.JSONArray#getJSONObject()

The following examples show how to use org.json.JSONArray#getJSONObject() . 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 File: NeopixelFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
Board(@NonNull Context context, int standardIndex) {

            String boardsJsonString = FileUtils.readAssetsFile("neopixel" + File.separator + "NeopixelBoards.json", context.getAssets());
            try {
                JSONArray boardsArray = new JSONArray(boardsJsonString);
                JSONObject boardJson = boardsArray.getJSONObject(standardIndex);

                name = boardJson.getString("name");
                width = (byte) boardJson.getInt("width");
                height = (byte) boardJson.getInt("height");
                stride = (byte) boardJson.getInt("stride");

            } catch (JSONException e) {
                Log.e(TAG, "Invalid board parameters");
                e.printStackTrace();
            }
        }
 
Example 2
Source File: AlbumParser.java    From Android-Application-ZJB with Apache License 2.0 6 votes vote down vote up
@Override
public List<Album> parser(String json) {
    ArrayList<Album> lists = new ArrayList<>();
    try {
        JSONArray array = new JSONArray(json);
        for (int i = 0; i < array.length(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            String jsonString = jsonObject.toString();
            Gson gson = new Gson();
            Album album = gson.fromJson(jsonString, Album.class);
            lists.add(album);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return lists;
}
 
Example 3
Source File: InviteServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String getTaskId(String inviteId) throws Exception
{
    String url = "/api/task-instances";
    Response response = sendRequest(new GetRequest(url), 200);
    JSONObject top = new JSONObject(response.getContentAsString());
    JSONArray data = top.getJSONArray("data");
    for (int i=0; i < data.length(); i++)
    {
        JSONObject task = data.getJSONObject(i);
        JSONObject workflowInstance = task.getJSONObject("workflowInstance");
        if (!inviteId.equalsIgnoreCase(workflowInstance.getString("id")))
        {
            continue;
        }
        return task.getString("id");
    }
    return null;
}
 
Example 4
Source File: FanartSearchFragment.java    From Mizuu with Apache License 2.0 6 votes vote down vote up
private void loadJson(String baseUrl) {
	try {
		mCovers.clear();
		mImageUrls.clear();
		
		JSONObject jObject = new JSONObject(mJson);
		JSONArray array = jObject.getJSONArray("backdrops");

		for (int i = 0; i < array.length(); i++) {
			JSONObject o = array.getJSONObject(i);
			mCovers.add(new Cover(baseUrl + MizLib.getBackdropThumbUrlSize(getActivity()) + o.getString("file_path"), o.getString("iso_639_1")));
			mImageUrls.add(baseUrl + MizLib.getBackdropThumbUrlSize(getActivity()) + o.getString("file_path"));
		}
	} catch (Exception e) {}

	if (isAdded()) {
		showContent();
	}
}
 
Example 5
Source File: VersionMigrator.java    From JetUML with GNU General Public License v3.0 6 votes vote down vote up
private void removeSelfDependencies(JSONObject pDiagram)
{
	JSONArray edges = pDiagram.getJSONArray("edges");
	List<JSONObject> newEdges = new ArrayList<>();
	for( int i = 0; i < edges.length(); i++ )
	{
		JSONObject object = edges.getJSONObject(i);
		if( object.getString("type").equals("DependencyEdge") && object.getInt("start") == object.getInt("end") )
		{
			aMigrated = true; // We don't add the dependency, essentially removing it.
		}
		else
		{
			newEdges.add(object);
		}
	}
	pDiagram.put("edges", new JSONArray(newEdges));
}
 
Example 6
Source File: GitFileDecorator.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private void calcGitLinks(JSONArray children, JSONObject representation, URI cloneLocation, Repository db, RemoteBranch defaultRemoteBranch, String branch,
		HttpServletRequest request) throws JSONException, URISyntaxException, CoreException, IOException {

	if (children != null) {
		for (int i = 0; i < children.length(); i++) {
			JSONObject child = children.getJSONObject(i);
			String location = child.getString(ProtocolConstants.KEY_LOCATION);
			if (db != null) {
				// if parent was a git repository we can reuse information computed above\
				addGitLinks(request, new URI(location), child, cloneLocation, db, defaultRemoteBranch, branch);
				JSONArray childItems = child.optJSONArray(ProtocolConstants.KEY_CHILDREN);
				if (childItems != null) {
					calcGitLinks(childItems, representation, cloneLocation, db, defaultRemoteBranch, branch, request);
				}
			} else {
				// maybe the child is the root of a git repository
				addGitLinks(request, new URI(location), child);
			}
		}
	}
}
 
Example 7
Source File: StoryMarshaller.java    From hex with Apache License 2.0 6 votes vote down vote up
private static List<Comment> marshallComments(JSONArray rawComments) {
    List<Comment> comments = new ArrayList<>();

    for (int i = 0; i < rawComments.length(); i++) {
        try {
            JSONObject rawComment = rawComments.getJSONObject(i);
            List<Comment> childComments = new ArrayList<>();
            JSONArray rawChildComments = rawComment.getJSONArray("comments");

            if (rawChildComments != null) {
                childComments = marshallComments(rawComment.getJSONArray("comments"));
            }

            String text = rawComment.getString("text");
            String author = rawComment.getString("author");
            int commentCount = rawComment.getInt("commentCount");
            Date date = new DateTime(rawComment.getString("time")).toDate();
            comments.add(new Comment(text, author, childComments, commentCount, date));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return comments;
}
 
Example 8
Source File: JsonDeserializer.java    From mobly-bundled-snippets with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static AdvertiseData jsonToBleAdvertiseData(JSONObject jsonObject) throws JSONException {
    AdvertiseData.Builder builder = new AdvertiseData.Builder();
    if (jsonObject.has("IncludeDeviceName")) {
        builder.setIncludeDeviceName(jsonObject.getBoolean("IncludeDeviceName"));
    }
    if (jsonObject.has("IncludeTxPowerLevel")) {
        builder.setIncludeTxPowerLevel(jsonObject.getBoolean("IncludeTxPowerLevel"));
    }
    if (jsonObject.has("ServiceData")) {
        JSONArray serviceData = jsonObject.getJSONArray("ServiceData");
        for (int i = 0; i < serviceData.length(); i++) {
            JSONObject dataSet = serviceData.getJSONObject(i);
            ParcelUuid parcelUuid = ParcelUuid.fromString(dataSet.getString("UUID"));
            builder.addServiceUuid(parcelUuid);
            if (dataSet.has("Data")) {
                byte[] data = Base64.decode(dataSet.getString("Data"), Base64.DEFAULT);
                builder.addServiceData(parcelUuid, data);
            }
        }
    }
    if (jsonObject.has("ManufacturerData")) {
        JSONObject manufacturerData = jsonObject.getJSONObject("ManufacturerData");
        int manufacturerId = manufacturerData.getInt("ManufacturerId");
        byte[] manufacturerSpecificData =
                Base64.decode(jsonObject.getString("ManufacturerSpecificData"), Base64.DEFAULT);
        builder.addManufacturerData(manufacturerId, manufacturerSpecificData);
    }
    return builder.build();
}
 
Example 9
Source File: JsonUtil.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static JSONObject get(JSONArray arr, int i) {

        JSONObject json = null;

        try {
            json = arr.getJSONObject(i);
        } catch (JSONException e) {
            LOG.error("Exception while getting element from json array: ", e);
        }

        return json;
    }
 
Example 10
Source File: K256KeyPairTest.java    From ripple-lib-java with ISC License 5 votes vote down vote up
@Test
public void testRFC6979() throws UnsupportedEncodingException, NoSuchAlgorithmException {
    JSONObject fixtures = new JSONObject(this.fixtures);
    JSONArray rfc6979 = fixtures.getJSONArray("rfc6979");
    for (int i = 0; i < rfc6979.length(); i++) {
        JSONObject test = rfc6979.getJSONObject(i);
        byte[] message = test.getString("message").getBytes("utf-8");
        byte[] messageHash = MessageDigest.getInstance("SHA-256").digest(message);
        final BigInteger[] specialKArray = new BigInteger[16];
        HMacDSAKCalculator calc = new HMacDSAKCalculator(new SHA256Digest()) {
            int ptr = 0;
            @Override
            public boolean isValid(BigInteger k) {
                specialKArray[ptr++] = k;
                return ptr == 16;
            }
        };
        BigInteger d = new BigInteger(test.getString("d"), 16);
        calc.init(SECP256K1.order(), d, messageHash);
        calc.nextK();

        for (int j = 0; j < 16; j++) {
            BigInteger bigInteger = specialKArray[j];
            String key = "k" + j;
            if (test.has(key)) {
                assertEquals(test.getString(key), bigInteger.toString(16));
            }
        }
    }
}
 
Example 11
Source File: ResponseParser.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static ArrayList<TokenDisplay> parseTokens(Context c, String response, LastIconLoaded callback) throws Exception {
    Log.d("tokentest", response);
    ArrayList<TokenDisplay> display = new ArrayList<TokenDisplay>();
    JSONArray data = new JSONObject(response).getJSONArray("tokens");
    for (int i = 0; i < data.length(); i++) {
        JSONObject currentToken = data.getJSONObject(i);
        try {
            display.add(new TokenDisplay(
                    currentToken.getJSONObject("tokenInfo").getString("name"),
                    currentToken.getJSONObject("tokenInfo").getString("symbol"),
                    new BigDecimal(currentToken.getString("balance")),
                    currentToken.getJSONObject("tokenInfo").getInt("decimals"),
                    currentToken.getJSONObject("tokenInfo").getJSONObject("price").getDouble("rate"),
                    currentToken.getJSONObject("tokenInfo").getString("address"),
                    currentToken.getJSONObject("tokenInfo").getString("totalSupply"),
                    currentToken.getJSONObject("tokenInfo").getLong("holdersCount"),
                    0
            ));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Download icon and cache it
        EtherscanAPI.getInstance().loadTokenIcon(c, currentToken.getJSONObject("tokenInfo").getString("name"), i == data.length() - 1, callback);

    }
    return display;
}
 
Example 12
Source File: Pyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 5 votes vote down vote up
static void parseAndSave(@NonNull JSONArray array) throws JSONException {
    List<Server> servers = new ArrayList<>(array.length());
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
        String name = CommonUtils.getStupidString(obj, "name");

        HttpUrl url = new HttpUrl.Builder()
                .host(obj.getString("host"))
                .scheme(obj.getBoolean("secure") ? "https" : "http")
                .port(obj.getInt("port"))
                .encodedPath(obj.getString("path"))
                .build();

        String metrics = CommonUtils.getStupidString(obj, "metrics");
        servers.add(new Server(url, metrics == null ? null : HttpUrl.parse(metrics),
                name == null ? (url.host() + " server") : name,
                obj.has("params") ? new Params(obj.getJSONObject("params")) : Params.defaultValues(),
                false));
    }

    JSONArray json = new JSONArray();
    for (Server server : servers)
        json.put(server.toJson());

    JsonStoring.intoPrefs().putJsonArray(PK.API_SERVERS, json);
    Prefs.putLong(PK.API_SERVERS_CACHE_AGE, System.currentTimeMillis());
}
 
Example 13
Source File: Temperature.java    From SmartPack-Kernel-Manager with GNU General Public License v3.0 5 votes vote down vote up
private TempJson(Context context) {
    try {
        JSONArray tempArray = new JSONArray(Utils.readAssetFile(context, "temp.json"));
        for (int i = 0; i < tempArray.length(); i++) {
            JSONObject device = tempArray.getJSONObject(i);
            if (Device.getBoard().equalsIgnoreCase(device.getString("board"))) {
                mDeviceJson = device;
                break;
            }
        }
    } catch (JSONException ignored) {
        String TAG = TempJson.class.getSimpleName();
        Log.e(TAG, "Can't read temp.json");
    }
}
 
Example 14
Source File: TrackerServerTest.java    From barefoot with Apache License 2.0 5 votes vote down vote up
@Test
public void testTrackerServer() throws IOException, JSONException, InterruptedException {
    Server server = new Server();
    InetAddress host = InetAddress.getLocalHost();
    Properties properties = new Properties();
    properties.load(new FileInputStream("config/tracker.properties"));
    int port = Integer.parseInt(properties.getProperty("server.port"));

    server.start();
    {
        String json = new String(
                Files.readAllBytes(
                        Paths.get(ServerTest.class.getResource("x0001-015.json").getPath())),
                Charset.defaultCharset());
        List<MatcherSample> samples = new LinkedList<>();
        JSONArray jsonsamples = new JSONArray(json);
        for (int i = 0; i < jsonsamples.length(); ++i) {
            MatcherSample sample = new MatcherSample(jsonsamples.getJSONObject(i));
            samples.add(sample);
            sendSample(host, port, sample.toJSON());
        }

        String id = new MatcherSample(jsonsamples.getJSONObject(0)).id();
        MatcherKState state = requestState(host, port, id);
        MatcherKState check = TrackerControl.getServer().getMatcher().mmatch(samples, 0, 0);

        assertEquals(check.sequence().size(), state.sequence().size());

        for (int i = 0; i < state.sequence().size(); i++) {
            assertEquals(check.sequence().get(i).point().edge().id(),
                    state.sequence().get(i).point().edge().id());
            assertEquals(check.sequence().get(i).point().fraction(),
                    state.sequence().get(i).point().fraction(), 1E-10);
        }
    }
    server.stop();
}
 
Example 15
Source File: WeatherFragment.java    From MuslimMateAndroid with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected List<Weather> doInBackground(Void... voids) {
    try {
        //weather list
        weathers = new ArrayList<>();
        LocationInfo locationInfo = ConfigPreferences.getLocationConfig(getContext());
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(URL + "lat=" + locationInfo.latitude + "&lon=" + locationInfo.longitude + "&lang="+ Locale.getDefault().getLanguage() + API_ID).build();

        Log.i("URL_WITHER" , URL + "lat=" + locationInfo.latitude + "&lon=" + locationInfo.longitude+"&lang="+ Locale.getDefault().getLanguage() + API_ID);
        //receive json and parse
        Response response = client.newCall(request).execute();
        String jsonData = response.body().string();
        if (jsonData != null) {
            JSONObject Jobject = new JSONObject(jsonData);
            JSONArray Jarray = Jobject.getJSONArray("list");
            for (int i = 0; i < Jarray.length(); i++) {
                JSONObject object = Jarray.getJSONObject(i);
                JSONObject main = object.getJSONObject("main");
                JSONArray weather = object.getJSONArray("weather");
                String desc = weather.getJSONObject(0).getString("description");
                Log.i("URL_WITHER" , "desc : "+desc);
                String icon = weather.getJSONObject(0).getString("icon");
                String date = object.getString("dt_txt");
                String temp = main.getString("temp");
                String temp_min = main.getString("temp_min");
                String temp_max = main.getString("temp_max");
                String humidity = main.getString("humidity");
                JSONObject wind = object.getJSONObject("wind");
                String windSpeed = wind.getString("speed");

                //convert weather degree and add to weather list
                weathers.add(new mindtrack.muslimorganizer.model.Weather
                        (date, Math.round(Float.valueOf(temp) - 272.15f) + "",
                                Math.round(Float.valueOf(temp_min) - 272.15f) + "",
                                Math.round(Float.valueOf(temp_max) - 272.15f) + "",
                                icon, desc, humidity, windSpeed));
            }


        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return weathers;
}
 
Example 16
Source File: GitCloneTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
static void ensureCloneIdDoesntExist(JSONArray clonesArray, String id) throws JSONException {
	for (int i = 0; i < clonesArray.length(); i++) {
		JSONObject clone = clonesArray.getJSONObject(i);
		assertFalse(id.equals(clone.get(ProtocolConstants.KEY_ID)));
	}
}
 
Example 17
Source File: QrReaderPresenterImpl.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void handleDataInfo(JSONArray jsonArray) {
    ArrayList<Trio<TrackedEntityDataValue, String, Boolean>> attributes = new ArrayList<>();
    try {
        // LOOK FOR TRACKED ENTITY ATTRIBUTES ON LOCAL DATABASE
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject attrValue = jsonArray.getJSONObject(i);
            TrackedEntityDataValue.Builder trackedEntityDataValueModelBuilder = TrackedEntityDataValue.builder();

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATABASE_FORMAT_EXPRESSION, Locale.getDefault());

            if (attrValue.has("event")) {
                trackedEntityDataValueModelBuilder.event(attrValue.getString("event"));
            }
            if (attrValue.has("dataElement")) {
                trackedEntityDataValueModelBuilder.dataElement(attrValue.getString("dataElement"));
            }
            if (attrValue.has("storedBy")) {
                trackedEntityDataValueModelBuilder.storedBy(attrValue.getString("storedBy"));
            }
            if (attrValue.has("value")) {
                trackedEntityDataValueModelBuilder.value(attrValue.getString("value"));
            }
            if (attrValue.has("providedElsewhere")) {
                trackedEntityDataValueModelBuilder.providedElsewhere(Boolean.parseBoolean(attrValue.getString("providedElsewhere")));
            }
            if (attrValue.has("created")) {
                trackedEntityDataValueModelBuilder.created(simpleDateFormat.parse(attrValue.getString("created")));
            }
            if (attrValue.has("lastUpdated")) {
                trackedEntityDataValueModelBuilder.lastUpdated(simpleDateFormat.parse(attrValue.getString("lastUpdated")));
            }

            if (attrValue.has("dataElement") && attrValue.getString("dataElement") != null) {
                // LOOK FOR dataElement ON LOCAL DATABASE.
                // IF FOUND, OPEN DASHBOARD
                if (d2.dataElementModule().dataElements().uid(attrValue.getString("dataElement")).blockingExists()) {
                    this.dataJson.add(attrValue);
                    DataElement de = d2.dataElementModule().dataElements().uid(attrValue.getString("dataElement")).blockingGet();
                    attributes.add(Trio.create(trackedEntityDataValueModelBuilder.build(), de.formName(), true));
                } else {
                    attributes.add(Trio.create(trackedEntityDataValueModelBuilder.build(), null, false));
                }
            } else {
                attributes.add(Trio.create(trackedEntityDataValueModelBuilder.build(), null, false));
            }
        }
    } catch (JSONException | ParseException e) {
        Timber.e(e);
    }

    view.renderTeiEventDataInfo(attributes);
}
 
Example 18
Source File: UpdateRobot.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
private List<RobotExecutor> getExecutorsFromParameter(String robot, HttpServletRequest request, ApplicationContext appContext, JSONArray json) throws JSONException, CerberusException {
    List<RobotExecutor> reList = new ArrayList<>();
    IFactoryRobotExecutor reFactory = appContext.getBean(IFactoryRobotExecutor.class);
    IRobotExecutorService reService = appContext.getBean(IRobotExecutorService.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();
    List<RobotExecutor> reList1 = reService.convert(reService.readByRobot(robot));

    for (int i = 0; i < json.length(); i++) {
        JSONObject reJson = json.getJSONObject(i);

        boolean delete = reJson.getBoolean("toDelete");
        Integer id = reJson.getInt("ID");
        String executor = reJson.getString("executor");
        String active = reJson.getString("active");
        Integer rank = reJson.getInt("rank");
        String host = reJson.getString("host");
        String port = reJson.getString("port");
        String host_user = reJson.getString("hostUser");
        String deviceName = reJson.getString("deviceName");
        String deviceUdid = reJson.getString("deviceUdid");
        String deviceLockUnlock = reJson.getBoolean("deviceLockUnlock") ? "Y" : "N";
        String executorProxyHost = "";
        if (reJson.has("executorProxyHost") && !StringUtil.isNullOrEmpty(reJson.getString("executorProxyHost"))) {
            executorProxyHost = reJson.getString("executorProxyHost");
        }
        Integer executorProxyPort = null;
        if (reJson.has("executorProxyPort") && !StringUtil.isNullOrEmpty(reJson.getString("executorProxyPort"))) {
            executorProxyPort = reJson.getInt("executorProxyPort");
        }
        String executorProxyActive = reJson.getBoolean("executorProxyActive") ? "Y" : "N";
        Integer executorExtensionPort = null;
        String executorExtensionHost = "";
        if (reJson.has("executorExtensionHost")) {
            executorExtensionHost = reJson.getString("executorExtensionHost");
        }
        if (reJson.has("executorExtensionPort") && !StringUtil.isNullOrEmpty(reJson.getString("executorExtensionPort"))) {
            executorExtensionPort = reJson.getInt("executorExtensionPort");
        }

        Integer devicePort = null;
        if (reJson.has("devicePort") && !StringUtil.isNullOrEmpty(reJson.getString("devicePort"))) {
            devicePort = reJson.getInt("devicePort");
        }

        String description = reJson.getString("description");

        String host_password = reJson.getString("hostPassword");
        if (host_password.equals("XXXXXXXXXX")) {
            host_password = "";
            for (RobotExecutor robotExecutor : reList1) {
                if (robotExecutor.getID() == id) {
                    host_password = robotExecutor.getHostPassword();
                    LOG.debug("Password not changed so reset to original value : " + robotExecutor.getHostPassword());
                }
            }
        }

        if (!delete) {
            RobotExecutor reo = reFactory.create(i, robot, executor, active, rank, host, port, host_user, host_password, deviceUdid, deviceName, devicePort, deviceLockUnlock, executorExtensionHost, executorExtensionPort, executorProxyHost, executorProxyPort, executorProxyActive, description, "", null, "", null);
            reList.add(reo);
        }
    }
    return reList;
}
 
Example 19
Source File: SfdcSerializerService.java    From Data-Migration-Tool with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public ArrayList<QueryResult> deSerialize(SforceObject sforceObject) {
    compare = new MetadataCompareService(false, true);

    String dataMappingDir = "/data-mappings/";
    if (PropertiesReader.getInstance().getProperty(PropertiesReader.PROPERTY_TYPE.BUILD, "data.mapping.dir") != null) {
        dataMappingDir =
                PropertiesReader.getInstance()
                        .getProperty(PropertiesReader.PROPERTY_TYPE.BUILD, "data.mapping.dir");
    }
    String dataJson =
            new ForceFileUtils().getFileAsString(dataMappingDir + sforceObject.getsObjectName() + ".json");
    ArrayList<QueryResult> queryResults = new ArrayList<QueryResult>();

    try {
        JSONArray jsonArray = new JSONArray(dataJson);
        SObject[] sObjects = new SObject[jsonArray.length()];

        Set<String> fieldList = sforceObject.getCommonFields();

        if (sforceObject.getUnmappedFieldsSet() != null) {
            Set<String> unmappedFieldList = sforceObject.getUnmappedFieldsSet();
            fieldList.removeAll(unmappedFieldList);
        }
        fieldList.add("Id");

        for (int index = 0; index < jsonArray.length(); index++) {
            JSONObject jsonObj = jsonArray.getJSONObject(index);

            SObject sObject = new SObject();
            sObject.setField("Type", jsonObj.get("Type"));

            for (String field : fieldList) {
                if (!field.equals("Type")) {
                    sObject.setField(field, jsonObj.get(field));
                    sObjects[index] = sObject;
                }
            }
        }
        QueryResult queryResult = new QueryResult();
        queryResult.setDone(true);
        queryResult.setSize(jsonArray.length());
        queryResult.setRecords(sObjects);
        queryResults.add(queryResult);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return queryResults;
}
 
Example 20
Source File: GitCommitTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testCommitWithCommiterOverwritten() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	IPath[] clonePaths = createTestProjects(workspaceLocation);

	for (IPath clonePath : clonePaths) {
		// clone a  repo
		String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

		// get project metadata
		WebRequest request = getGetRequest(contentLocation);
		WebResponse response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
		JSONObject project = new JSONObject(response.getText());
		JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);

		String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
		String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

		// "git add ."
		request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// commit all
		final String commiterName = "committer name";
		final String commiterEmail = "committer email";

		request = getPostGitCommitRequest(gitHeadUri, "Comit message", false, commiterName, commiterEmail, null, null);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// log
		JSONArray commitsArray = log(gitHeadUri);
		assertEquals(2, commitsArray.length());

		JSONObject commit = commitsArray.getJSONObject(0);
		assertEquals(commiterName, commit.get(GitConstants.KEY_COMMITTER_NAME));
		assertEquals(commiterEmail, commit.get(GitConstants.KEY_COMMITTER_EMAIL));
	}
}