Example usage for org.json.simple JSONArray toArray

List of usage examples for org.json.simple JSONArray toArray

Introduction

In this page you can find the example usage for org.json.simple JSONArray toArray.

Prototype

public Object[] toArray() 

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

Usage

From source file:org.arkanos.pivotal_analytics.pivotal.Project.java

/**
 * Downloads and constructs a given project.
 * /*from  w  ww .  ja  v  a 2 s. c  o  m*/
 * @param projectID specifies Pivotal ID reference to the Project.
 * @param token specifies User API Token from Pivotal.
 */
public Project(int projectID, String token) {
    PivotalAPI api = new PivotalAPI(token);
    String downloaded = api.downloadProject(projectID);
    JSONParser jp = new JSONParser();
    try {
        JSONObject jo = (JSONObject) jp.parse(downloaded);
        String date_start = (String) jo.get("start_date");
        if (date_start == null) {
            iterations_start = new SimpleDateFormat("yyyy-MM-dd").parse("2013-01-01");
        } else {
            iterations_start = new SimpleDateFormat("yyyy-MM-dd").parse(date_start);
        }

        current_iteration = ((Long) jo.get("current_iteration_number")).intValue();

        long size = ((Long) jo.get("iteration_length")).longValue();
        iteration_size = size * 7 * 24 * 60 * 60 * 1000;

        name = (String) jo.get("name");
        company = (Long) jo.get("account_id") + "";

        downloaded = api.downloadUsers(projectID);

        JSONArray ja = (JSONArray) jp.parse(downloaded);

        users = new UserLookup();
        for (Object pm : ja.toArray()) {
            users.addUser((JSONObject) (((JSONObject) pm).get("person")));
        }

        loadStories(projectID, token);
    } catch (ParseException e) {
        System.out.println(
                "[ERROR:ParseException] There was an Exception while parsing Pivotal Project Content, see error logs for stack trace.");
        e.printStackTrace();
    } catch (org.json.simple.parser.ParseException e) {
        System.out.println(
                "[ERROR:ParseException] There was an Exception while parsing Pivotal Project JSON, see error logs for stack trace.");
        e.printStackTrace();
    }
}

From source file:org.arkanos.pivotal_analytics.pivotal.Ticket.java

/**
 * Constructs the Ticket based on an XML node given by the API.
 * //from   www  .  j  a v  a  2  s.  c o m
 * @param jo specifies the ticket information in a JSON object.
 * @param users provides a user lookup table for reading names from IDs.
 */
public Ticket(JSONObject jo, UserLookup users) {
    try {
        this.ID = ((Long) jo.get("id")).intValue();
        this.StoryType = (String) jo.get("story_type");
        this.URL = new URL((String) jo.get("url"));
        if (jo.get("estimate") != null) {
            this.estimate = ((Long) jo.get("estimate")).intValue();
        } else {
            this.estimate = 0;
        }
        this.currentState = (String) jo.get("current_state");
        this.title = (String) jo.get("name");
        this.requestedBy = users.getUser(jo.get("requested_by_id").toString());

        this.ownedBy = null;
        if (jo.get("owner_ids") != null) {
            JSONArray owners = (JSONArray) jo.get("owner_ids");
            for (Object o : owners.toArray()) {
                if (this.ownedBy != null) {
                    this.ownedBy += ",";
                    this.ownedBy += users.getUser(o.toString());
                } else {
                    this.ownedBy = users.getUser(o.toString());
                }
            }
        }

        this.createdAt = DatatypeConverter.parseDateTime((String) jo.get("created_at")).getTime();
        if (currentState.compareTo("accepted") == 0) {
            this.acceptedAt = DatatypeConverter.parseDateTime((String) jo.get("accepted_at")).getTime();
        } else {
            this.acceptedAt = null;
        }

        this.labels = null;
        for (Object l : ((JSONArray) jo.get("labels")).toArray()) {
            if (this.labels != null) {
                this.labels += "," + ((JSONObject) l).get("name");
            } else {
                this.labels = ((JSONObject) l).get("name").toString();
            }

        }
    } catch (MalformedURLException e) {
        System.out.println("Malformed URL. " + (String) jo.get("url"));
        //e.printStackTrace();
    } catch (NullPointerException e) {
        System.out.println("Ticket could not be made, strange null error. Data: " + jo.toJSONString());
        //e.printStackTrace();
    }
}

