001/*
002 * ModeShape (http://www.modeshape.org)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.modeshape.jdbc.rest;
017
018import java.util.ArrayList;
019import java.util.Iterator;
020import java.util.List;
021import org.codehaus.jettison.json.JSONArray;
022import org.codehaus.jettison.json.JSONObject;
023
024/**
025 * POJO which can unmarshal the {@link org.codehaus.jettison.json.JSONObject} representation of a list of workspaces coming
026 * from a ModeShape REST Service.
027 *
028 * @author Horia Chiorean (hchiorea@redhat.com)
029 */
030public final class Workspaces implements Iterable<String> {
031
032    private final List<String> workspaces;
033
034    /**
035     * Creates a new instance which wraps a JSON response.
036     *
037     * @param object a {@link org.codehaus.jettison.json.JSONObject}; never {@code null}
038     */
039    protected Workspaces( JSONObject object ) {
040        try {
041            if (!object.has("workspaces")) {
042                throw new IllegalArgumentException("Invalid JSON object: " + object);
043            }
044            JSONArray workspacesJSON = object.getJSONArray("workspaces");
045            this.workspaces = new ArrayList<>(workspacesJSON.length());
046            for (int i = 0; i < workspacesJSON.length(); i++) {
047                JSONObject workspaceJSON = workspacesJSON.getJSONObject(i);
048                this.workspaces.add(workspaceJSON.getString("name"));
049            }
050        } catch (Exception e){
051            throw new RuntimeException(e);
052        }
053    }
054
055    @Override
056    public Iterator<String> iterator() {
057        return workspaces.iterator();
058    }
059
060    /**
061     * Returns the list of workspaces.
062     *
063     * @return a list of workspace names; never {@code null}
064     */
065    public List<String> getWorkspaces() {
066        return workspaces;
067    }
068}