From source file:org.jaggeryjs.jaggery.app.mgt.TomcatJaggeryWebappsDeployer.java

private static void addSessionCreatedListners(Context context, JSONArray arr) {
    if (arr != null) {
        try {//w  w  w. ja va 2s . com
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext
                    .getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);

            List<String> jsListeners = new ArrayList<String>();

            Object[] scripts = arr.toArray();
            for (Object script : scripts) {

                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);

                jsListeners.add(path);
            }

            servletContext.setAttribute(JaggeryCoreConstants.JS_CREATED_LISTENERS, jsListeners);

        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}

From source file:org.jaggeryjs.jaggery.app.mgt.TomcatJaggeryWebappsDeployer.java

private static void addSessionDestroyedListners(Context context, JSONArray arr) {
    if (arr != null) {
        try {//from  w  w w .  j  a va2 s . c om
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext
                    .getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);

            List<String> jsListeners = new ArrayList<String>();

            Object[] scripts = arr.toArray();
            for (Object script : scripts) {

                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);

                jsListeners.add(path);
            }

            servletContext.setAttribute(JaggeryCoreConstants.JS_DESTROYED_LISTENERS, jsListeners);

        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}

From source file:org.jaggeryjs.jaggery.app.mgt.TomcatJaggeryWebappsDeployer.java

private static void executeScripts(Context context, JSONArray arr) {
    if (arr != null) {
        try {//from  w  w  w .  ja  va  2 s. c  o m
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext
                    .getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);
            ScriptableObject sharedScope = sharedContext.getScope();

            Object[] scripts = arr.toArray();
            for (Object script : scripts) {
                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);
                String[] parts = WebAppManager.getKeys(servletContext.getContextPath(), path, path);
                ScriptCachingContext sctx = new ScriptCachingContext(sharedContext.getTenantId(), parts[0],
                        parts[1], parts[2]);
                sctx.setSecurityDomain(new JaggerySecurityDomain(path, servletContext));
                engine.exec(new ScriptReader(servletContext.getResourceAsStream(path)) {
                    @Override
                    protected void build() throws IOException {
                        try {
                            sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                        } catch (ScriptException e) {
                            throw new IOException(e);
                        }
                    }
                }, sharedScope, sctx);
            }
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}

From source file:org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager.java

private static void executeScripts(Context context, JSONArray arr) {
    if (arr != null) {
        try {//ww w  .j  a  v a2  s  .com
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext
                    .getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);
            ScriptableObject sharedScope = sharedContext.getScope();

            Object[] scripts = arr.toArray();
            for (Object script : scripts) {
                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);
                String[] parts = WebAppManager.getKeys(servletContext.getContextPath(), path, path);
                ScriptCachingContext sctx = new ScriptCachingContext(sharedContext.getTenantDomain(), parts[0],
                        parts[1], parts[2]);
                sctx.setSecurityDomain(new JaggerySecurityDomain(path, servletContext));
                engine.exec(new ScriptReader(servletContext.getResourceAsStream(path)) {
                    @Override
                    protected void build() throws IOException {
                        try {
                            sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                        } catch (ScriptException e) {
                            // throw new IOException(e);
                        }
                    }
                }, sharedScope, sctx);
            }
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}

From source file:org.pentaho.repo.controller.RepositoryBrowserController.java

public LinkedList<String> getRecentSearches() {
    LinkedList<String> recentSearches = new LinkedList<String>();
    try {//  w w w . j  ava2s .c  o  m
        PropsUI props = PropsUI.getInstance();
        String jsonValue = props.getRecentSearches();
        if (jsonValue != null) {
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonValue);

            String login = "file_repository_no_login";
            if (Spoon.getInstance().rep.getUserInfo() != null) {
                login = Spoon.getInstance().rep.getUserInfo().getLogin();
            }
            JSONArray jsonArray = (JSONArray) jsonObject.get(login);
            CollectionUtils.addAll(recentSearches, jsonArray.toArray());
        }
    } catch (Exception e) {
        // Log error in console
    }
    return recentSearches;
}

From source file:org.wso2.carbon.appmgt.impl.dao.AppMDAO.java

public void addWebApp(WebApp app) throws AppManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;//from   w ww  .j  a  va2  s .c om
    String businessOwnerName = app.getBusinessOwner();
    String query = "INSERT INTO APM_APP(APP_PROVIDER, TENANT_ID, APP_NAME, APP_VERSION, CONTEXT, TRACKING_CODE, "
            + "VISIBLE_ROLES, UUID, SAML2_SSO_ISSUER, LOG_OUT_URL,APP_ALLOW_ANONYMOUS, APP_ENDPOINT, TREAT_AS_SITE) "
            + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";

    try {
        String gatewayURLs = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration().getFirstProperty(GATEWAY_URL);
        String[] urlArray = gatewayURLs.split(",");
        String prodURL = urlArray[0];
        String logoutURL = app.getLogoutURL();
        if (logoutURL != null && !"".equals(logoutURL.trim())) {
            logoutURL = prodURL.concat(app.getContext()).concat("/" + app.getId().getVersion() + "/")
                    .concat(logoutURL);
        }

        int tenantId;
        String tenantDomain = MultitenantUtils
                .getTenantDomain(AppManagerUtil.replaceEmailDomainBack(app.getId().getProviderName()));
        try {
            tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            throw new AppManagementException(
                    "Error in retrieving Tenant Information while adding app :" + app.getId().getApiName(), e);
        }

        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        prepStmt = connection.prepareStatement(query, new String[] { "APP_ID" });
        prepStmt.setString(1, AppManagerUtil.replaceEmailDomainBack(app.getId().getProviderName()));
        prepStmt.setInt(2, tenantId);
        prepStmt.setString(3, app.getId().getApiName());
        prepStmt.setString(4, app.getId().getVersion());
        prepStmt.setString(5, app.getContext());
        prepStmt.setString(6, app.getTrackingCode());
        prepStmt.setString(7, app.getVisibleRoles());
        prepStmt.setString(8, app.getUUID());
        prepStmt.setString(9, app.getSaml2SsoIssuer());
        prepStmt.setString(10, logoutURL);
        prepStmt.setBoolean(11, app.getAllowAnonymous());
        prepStmt.setString(12, app.getUrl());
        prepStmt.setBoolean(13, Boolean.parseBoolean(app.getTreatAsASite()));

        prepStmt.execute();

        rs = prepStmt.getGeneratedKeys();
        int webAppId = -1;
        if (rs.next()) {
            webAppId = rs.getInt(1);
        }
        addURLTemplates(webAppId, app, connection);
        //Set default versioning details
        saveDefaultVersionDetails(app, connection);

        recordAPILifeCycleEvent(app.getId(), null, APIStatus.CREATED,
                AppManagerUtil.replaceEmailDomainBack(app.getId().getProviderName()), connection);
        if (app.getPolicyPartials() != null && !app.getPolicyPartials().isEmpty()) {
            JSONArray policyPartialIdList = (JSONArray) JSONValue.parse(app.getPolicyPartials());
            saveApplicationPolicyPartialsMappings(connection, webAppId, policyPartialIdList.toArray());
        }

        //save policy groups app wise
        if (app.getPolicyGroups() != null && !app.getPolicyGroups().isEmpty()) {
            JSONArray policyGroupIdList = (JSONArray) JSONValue.parse(app.getPolicyGroups());
            saveApplicationPolicyGroupsMappings(connection, webAppId, policyGroupIdList.toArray());
        }

        //save java policies app wise
        if (app.getJavaPolicies() != null && !app.getJavaPolicies().isEmpty()) {
            JSONArray javaPolicyIdList = (JSONArray) JSONValue.parse(app.getJavaPolicies());
            saveJavaPolicyMappings(connection, webAppId, javaPolicyIdList.toArray());
        }

        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                log.error("Failed to rollback when adding the WebApp: " + app.getId() + " to the database", e);
            }
        }
        handleException("Error while adding the WebApp: " + app.getId() + " to the database", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
    }
}

From source file:org.wso2.carbon.appmgt.impl.dao.AppMDAO.java

public void updateAPI(WebApp api, String authorizedAdminCookie) throws AppManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;//from w  ww  . j a  va 2 s.com
    String query = "UPDATE APM_APP "
            + " SET CONTEXT = ?, LOG_OUT_URL  = ?, APP_ALLOW_ANONYMOUS = ?, APP_ENDPOINT = ? ,TREAT_AS_SITE = ? ,"
            + " VISIBLE_ROLES = ? WHERE APP_PROVIDER = ? AND APP_NAME = ? AND APP_VERSION = ? ";

    String gatewayURLs = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration().getFirstProperty(GATEWAY_URL);

    String[] urlArray = gatewayURLs.split(",");
    String prodURL = urlArray[0];
    String logoutURL = api.getLogoutURL();
    String logoutURLStart = prodURL.concat(api.getContext()).concat("/" + api.getId().getVersion());
    if (logoutURL.endsWith("/")) {
        logoutURL = logoutURLStart.concat(logoutURL);
    } else {
        logoutURL = logoutURLStart.concat("/" + logoutURL);
    }

    try {
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);

        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, api.getContext());
        prepStmt.setString(2, logoutURL);
        prepStmt.setBoolean(3, api.getAllowAnonymous());
        prepStmt.setString(4, api.getUrl());
        prepStmt.setBoolean(5, Boolean.parseBoolean(api.getTreatAsASite()));
        prepStmt.setString(6, api.getVisibleRoles());
        prepStmt.setString(7, AppManagerUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        prepStmt.setString(8, api.getId().getApiName());
        prepStmt.setString(9, api.getId().getVersion());
        prepStmt.execute();

        int webAppId = getWebAppIdFromUUID(api.getUUID(), connection);

        //Update and persist policy partial info
        if (api.getPolicyPartials() != null) {
            JSONArray policyPartialIdList = (JSONArray) JSONValue.parse(api.getPolicyPartials());

            //Remove existing updated entitlement policies from IDP
            removeApplicationsEntitlementPolicies(webAppId, connection, authorizedAdminCookie);
        }

        if (api.getPolicyGroups() != null && !api.getPolicyGroups().isEmpty()) {
            JSONArray policyGroupIdList = (JSONArray) JSONValue.parse(api.getPolicyGroups());
            updatePolicyGroups(webAppId, policyGroupIdList.toArray(), connection);
        }

        //update java policy handlers
        if (api.getJavaPolicies() != null && !api.getJavaPolicies().isEmpty()) {
            JSONArray javaPolicyIdList = (JSONArray) JSONValue.parse(api.getJavaPolicies());
            updateJavaPolicies(webAppId, javaPolicyIdList.toArray(), connection);
        }

        updateURLTemplates(api, connection);

        //if selected as default version save entry
        saveDefaultVersionDetails(api, connection);

        connection.commit();

    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                log.error("Failed to rollback when updating the WebApp" + api.getId() + " in the database", e);
            }
        }
        handleException("Error while updating the WebApp: " + api.getId() + " in the database", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
    }
}

From source file:tk.itstake.steakgui.util.ItemStackConverter.java

public static ItemStack convert(JSONObject json) {
    ItemStack item = new ItemStack(Material.valueOf(((String) json.get("type")).toUpperCase()),
            (int) (long) json.get("amount"), (short) (long) json.get("data"));
    if (json.containsKey("meta")) {
        JSONObject metajson = (JSONObject) json.get("meta");
        ItemMeta meta = item.getItemMeta();
        if (metajson.containsKey("name")) {
            meta.setDisplayName((String) metajson.get("name"));
        }/*from  www  .j  a  v  a 2  s.c o  m*/
        if (metajson.containsKey("lore")) {
            meta.setLore((List<String>) metajson.get("lore"));
        }
        if (metajson.containsKey("enchantments")) {
            JSONObject enchantment = (JSONObject) metajson.get("enchantments");
            for (Object enchant : enchantment.keySet()) {
                Integer level = (int) (long) enchantment.get(enchant);
                meta.addEnchant(Enchantment.getByName((String) enchant), level, true);
            }
        }
        if (metajson.containsKey("flags")) {
            try {
                Class.forName("org.bukkit.inventory.ItemFlag");
                JSONArray flagobj = (JSONArray) metajson.get("flags");
                org.bukkit.inventory.ItemFlag[] flaglist = new org.bukkit.inventory.ItemFlag[flagobj.size()];
                int ai = 0;
                for (Object flag : flagobj.toArray()) {
                    flaglist[ai] = org.bukkit.inventory.ItemFlag.valueOf((String) flag);
                    ai++;
                }
                meta.addItemFlags(flaglist);
            } catch (ClassNotFoundException e) {
            }
        }
        item.setItemMeta(meta);
    }
    return item;
}