Example usage for com.google.gson JsonObject getAsJsonObject

List of usage examples for com.google.gson JsonObject getAsJsonObject

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonObject.

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:de.behrfried.wikianalyzer.wawebapp.server.service.JsonWikiAccess.java

License:Apache License

@Override
public CriterionInfo getCriterionInfo(List<TitleOrCategory> titlesOrCategories)
        throws CriterionNotFoundException {

    final Map<String, Map<String, Integer>> users = new HashMap<String, Map<String, Integer>>();
    final Map<String, List<Integer>> pages = new HashMap<String, List<Integer>>();
    for (final TitleOrCategory toc : titlesOrCategories) {
        if (toc.isCategory()) {
            String nextpage = "";
            do {//from   w  w w. j  a  va2  s.co m
                String resp = this.requester.getResult(this.convertRequest(
                        "action=query&format=json&list=categorymembers&cmlimit=500&cmtitle=Kategorie:"
                                + toc.getTitle() + "&cmstartsortkey=" + nextpage));

                final JsonObject root = this.parser.parse(resp).getAsJsonObject();

                final JsonArray jsonPagesArr = root.getAsJsonObject("query").getAsJsonArray("categorymembers");

                final List<Integer> pageids = new ArrayList<Integer>(jsonPagesArr.size());
                for (final JsonElement jsonElem : jsonPagesArr) {
                    pageids.add(jsonElem.getAsJsonObject().getAsJsonPrimitive("pageid").getAsInt());
                }
                pages.put(toc.getTitle(), pageids);

                nextpage = "";
                if (root.has("query-continue")) {
                    nextpage = root.getAsJsonObject("query-continue").getAsJsonObject("categorymembers")
                            .getAsJsonPrimitive("cmcontinue").getAsString();
                }

            } while (!nextpage.isEmpty());
        } else {
            final List<Integer> pageids = new ArrayList<Integer>(1);
            pageids.add(this.getPageId(toc.getTitle()));
            pages.put(toc.getTitle(), pageids);
            this.getPageId(toc.getTitle());
        }
    }

    /*
     * iterate all criterions
     */
    // User, Title, Commits
    for (final Map.Entry<String, List<Integer>> entry : pages.entrySet()) {

        for (final int pageid : entry.getValue()) {
            /*
            * iterate all revisions
            */
            int lastRev = 0;
            while (lastRev != -1) {
                final String response1 = this.requester
                        .getResult(this.convertRequest("action=query&format=json&prop=revisions&rvprop=user"
                                + "&rvlimit=500&rvdir=newer&rvexcludeuser=127.0.0.1&pageids=" + pageid
                                + "&rvstartid=" + lastRev + "&continue="));

                final JsonObject root = this.parser.parse(response1).getAsJsonObject();
                final JsonObject page = root.getAsJsonObject("query").getAsJsonObject("pages")
                        .getAsJsonObject(pageid + "");

                if (!page.has("revisions")) {
                    break;
                }

                final JsonArray jsonRevArr = page.getAsJsonArray("revisions");
                for (final JsonElement jsonElem : jsonRevArr) {
                    final String user = jsonElem.getAsJsonObject().getAsJsonPrimitive("user").getAsString();
                    if (!users.containsKey(user)) {
                        final Map<String, Integer> title = new HashMap<String, Integer>();
                        users.put(user, title);
                    }
                    final Map<String, Integer> title = users.get(user);
                    if (!title.containsKey(entry.getKey())) {
                        title.put(entry.getKey(), 0);
                    }
                    title.put(entry.getKey(), title.get(entry.getKey()) + 1);

                }

                lastRev = root.has("continue")
                        ? root.getAsJsonObject("continue").getAsJsonPrimitive("rvcontinue").getAsInt()

                        :

                        -1;
            }
        }

    }

    final List<CriterionInfo.User> userList = new ArrayList<CriterionInfo.User>(users.size());
    outer: for (final Map.Entry<String, Map<String, Integer>> entry : users.entrySet()) {

        final CriterionInfo.User user = new CriterionInfo.User(entry.getKey(), 1);
        for (final TitleOrCategory toc : titlesOrCategories) {
            if (!entry.getValue().containsKey(toc.getTitle())) {
                continue outer;
            }
            user.setMatch(user.getMatch() * entry.getValue().get(toc.getTitle()));
        }
        userList.add(user);
    }
    outer: for (int i = 0; i < userList.size(); i++) {
        final CriterionInfo.User us = userList.get(i);
        final String userBotRsp = this.requester.getResult(this.convertRequest(
                "action=query&format=json&list=users&usprop=groups|blockinfo&ususers=" + us.getUserName()));
        final JsonObject usersJsonObj = this.parser.parse(userBotRsp).getAsJsonObject().getAsJsonObject("query")
                .getAsJsonArray("users").get(0).getAsJsonObject();
        if (usersJsonObj.has("blockid")) {
            userList.remove(i);
            continue;
        }
        if (!usersJsonObj.has("groups")) {
            userList.remove(i);
            continue;
        }
        final JsonArray groupsJsonArr = usersJsonObj.getAsJsonArray("groups");
        for (JsonElement jsonElement : groupsJsonArr) {
            if ("bot".equals(jsonElement.getAsJsonPrimitive().getAsString())) {
                userList.remove(i);
                continue outer;
            }
        }
        us.setMatch(us.getMatch()
                * (Double) this.calcReputation(us.getUserName(), users.get(us.getUserName()).size(), false)[0]);
    }
    Collections.sort(userList, new Comparator<CriterionInfo.User>() {
        @Override
        public int compare(CriterionInfo.User user, CriterionInfo.User user2) {
            return (int) Math.signum(user2.getMatch() - user.getMatch());
        }
    });

    return new CriterionInfo(userList);
}

From source file:de.craftolution.craftoplugin4.modules.bot.result.Result.java

License:MIT License

public static Result parse(ResultPacket resultPacket) {
    JsonObject content = resultPacket.getContent();

    // Stats//from  www  .j av  a 2 s.  c o m
    JsonObject statsJson = content.getAsJsonObject("stats");
    long processTime = statsJson.get("process-time").getAsLong();
    int processedNodeCount = statsJson.get("processed-node-count").getAsInt();
    int dismissedNodeCount = statsJson.get("dismissed-node-count").getAsInt();

    // Response
    JsonObject responseJson = content.getAsJsonObject("response");
    String responseText = responseJson.get("text").getAsString().trim(); // TODO: Fix trailing whitespace

    // Entries
    JsonObject entries = content.getAsJsonObject("entries");
    List<ResultEntry> entryList = Lists.newArrayList();
    Set<Entry<String, JsonElement>> set = entries.entrySet();
    for (Entry<String, JsonElement> entry : set) {
        JsonObject obj = entry.getValue().getAsJsonObject();
        ResultEntry resultEntry = new ResultEntry();

        resultEntry.nodeId = entry.getKey();
        resultEntry.question = obj.get("node").getAsJsonObject().get("question").getAsString();
        resultEntry.probability = obj.get("probability").getAsFloat();

        entryList.add(resultEntry);
    }

    // Process chain
    //JsonObject processChain = new JsonObject();

    Result result = new Result(responseText, processTime, processedNodeCount, dismissedNodeCount, entryList);
    return result;
}

From source file:de.elomagic.vaadin.addon.speechrecognition.SpeechRecognitionResultDeserializer.java

License:Apache License

@Override
public SpeechRecognitionResult deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    JsonObject o = json.getAsJsonObject();

    int length = o.get("length").getAsInt();
    SpeechRecognitionResult results = new SpeechRecognitionResult();
    for (int i = 0; i < length; i++) {
        JsonObject resultObject = o.getAsJsonObject(Integer.toString(i));
        results.add((SpeechRecognitionAlternative) context.deserialize(resultObject,
                SpeechRecognitionAlternative.class));
    }/*from w w  w  .  j  a  v  a  2s.  co  m*/

    return results;
}

From source file:de.elomagic.vaadin.addon.speechrecognition.SpeechRecognitionResultsDeserializer.java

License:Apache License

@Override
public SpeechRecognitionResults deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    JsonObject o = json.getAsJsonObject();

    int length = o.get("length").getAsInt();
    SpeechRecognitionResults results = new SpeechRecognitionResults();
    for (int i = 0; i < length; i++) {
        JsonObject resultObject = o.getAsJsonObject(Integer.toString(i));
        results.add((SpeechRecognitionResult) context.deserialize(resultObject, SpeechRecognitionResult.class));
    }/*from www.  j  a v a 2  s  .  c  o  m*/

    return results;
}

From source file:diuf.unifr.ch.first.xwot.rxtx.ArduinoCommunication.java

public JsonObject read(String element) {
    JsonElement jElement;/*  ww w.j  a  v a 2  s. c  o m*/
    try {
        jElement = new JsonParser().parse(getConnection().getLine());
    } catch (NullPointerException e) {
        logger.info("error during communication with arduino. No informations from hardware");
        return null;
    } catch (JsonSyntaxException e) {
        logger.info("error during communication with arduino. Unable to parse json");
        return null;
    }
    JsonObject jObject = jElement.getAsJsonObject();
    if (!jObject.has(element)) {
        logger.debug("'" + element + "' not found in the json string: " + jObject.toString());
        return null;
    }
    return jObject.getAsJsonObject(element);
}

From source file:dmadmin.API.java

License:Open Source License

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from  ww w . j av  a2  s.  c o m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //
    // Handles API interface (D) = documented
    //
    // (D) API/login?user=admin&pass=admin
    // (D) API/environments?all=y|n[&application=appname|appid] (lists all environments - all = show sub-domains)
    // (D) API/environment/envid|envname (lists an individual environment)
    // (D) API/applications?all=y|n (lists all applications - all = show sub-domains)
    // (D) API/application/appid|appname (lists an individual application)
    // (D) API/application/appid|appname?[latest=y&][branch=<name>] (gets latest app version, on branch if specified)
    // (D) API/servers?all=y|n[&environment=envname|envid]
    // (D) API/server/<servername>
    // (D) API/component/compid|compname?[latest=y&][branch=<name>] (gets latest comp version, on branch if specified)
    // (D) API/calendar?[env=<env>&app=<app>][&start=<start>&end=<end>]
    // API/newappver/appid|appname[&taskname=<name>]
    // API/newcompver/compid|compname
    // API/replace/application/component/newcomponent
    // (D) API/deploy/appname?environment=envname&wait=Y|N
    // (D) API/log?id=nnn or...
    // (D) API/log/nnn
    // objname can be fully qualified to differentiate between objects with same name in different domains
    // (D) API/setvar/<objtype>/<objname>?name=<name>&value=<value>
    // getvar gets either a single value or all name/value pairs set against an object
    // (D) API/getvar/<objtype>/<objname>/[&name=<name>]
    // (D) API/del/user/name
    // (D) API/new/user/name[?domain=<domain>&realname=<real name>&ldap=<ldap datasource>&tel=<tel no>&email=<email>&cpw=Y|N&locked=Y|N&pw=<password>]
    // (D) API/mod/user/name[?domain=<domain>&realname=<real name>&ldap=<ldap datasource>&tel=<tel no>&email=<email>&cpw=Y|N&locked=Y|N&pw=<password>]
    // (D) API/del/server/name
    // (D) API/new/server/name[?domain=<domain>&env=<environment>&<type=<type>&hostname=<hostname>&protocol=<protocol>&basedir=<basedir>&credname=<credname>&autoping=Y|N&automd5=Y|N&comptype=<list of comp
    // types>&pinginterval=<pinginterval>&pingstart=<starttime>&pingend=<pingend>&pingtemplate=<tmpl>&md5template=<tmpl>&sshport=<port>
    // (D) API/mod/server/name/ " " "
    // API/del/environment/name
    // API/new/environment/name[?domain=<domain>&summary=<summary>]
    // API/mod/environment/name/ " "
    // API/new/appver/appname[?name=<vername>]
    // API/new/compver/compname[?name=<vername>]
    // (D) API/clone/server/<servername>/<newname>[?domain=dom]
    // (D) API/clone/environment/<envname>/<newname?[?domain=dom]
    // (D) API/assign/server/<servername>/<environmentname>
    // (D) API/assign/application/<appname>/<environmentname>
    // (D) API/assign/user/<username>/<groupname>
    // (D) API/unassign/server/<servername>/<environmentname>
    // (D) API/unassign/application/<appname>/<environmentname>
    // (D) API/unassign/user/<username>/<groupname>
    // (D) API/approve/<appname>?taskname=<name>[&notes=<notes>&approve=Y|N]
    // API/buildid/<compname>/<buildid>
    // API/buildnotify/buildurl=<url>

    try (DMSession so = DMSession.getInstance(request)) {

        JSONObject obj = new JSONObject();

        int deploymentid = 0; // for deployments

        PrintWriter out = response.getWriter();
        boolean delop = false;

        try {
            String path = request.getPathInfo();
            if (path.length() > 1 && (path.charAt(0) == '/')) {
                path = path.substring(1);
            }

            String[] elements = path.split("/");
            // System.out.println("elements[0] = " + elements[0]);
            for (int i = 1; i < elements.length; i++) {
                System.out.println("Before elements[" + i + "]=[" + elements[i] + "]");
                elements[i] = java.net.URLDecoder.decode(elements[i], "UTF-8");
                System.out.println("After elements[" + i + "]=[" + elements[i] + "]");
            }

            if (elements.length < 1) {
                throw new ApiException("Invalid request path");
            }

            String user = request.getParameter("user");
            String pass = request.getParameter("pass");
            String provider = request.getParameter("provider");
            String a = request.getParameter("all");
            boolean all = (a == null) ? false : (a.charAt(0) == 'y' || a.charAt(0) == 'Y');

            response.setContentType("application/json");

            if (provider == null)
                provider = "";

            if (elements[0].equals("login")) {
                if (user == null) {
                    throw new ApiException("user must be specified");
                }
                if (pass == null) {
                    throw new ApiException("password must be specified");
                }

                if (provider != null && provider.length() > 0) {
                    String j = so.jsonGetRequest(pass, provider);
                    if (j == null)
                        throw new ApiException("Login failed");

                    if (provider.equals("github")) {
                        JsonObject json = new JsonParser().parse(j).getAsJsonObject();
                        String u = json.getAsJsonObject("data").get("alias").getAsString();

                        if (!user.equals(u))
                            throw new ApiException("Login failed");
                    }
                    pass = "";
                } else {
                    if (so.Login(user, pass).getExceptionType() != LoginExceptionType.LOGIN_OKAY) {
                        throw new ApiException("Login failed");
                    }
                }
                obj.add("success", true);

                HttpSession session = request.getSession();
                session.setAttribute("session", so);
                Cookie loggedinUser = new Cookie("p1", user);
                Cookie loggedinPw = new Cookie("p2", pass);
                loggedinUser.setPath("/");
                loggedinPw.setPath("/");

                response.addCookie(loggedinUser);
                response.addCookie(loggedinPw);
                return; // finally will send result
            }

            if (user != null) {
                if (pass == null)
                    throw new ApiException("password must be specified");
                if (so.Login(user, pass).getExceptionType() != LoginExceptionType.LOGIN_OKAY) {
                    throw new ApiException("Login failed");
                }
            } else {
                // Not doing SQL - check if there's an open session with an ID of 0. If so,
                // clear the session.
                if (so != null && so.GetUserID() == 0) {
                    // Outstanding SQL Query session - remove the session to prevent it being used
                    request.getSession().invalidate();
                }
            }

            // END TEMP

            if (so == null) {
                throw new ApiException("Not logged in");
            }

            if (elements[0].equals("deploy")) {
                // Go invoke a deployment
                System.out.println("API: deploy");
                deploymentid = doDeployment(so, elements, request);
            } else if (elements[0].equals("environment")) {
                System.out.println("API: Environment");
                if (elements.length == 2) {
                    Environment env = getEnvironmentFromNameOrID(so, elements[1]);
                    System.out.println(env.getName());
                    obj.add("result", assembleJSONForEnvironment(so, env));
                } else {
                    throw new ApiException("Path contains wrong number of elements");
                }
            } else if (elements[0].equals("environments")) {
                System.out.println("DOING environments");
                if (elements.length == 1) {
                    System.out.println("length is 1");
                    String appname = request.getParameter("application");
                    JSONArray result = new JSONArray();
                    if (appname != null) {
                        System.out.println("Doing envlist for application");
                        // Getting environments for application
                        Application app = getApplicationFromNameOrID(so, appname);
                        System.out.println("Application is " + app.getName());
                        List<Environment> envs = so.getEnvironmentsForApplication(app, app.getDomain());
                        System.out.println("environment list is size " + envs.size());
                        for (Environment e : envs) {
                            Environment env = so.getEnvironment(e.getId(), true);
                            JSONObject je = assembleJSONForEnvironment(so, env);
                            result.add(je);
                        }
                    } else {
                        System.out.println("Application is null");
                        List<DMObject> envs = so.getDMObjects(ObjectType.ENVIRONMENT, all);
                        System.out.println("environment list is size " + envs.size());
                        for (DMObject env : envs) {
                            JSONObject je = assembleJSONForEnvironment(so, (Environment) env);
                            result.add(je);
                        }
                    }
                    obj.add("result", result);
                } else {
                    throw new ApiException("Path contains too many elements");
                }
            } else if (elements[0].equals("components")) {
                if (elements.length == 1) {
                    System.out.println("length is 1");
                    String appname = request.getParameter("application");
                    JSONArray result = new JSONArray();
                    if (appname != null) {
                        System.out.println("Doing complist for application");
                        // Getting components for application
                        Application app = getApplicationFromNameOrID(so, appname);
                        System.out.println("Application is " + app.getName());
                        List<Component> comps = so.getComponents(ObjectType.APPLICATION, app.getId(), false);
                        System.out.println("component list is size " + comps.size());
                        for (Component c : comps) {
                            Component comp = so.getComponent(c.getId(), true);
                            JSONObject je = assembleJSONForComponent(so, comp);
                            result.add(je);
                        }
                    } else {
                        System.out.println("Application is null");
                        List<DMObject> comps = so.getDMObjects(ObjectType.COMPONENT, all);
                        System.out.println("component list is size " + comps.size());
                        for (DMObject comp : comps) {
                            JSONObject je = assembleJSONForComponent(so, (Component) comp);
                            result.add(je);
                        }
                    }
                    obj.add("result", result);
                }
            } else if (elements[0].equals("component")) {
                System.out.println("API: component");
                if (elements.length == 2) {
                    Component comp = getComponentFromNameOrID(so, elements[1]);
                    System.out.println(comp.getName());
                    // Check for "latest" and "branch" options
                    String lstr = request.getParameter("latest");
                    String branchname = request.getParameter("branch");
                    boolean latest = (lstr != null && lstr.equalsIgnoreCase("Y"));
                    if (latest) {
                        Component lcomp = so.getLatestVersion(comp, branchname);
                        if (lcomp != null) {
                            obj.add("result", assembleJSONForComponent(so, lcomp));
                        } else {
                            throw new ApiException("No Component Found");
                        }
                    } else {
                        obj.add("result", assembleJSONForComponent(so, comp));
                    }
                } else {
                    throw new ApiException("Path contains wrong number of elements");
                }
            } else if (elements[0].equals("application")) {
                System.out.println("API: Application");
                if (elements.length == 2) {
                    Application app = getApplicationFromNameOrID(so, elements[1]);
                    System.out.println(app.getName());
                    // Check for "latest" and "branch" options
                    String lstr = request.getParameter("latest");
                    String branchname = request.getParameter("branch");
                    boolean latest = (lstr != null && lstr.equalsIgnoreCase("Y"));
                    if (latest) {
                        Application lapp = so.getLatestVersion(app, branchname);
                        if (lapp != null) {
                            obj.add("result", assembleJSONForApplication(so, lapp));
                        } else {
                            throw new ApiException("No Application Found");
                        }
                    } else {
                        obj.add("result", assembleJSONForApplication(so, app));
                    }
                } else {
                    throw new ApiException("Path contains wrong number of elements");
                }

            } else if (elements[0].equals("credential")) {
                System.out.println("API: Credential");
                if (elements.length == 2) {
                    Credential cred = getCredentialFromNameOrID(so, elements[1]);
                    System.out.println(cred.getName());
                    // Check for "latest" and "branch" options
                    obj.add("result", assembleJSONForCredential(so, cred));
                } else {
                    throw new ApiException("Path contains wrong number of elements");
                }
            } else if (elements[0].equals("domains")) {
                System.out.println("API: domains");
                String domlist = so.getDomainList();
                System.out.println(domlist);
                obj.add("result", domlist);
            } else if (elements[0].equals("server")) {
                System.out.println("API: Server");
                if (elements.length == 2) {
                    Server srv = getServerFromNameOrID(so, elements[1]);
                    System.out.println(srv.getName());
                    // Check for "latest" and "branch" options
                    obj.add("result", assembleJSONForServer(so, srv));
                } else {
                    throw new ApiException("Path contains wrong number of elements");
                }
            } else if (elements[0].equals("testserver")) {
                System.out.println("API: TestServer");
                if (elements.length == 2) {
                    Server srv = getServerFromNameOrID(so, elements[1]);
                    System.out.println(srv.getName());
                    // Check for "latest" and "branch" options
                    obj.add("result", assembleJSONForTestServer(so, srv));
                } else {
                    throw new ApiException("Path contains wrong number of elements");
                }
            } else if (elements[0].equals("applications")) {
                System.out.println("DOING applications");
                if (elements.length == 1) {
                    System.out.println("length is 1");
                    List<DMObject> apps = so.getDMObjects(ObjectType.APPLICATION, all);
                    System.out.println("application list is size " + apps.size());
                    JSONArray result = new JSONArray();
                    for (DMObject dob : apps) {
                        Application app = (Application) dob;
                        JSONObject je = new JSONObject();
                        je.add("id", app.getId());
                        je.add("name", app.getName());
                        je.add("domain", app.getDomain().getFullDomain());
                        je.add("parentid", app.getParentId());
                        je.add("predecessorid", app.getPredecessorId());
                        je.add("summary", app.getSummary());
                        DMObject owner = app.getOwner();
                        if (owner != null) {
                            if (owner.getObjectType() == ObjectType.USER)
                                je.add("owneruser", owner.getName());
                            if (owner.getObjectType() == ObjectType.USERGROUP)
                                je.add("ownergroup", owner.getName());
                        }
                        result.add(je);
                    }
                    obj.add("result", result);
                } else {
                    throw new ApiException("Path contains too many elements");
                }
            } else if (elements[0].equals("domain")) {
                Domain domain = getDomainFromNameOrID(so, elements[1]);
                if (domain == null) {
                    throw new ApiException("Could not find domain");
                } else {
                    obj.add("result", assembleJSONForDomain(so, domain));
                }
            } else if (elements[0].equals("user")) {
                User u = this.getUserFromNameOrID(so, elements[1]);
                if (u == null) {
                    throw new ApiException("Could not find user");
                } else {
                    obj.add("result", assembleJSONForUser(so, u));
                }
            } else if (elements[0].equals("approve")) {
                // Approving an application
                if (elements.length == 2) {
                    String approve = request.getParameter("approve");
                    Application app = getApplicationFromNameOrID(so, elements[1]);
                    Task t = null;
                    String taskname = request.getParameter("taskname");
                    if (taskname == null)
                        taskname = request.getParameter("task");
                    if (taskname == null) {
                        // task not specified - find one
                        t = so.getTaskByType(app.getDomain(), TaskType.APPROVE);
                        if (t == null)
                            throw new ApiException("Could not find appropriate Approve Task");
                    } else {
                        // task specified - use that
                        System.out.println("Looking up task " + taskname);
                        try {
                            t = so.getTaskByName(taskname); // throws exception if not found or no access
                            if (t.getTaskType() != TaskType.APPROVE)
                                throw new ApiException("Specified task is not an Approve task");
                        } catch (Exception ex) {
                            throw new ApiException(ex.getMessage());
                        }
                    }
                    TaskApprove tap = so.getTaskApprove(t.getId());
                    if (tap != null) {
                        tap.setApplication(app);
                        if (approve != null && approve.equalsIgnoreCase("n")) {
                            tap.setApproved(false);
                        } else {
                            tap.setApproved(true);
                        }
                        String notes = request.getParameter("notes");
                        if (notes != null) {
                            tap.setText(notes);
                        } else {
                            tap.setText("");
                        }
                        if (tap.run() == false) {
                            throw new ApiException("Approval Task Failed: " + tap.getOutput());
                        }
                    } else {
                        throw new ApiException("Cannot get approve task " + t.getId());
                    }
                } else {
                    throw new ApiException("Path contains too many elements");
                }
            } else if (elements[0].equals("newappver")) {
                // Creating a new application version.
                System.out.println("API: newappver");
                if (elements.length == 2) {
                    Application newapp = newAppVersion(so, elements[1], request);
                    obj.add("result", assembleJSONForApplication(so, newapp));
                } else {
                    throw new ApiException("Path contains wrong number of elements");
                }
            } else if (elements[0].equals("newcompver")) {
                System.out.println("DOING newcompver");
                if (elements.length == 2) {
                    Component newComp = newCompVersion(so, elements[1], request);
                    obj.add("result", assembleJSONForComponent(so, newComp));
                } else {
                    throw new ApiException("Path contains too many elements");
                }
            } else if (elements[0].equals("replace")) {
                // API/replace/application/component/newcomponent
                if (elements.length == 4) {
                    Application app = getApplicationFromNameOrID(so, elements[1]);
                    Component oldcomp = getComponentFromNameOrID(so, elements[2]);
                    Component newcomp = getComponentFromNameOrID(so, elements[3]);
                    System.out.println("Replacing component " + oldcomp.getId() + " with " + newcomp.getId()
                            + " for app " + app.getId());
                    so.applicationReplaceComponent(app.getId(), oldcomp.getId(), newcomp.getId(), false);
                } else {
                    throw new ApiException("Path contains invalid number of elements");
                }

            } else if (elements[0].equals("setaction")) {

                System.out.println("DOING setaction");
                if (elements.length == 3) {
                    String objtype = elements[1];
                    String objname = elements[2];

                    if (objtype.equals("component")) {
                        Component comp = getComponentFromNameOrID(so, objname);
                        String actiontype = request.getParameter("actiontype");
                        String actionname = request.getParameter("actionname");
                        Action action = getActionFromNameOrID(so, actionname);

                        if (actiontype.equals("pre"))
                            comp.setPreAction(action);
                        else if (actiontype.equals("post"))
                            comp.setPostAction(action);
                        else
                            comp.setCustomAction(action);

                        so.updateComponentAction(comp);
                    } else if (objtype.equals("application")) {
                        Application app = getApplicationFromNameOrID(so, objname);
                        String actiontype = request.getParameter("actiontype");
                        String actionname = request.getParameter("actionname");
                        Action action = getActionFromNameOrID(so, actionname);

                        if (actiontype.equals("pre"))
                            app.setPreAction(action);
                        else if (actiontype.equals("post"))
                            app.setPostAction(action);
                        else
                            app.setCustomAction(action);

                        so.updateApplicationAction(app);
                    }
                }
            } else if (elements[0].equals("setvar")) {

                System.out.println("DOING setvar");
                if (elements.length == 3) {
                    String objtype = elements[1];
                    String objname = elements[2];
                    String varname = request.getParameter("name");
                    String varval = request.getParameter("value");
                    if (varname == null)
                        throw new ApiException("name not specified");
                    AttributeChangeSet acs = new AttributeChangeSet();
                    DMAttribute attr = new DMAttribute();
                    attr.setName(varname);
                    attr.setValue(varval != null ? varval : "");
                    acs.addChanged(attr);

                    for (int i = 1; i < 100; i++) {
                        varname = request.getParameter("name" + i);
                        varval = request.getParameter("value" + i);
                        if (varname == null)
                            break;

                        attr = new DMAttribute();
                        attr.setName(varname);
                        attr.setValue(varval != null ? varval : "");
                        acs.addChanged(attr);
                    }

                    try {
                        if (objtype.equalsIgnoreCase("environment")) {
                            Environment env = getEnvironmentFromNameOrID(so, objname);
                            so.updateAttributesForObject(env, acs);
                        } else if (objtype.equalsIgnoreCase("application")) {
                            Application app = getApplicationFromNameOrID(so, objname);
                            so.updateAttributesForObject(app, acs);
                        } else if (objtype.equalsIgnoreCase("server")) {
                            Server serv = getServerFromNameOrID(so, objname);
                            ;
                            so.updateAttributesForObject(serv, acs);
                        } else if (objtype.equalsIgnoreCase("component")) {
                            Component comp = getComponentFromNameOrID(so, objname);
                            so.updateAttributesForObject(comp, acs);
                        } else {
                            throw new ApiException("Invalid object type " + objtype);
                        }
                    } catch (RuntimeException ex) {
                        throw new ApiException(ex.getMessage());
                    }
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("getvar")) {
                System.out.println("DOING getvar");
                if (elements.length == 3) {
                    String objtype = elements[1];
                    String objname = elements[2];
                    String reqname = request.getParameter("name");
                    try {
                        List<DMAttribute> atts;
                        if (objtype.equalsIgnoreCase("environment")) {
                            Environment env = getEnvironmentFromNameOrID(so, objname);
                            atts = env.getAttributes();
                        } else if (objtype.equalsIgnoreCase("application")) {
                            Application app = getApplicationFromNameOrID(so, objname);
                            atts = app.getAttributes();
                        } else if (objtype.equalsIgnoreCase("server")) {
                            Server serv = getServerFromNameOrID(so, objname);
                            atts = serv.getAttributes();
                        } else if (objtype.equalsIgnoreCase("component")) {
                            Component comp = getComponentFromNameOrID(so, objname);
                            atts = comp.getAttributes();
                        } else {
                            throw new ApiException("Invalid object type " + objtype);
                        }
                        if (atts != null) {
                            JSONArray as = new JSONArray();
                            for (int i = 0; i < atts.size(); i++) {
                                DMAttribute att = atts.get(i);
                                if (reqname == null || (reqname != null && reqname.equals(att.getName()))) {
                                    JSONObject jo = new JSONObject();
                                    jo.add(att.getName(), att.getValue());
                                    as.add(jo);
                                }
                            }
                            obj.add("attributes", as);
                        }
                    } catch (RuntimeException ex) {
                        throw new ApiException(ex.getMessage());
                    }
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }

            } else if (elements[0].equals("log")) {
                System.out.println("DOING deployment log length=" + elements.length);
                int id = 0;
                try {
                    if (elements.length == 2) {
                        id = Integer.parseInt(elements[1]);
                    } else {
                        String deploylogid = request.getParameter("id");
                        if (deploylogid == null) {
                            throw new ApiException("id not specified");
                        }
                        id = Integer.parseInt(deploylogid);
                    }
                } catch (NumberFormatException ex) {
                    throw new ApiException("id invalid or no access");
                }

                String complete = request.getParameter("checkcomplete");
                if (complete != null && complete.equalsIgnoreCase("Y")) {
                    Deployment dep = so.getDeployment(id, true);
                    if (dep != null)
                        obj.add("iscomplete", dep.isComplete());
                    else
                        obj.add("iscomplete", false);
                } else {
                    if (id == 0 || so.validateDeploymentId(id) == false) {
                        throw new ApiException("id invalid or no access");
                    } else {

                        Deployment dep = so.getDeployment(id, true);
                        //
                        int envid = dep.getEnvironment().getId();
                        int envdomain = so.getEnvironment(envid, true).getDomainId();
                        System.out.println("envdomain=" + envdomain);
                        if (so.ValidDomain(envdomain, false)) {
                            obj.add("id", dep.getId());
                            obj.add("application", dep.getApplication().getName());
                            // obj.add("domain",dep.getDomain().getName());
                            obj.add("environment", dep.getEnvironment().getName());
                            obj.add("exitcode", dep.getExitCode());
                            obj.add("exitstatus", dep.getExitStatus());
                            obj.add("started", dep.getStarted());
                            obj.add("finished", dep.getFinished());
                            obj.add("complete", dep.isComplete());
                            List<DeploymentLogEntry> dl = dep.getLog();
                            obj.add("loglinecount", dl.size());
                            JSONArray logdir = new JSONArray();
                            for (int i = 0; i < dl.size(); i++) {
                                DeploymentLogEntry de = dl.get(i);
                                String logline = de.getLine();
                                logline = logline.replace("\\r", "");
                                logdir.add(logline);
                            }
                            obj.add("logoutput", logdir);
                        } else {
                            throw new ApiException("id invalid or no access");
                        }
                    }
                }
            } else if (elements[0].equals("new")) {
                // Adding a new object
                if (elements.length == 3) {
                    if (elements[1].equals("user"))
                        AddUser(so, elements[2], request);
                    else if (elements[1].equals("server"))
                        AddServer(so, elements[2], request);
                    else if (elements[1].equals("appver"))
                        newAppVersion(so, elements[2], request);
                    else if (elements[1].equals("compver")) {
                        Component newComp = newCompVersion(so, elements[2], request);
                        obj.add("result", assembleJSONForComponent(so, newComp));
                    } else if (elements[1].equals("environment"))
                        AddEnvironment(so, elements[2], request);
                    else if (elements[1].equals("domain"))
                        AddDomain(so, elements[2], request);
                    else if (elements[1].equals("credential"))
                        AddCredential(so, elements[2], request);
                    else if (elements[1].equals("compitem")) {
                        String compname = request.getParameter("component");
                        String xStr = request.getParameter("xpos");
                        String yStr = request.getParameter("ypos");
                        String removeAllStr = request.getParameter("removeall");
                        String repo = request.getParameter("repo");
                        String pattern = request.getParameter("pattern");
                        String uri = request.getParameter("uri");
                        int xpos = 0;
                        int ypos = 0;
                        boolean removeAll = false;

                        if (repo == null)
                            repo = "";

                        if (pattern == null)
                            pattern = "";

                        if (uri == null)
                            uri = "";

                        if (xStr == null || xStr.length() == 0)
                            xpos = 0;
                        else
                            xpos = Integer.parseInt(xStr);

                        if (yStr == null || yStr.length() == 0)
                            ypos = 0;
                        else
                            ypos = Integer.parseInt(yStr);

                        if (removeAllStr != null && removeAllStr.equalsIgnoreCase("Y"))
                            removeAll = true;

                        AddComponentItems(so, compname, elements[2], xpos, ypos, removeAll, request, repo,
                                pattern, uri);
                    } else
                        throw new ApiException("Invalid object \"" + elements[1] + "\" for \"new\" operation");

                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("del")) {
                // Deleting an existing object.
                if (elements.length == 3) {
                    if (elements[1].equals("user")) {
                        String username = elements[2];
                        User usertodel = getUserFromNameOrID(so, username);
                        if (!usertodel.isUpdatable())
                            throw new ApiException("Permission Denied");
                        so.RemoveObject("user", usertodel.getId(), out, true);
                        delop = true;
                    } else if (elements[1].equals("server")) {
                        String servername = elements[2];
                        Server servertodel = getServerFromNameOrID(so, servername);
                        if (!servertodel.isUpdatable())
                            throw new ApiException("Permission Denied");
                        so.RemoveObject("server", servertodel.getId(), out, true);
                        delop = true;
                    }
                    if (elements[1].equals("environment")) {
                        String envname = elements[2];
                        Environment envtodel = getEnvironmentFromNameOrID(so, envname);
                        if (!envtodel.isUpdatable())
                            throw new ApiException("Permission Denied");
                        so.RemoveObject("environment", envtodel.getId(), out, true);
                        delop = true;
                    } else if (elements[1].equals("credential")) {
                        String credname = elements[2];
                        Credential credtodel = getCredentialFromNameOrID(so, credname);
                        if (!credtodel.isUpdatable())
                            throw new ApiException("Permission Denied");
                        so.RemoveObject("credentials", credtodel.getId(), out, true);
                        delop = true;
                    } else
                        throw new ApiException("Invalid object \"" + elements[1] + "\" for \"del\" operation");
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("mod")) {
                // Modifying an existing object
                if (elements.length == 3) {
                    if (elements[1].equals("user"))
                        ModUser(so, elements[2], request);
                    else if (elements[1].equals("server"))
                        ModServer(so, elements[2], request);
                    else if (elements[1].equals("environment"))
                        ModEnvironment(so, elements[2], request);
                    else if (elements[1].equals("credential"))
                        ModCredential(so, elements[2], request);
                    else
                        throw new ApiException("Invalid object \"" + elements[1] + "\" for \"mod\" operation");
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("clone")) {
                // API/clone/server/<servername>/<newname>
                // API/clone/environment/<envname>/<newname>
                // API/clone/user/<username>/<newname>
                if (elements.length == 4) {
                    if (elements[1].equals("server"))
                        cloneServer(so, elements[2], elements[3], request);
                    else if (elements[1].equals("environment"))
                        cloneEnvironment(so, elements[2], elements[3], request);
                    else
                        throw new ApiException(
                                "Invalid object \"" + elements[1] + "\" for \"clone\" operation");
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("assign")) {

                // API/assign/server/<servername>/<environmentname>
                // API/assign/application/<appname>/<environmentname>
                if (elements.length == 4) {
                    if (elements[1].equals("server"))
                        assignServer(so, elements[2], elements[3]);
                    else if (elements[1].equals("application"))
                        assignApplication(so, elements[2], elements[3]);
                    else if (elements[1].equals("user"))
                        assignUser(so, elements[2], elements[3]);
                    else
                        throw new ApiException(
                                "Invalid object \"" + elements[1] + "\" for \"assign\" operation");
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("unassign")) {
                // API/unassign/server/<servername>/<environmentname>
                // API/unassign/application/<appname>/<environmentname>
                if (elements.length == 4) {
                    if (elements[1].equals("server"))
                        deAssignServer(so, elements[2], elements[3]);
                    else if (elements[1].equals("application"))
                        deAssignApplication(so, elements[2], elements[3]);
                    else if (elements[1].equals("user"))
                        deAssignUser(so, elements[2], elements[3]);
                    else
                        throw new ApiException(
                                "Invalid object \"" + elements[1] + "\" for \"assign\" operation");
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("buildid")) {
                // Associates a build ID with the specified component
                // API/buildid/<compname>/<buildid>
                if (elements.length == 3) {
                    addBuildNumber(so, elements[1], elements[2], request);
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("buildnotify")) {
                // API/buildnotify?buildurl=<buildurl>
                if (elements.length == 1) {
                    String buildurl = request.getParameter("buildurl");
                    if (buildurl == null)
                        throw new ApiException("buildurl parameter not specified");
                    JSONArray info = buildNotify(so, buildurl);
                    obj.add("affected_objects", info);
                } else {
                    throw new ApiException("Path contains wrong number of elements (" + elements.length + ")");
                }
            } else if (elements[0].equals("calendar")) {
                // Listing calendar entries
                // API/calendar?[env=<env>&app=<app>][&start=<start>&end=<end>&all=Y&deploy=Y]
                String envname = request.getParameter("env");
                String appname = request.getParameter("app");
                String starttext = request.getParameter("start");
                String endtext = request.getParameter("end");
                long starttime = 0;
                long endtime = 0;
                if (starttext != null) {
                    starttime = convertDateTime(starttext);
                } else {
                    starttime = so.timeNow();
                }
                if (endtext != null)
                    endtime = convertDateTime(endtext);
                Environment env = null;
                Application app = null;

                if (envname != null)
                    env = getEnvironmentFromNameOrID(so, envname);
                if (appname != null)
                    app = getApplicationFromNameOrID(so, appname);
                List<DMCalendarEvent> events = so.getEvents(env, app, starttime, endtime);
                JSONArray es = new JSONArray();
                for (DMCalendarEvent event : events) {
                    JSONObject jo = new JSONObject();
                    jo.add("id", event.getID());
                    jo.add("title", event.getEventTitle());
                    jo.add("desc", event.getEventDesc());
                    jo.add("type", event.getEventTypeString());
                    jo.add("starttime", tsObject(event.getStart()));
                    jo.add("endtime", tsObject(event.getEnd()));
                    jo.add("allday", event.getAllDayEvent());
                    if (event.getApproved() > 0) {
                        jo.add("approved", tsObject(event.getApproved()));
                        jo.add("approver", event.getApprover());
                    }
                    jo.add("creator", userObject(so, event.getCreatorID()));
                    jo.add("created", tsObject(event.getCreated()));
                    jo.add("deployid", event.getDeployID());
                    jo.add("pending", event.getPending());
                    int appid = event.getAppID();
                    int envid = event.getEnvID();
                    if (appid > 0) {
                        Application eventapp = so.getApplication(appid, false);
                        JSONObject appjo = new JSONObject();
                        appjo.add("id", eventapp.getId());
                        appjo.add("name", eventapp.getName());
                        jo.add("application", appjo);
                    }
                    if (envid > 0) {
                        Environment eventenv = so.getEnvironment(envid, false);
                        JSONObject envjo = new JSONObject();
                        envjo.add("id", eventenv.getId());
                        envjo.add("name", eventenv.getName());
                        jo.add("environment", envjo);
                    }
                    es.add(jo);
                }
                obj.add("result", es);
            } else if (!elements[0].equals("sql")) {
                throw new ApiException("Unrecognised request path: " + path);
            }

            obj.add("success", true);
            if (deploymentid != 0) {
                obj.add("deploymentid", deploymentid);
            }
        } catch (ApiException e) {
            System.out.println("ApiException caught e=" + e.getMessage());
            if (so != null) {
                try {
                    so.GetConnection().rollback();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            obj.add("success", false);
            obj.add("error", e.getMessage());
        } catch (Exception e) {
            System.out.println("Exception caught, e=" + e.getMessage());
            e.printStackTrace();
            if (so != null) {
                try {
                    so.GetConnection().rollback();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
            obj.add("success", false);
            obj.add("error", e.toString());
        } finally {
            if (!delop) {
                // Delete operations call RemoveObject which writes success or failure JSON to the PrintWriter...
                String ret = obj.getJSON();
                System.out.println(ret);
                out.println(ret);
            }
        }
    }
}

From source file:dmadmin.DMSession.java

License:Open Source License

JSONObject getProjectsFromBamboo(int builderid) {
    System.out.println("getProjectsFromBamboo");
    String sql = "select value,encrypted from dm.dm_buildengineprops where name='Server URL' and builderid = ?";
    JSONObject ret = new JSONObject();
    try {//from  ww w .ja v  a  2s . com
        Builder builder = getBuilder(builderid);
        Credential cred = builder.getCredential();
        PreparedStatement stmt = m_conn.prepareStatement(sql);
        stmt.setInt(1, builderid);
        ResultSet rs = stmt.executeQuery();
        if (rs.next()) {
            // Got the Server URL
            String serverURL = rs.getString(1);
            if (rs.getString(2).equalsIgnoreCase("y")) {
                // Server URL is encrypted
                serverURL = new String(Decrypt3DES(serverURL, m_passphrase));
            }
            System.out.println("Server URL=" + serverURL);
            String res = getJSONFromServer(serverURL + "/rest/api/latest/plan.json", cred);
            if (res.startsWith("Could not connect")) {
                ret.add("error", res);
            } else {
                JsonObject returnedjson = new JsonParser().parse(res).getAsJsonObject();
                JsonObject plans = returnedjson.getAsJsonObject("plans");
                JsonArray plan = plans.getAsJsonArray("plan");
                JSONArray retJobs = new JSONArray();
                if (plan.size() == 0) {
                    ret.add("error", "No Projects found on Bamboo Server " + serverURL);
                }
                for (int i = 0; i < plan.size(); i++) {
                    JsonObject jsonPlan = plan.get(i).getAsJsonObject();
                    String planname = jsonPlan.get("shortName").getAsString();
                    JSONObject jobobj = new JSONObject();
                    jobobj.add("name", planname);
                    retJobs.add(jobobj);
                }
                ret.add("jobs", retJobs);
            }
        } else {
            // Couldn't find server URL - stick an error into the return object
            ret.add("error", "Build Engine has no Server URL defined");
        }
        rs.close();
        stmt.close();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        ret.add("error", "SQL Failed running getProjectsFromBamboo");
    }
    return ret;
}

From source file:dmadmin.DMSession.java

License:Open Source License

@SuppressWarnings("deprecation")
public void SyncAnsible(ServletContext context) {
    internalLogin(context);/*from  ww  w . jav  a  2  s  .  c o  m*/

    int domainid = -1;

    try {
        PreparedStatement st;
        st = getDBConnection().prepareStatement("select id from dm.dm_domain where name = 'Infrastructure'");

        ResultSet rs2 = st.executeQuery();
        while (rs2.next()) {
            domainid = rs2.getInt(1);
        }
        rs2.close();
        st.close();
    } catch (SQLException e) {
    }

    if (domainid == -1) {
        try {
            PreparedStatement st;
            st = getDBConnection().prepareStatement(
                    "insert into dm.dm_domain (id,name,domainid,ownerid,status) (select max(id)+1,'Infrastructure', 1, 1,'N' from dm.dm_domain)");
            st.execute();
            st.close();
            st = getDBConnection()
                    .prepareStatement("select id from dm.dm_domain where name = 'Infrastructure'");

            ResultSet rs2 = st.executeQuery();
            while (rs2.next()) {
                domainid = rs2.getInt(1);
            }
            rs2.close();
            st.close();
        } catch (SQLException e) {
        }
    }

    if (domainid == -1)
        domainid = 1;

    int download_filter = 120; // Number of downloads before we consider it worthy of import
    String om_filter = System.getenv("OM_ANSIBLE_DOWNLOAD_FILTER");
    if (om_filter != null) {
        try {
            download_filter = Integer.parseInt(om_filter);
        } catch (NumberFormatException e) {
            System.out.println("Invalid value " + om_filter + " for OM_ANSIBLE_DOWNLOAD_FILTER value");
        }
    }
    int numpages = 0;

    try {
        String json = readUrl("https://galaxy.ansible.com/api/v1/roles/?format=json");
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(json);
        JsonObject ansible = je.getAsJsonObject();
        numpages = ansible.get("num_pages").getAsInt();
    } catch (Exception localException1) {
    }

    File tempdir = new File("temp/roles");
    tempdir.mkdirs();
    System.out.println("ROLES=" + tempdir.getAbsoluteFile());

    // Base64 b64 = new Base64();

    for (int page = 1; page < numpages; page++) {
        try {
            String json = readUrl("https://galaxy.ansible.com/api/v1/roles/?page=" + page + "&format=json");
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(json);

            JsonObject ansible = je.getAsJsonObject();
            JsonArray results = (JsonArray) ansible.get("results");
            for (int i = 0; i < results.size(); i++) {
                JsonObject role = results.get(i).getAsJsonObject();

                String name = role.get("name").getAsString();
                String namespace = role.get("namespace").getAsString();
                String fullName = namespace + "." + name;

                String actionName = name.replaceAll(" ", "_");
                actionName = actionName.replaceAll("-", "_");

                String user = role.get("github_user").getAsString();
                String repo = role.get("github_repo").getAsString();
                String summ = role.get("description").getAsString();
                int dlcnt = role.get("download_count").getAsInt();

                if (dlcnt >= download_filter) {
                    summ = StringEscapeUtils.escapeXml(summ);
                    JsonObject summfields = role.getAsJsonObject("summary_fields");
                    JsonArray tags = summfields.get("tags").getAsJsonArray();
                    String category = "General";
                    try {
                        JsonObject tag = tags.get(0).getAsJsonObject();
                        category = tag.get("name").getAsString();
                        category = capitalize(category);
                    } catch (IndexOutOfBoundsException localIndexOutOfBoundsException) {
                    }

                    String default_vars_str = readUrl("https://raw.githubusercontent.com/" + user + "/" + repo
                            + "/master/defaults/main.yml");
                    JsonObject default_vars_json = convertToJson(default_vars_str);

                    PrintWriter writer = new PrintWriter("temp/roles/" + user + "_" + repo + ".xml");
                    writer.println("<action name=\"ansible_" + actionName + "_" + user.replaceAll("-", "_")
                            + "\" summary=\"" + summ + "\" isGraphical=\"N\" category=\"" + category + "\">");
                    writer.println("<kind copy=\"N\">3</kind>");
                    writer.println("<scripts>");
                    writer.println("<scriptbody filename=\"omansible.sh\">");
                    writer.println("</scriptbody>");
                    writer.println("</scripts>");
                    writer.println("<cmdline>");
                    writer.println("<script name=\"${DMHOME}/scripts/omansible.sh\" />");
                    writer.println("<flag name=\"Target\" switch=\"--ansible_target\" pad=\"false\" />");
                    writer.println("<flag name=\"TargetArg\" switch=\"${server.hostname}\" pad=\"false\" />");
                    writer.println("<flag name=\"GalaxyRole\" switch=\"--galaxy_role\" pad=\"false\" />");
                    writer.println("<flag name=\"GalaxyRoleArg\" switch=\"" + fullName + "\" pad=\"false\" />");
                    writer.println(
                            "<flag name=\"AnsibleSshUser\" switch=\"--ansible_ssh_user\" pad=\"false\" />");
                    writer.println(
                            "<flag name=\"AnsibleSshUserArg\" switch=\"'${AnsibleSshUser}'\" pad=\"false\" />");
                    writer.println(
                            "<flag name=\"AnsibleSshPassword\" switch=\"--ansible_ssh_pass\" pad=\"false\" />");
                    writer.println(
                            "<flag name=\"AnsibleSshPasswordArg\" switch=\"'${AnsibleSshPassword}'\" pad=\"false\" />");
                    writer.println(
                            "<flag name=\"AnsibleSudoPassword\" switch=\"--ansible_sudo_pass\" pad=\"false\" />");
                    writer.println(
                            "<flag name=\"AnsibleSudoPasswordArg\" switch=\"'${AnsibleSudoPassword}'\" pad=\"false\" />");

                    writer.println(
                            "<argument name=\"AnsibleVariableFile\" type=\"Entry\" inpos=\"0\" switchmode=\"S\" switch=\"--ansible_variable_file\" negswitch=\"\" pad=\"false\" required=\"false\" />");

                    if (default_vars_json.isJsonObject()) {
                        Set<Entry<String, JsonElement>> ens = default_vars_json.entrySet();
                        if (ens != null) {
                            for (Iterator<Entry<String, JsonElement>> iterator = ens.iterator(); iterator
                                    .hasNext();) {
                                Entry<String, JsonElement> en = iterator.next();
                                if (!((JsonElement) en.getValue()).isJsonPrimitive())
                                    continue;
                                writer.println("<argument name=\"" + capitalize((String) en.getKey())
                                        + "\" type=\"Entry\" inpos=\"0\" switchmode=\"S\" switch=\"--"
                                        + (String) en.getKey()
                                        + "\" negswitch=\"\" pad=\"false\" required=\"false\" />");
                            }
                        }

                    }

                    writer.println("</cmdline>");
                    writer.println("<fragment name=\"ansible_" + actionName + "_" + user.replaceAll("-", "_")
                            + "_role\" summary=\"" + summ + "\">");
                    writer.println(
                            "<parameter name=\"AnsibleVariableFile\" type=\"Entry\" required=\"N\" default_value=\"${ansible_variable_file}\"/>");

                    HashMap<String, String> defaultvars = new HashMap<String, String>();
                    if (default_vars_json.isJsonObject()) {
                        Set<Entry<String, JsonElement>> ens = default_vars_json.entrySet();
                        if (ens != null) {
                            for (Iterator<Entry<String, JsonElement>> iterator = ens.iterator(); iterator
                                    .hasNext();) {
                                Entry<String, JsonElement> en = iterator.next();
                                if (!((JsonElement) en.getValue()).isJsonPrimitive())
                                    continue;
                                defaultvars.put((String) en.getKey(),
                                        ((JsonElement) en.getValue()).toString().replaceAll("^\"|\"$", ""));
                                writer.println("<parameter name=\"" + capitalize((String) en.getKey())
                                        + "\" type=\"Entry\" required=\"N\" default_value=\"${"
                                        + (String) en.getKey() + "}\" />");
                            }
                        }
                    }

                    writer.println("</fragment>");
                    writer.println(" </action>");
                    writer.close();

                    int existingdomain = -1;
                    try {
                        PreparedStatement st;
                        st = getDBConnection()
                                .prepareStatement("select domainid from dm.dm_action where name = ?");
                        st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_"));

                        ResultSet rs2 = st.executeQuery();
                        while (rs2.next()) {
                            existingdomain = rs2.getInt(1);
                        }
                        rs2.close();
                        st.close();
                    } catch (SQLException e) {
                    }
                    if (existingdomain == -1)
                        existingdomain = domainid;

                    System.out.println("Import Domain=" + existingdomain);
                    ImportFunction(existingdomain,
                            new File("temp/roles/" + user + "_" + repo + ".xml").getAbsolutePath());
                    long t = timeNow();

                    PreparedStatement st = getDBConnection()
                            .prepareStatement("select id from dm.dm_action where name = ?");
                    st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_action");

                    int actionid = 0;

                    ResultSet rs2 = st.executeQuery();
                    while (rs2.next()) {
                        actionid = rs2.getInt(1);
                    }
                    rs2.close();
                    st.close();

                    existingdomain = -1;
                    try {
                        st = getDBConnection()
                                .prepareStatement("select domainid from dm.dm_action where name = ?");
                        st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_action");

                        rs2 = st.executeQuery();
                        while (rs2.next()) {
                            existingdomain = rs2.getInt(1);
                        }
                        rs2.close();
                        st.close();
                    } catch (SQLException e) {
                    }
                    if (existingdomain == -1)
                        existingdomain = domainid;

                    int x;
                    if (actionid == 0) {
                        st = getDBConnection().prepareStatement(
                                "INSERT INTO dm.dm_action (id,name,domainid,function,graphical,ownerid,creatorid,modifierid,created,modified,status,kind) VALUES(?,?,?,'N','Y',?,?,?,?,?,'N',6)");
                        actionid = getID("action");
                        st.setInt(1, actionid);
                        st.setString(2, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_action");
                        st.setInt(3, existingdomain);
                        st.setInt(4, 1);
                        st.setInt(5, 1);
                        st.setInt(6, 1);
                        st.setLong(7, t);
                        st.setLong(8, t);
                        st.execute();
                        st.close();

                        st = getDBConnection().prepareStatement("select id from dm.dm_category where name = ?");
                        st.setString(1, category);

                        int categoryid = 0;
                        rs2 = st.executeQuery();
                        while (rs2.next()) {
                            categoryid = rs2.getInt(1);
                        }
                        rs2.close();
                        st.close();

                        st = getDBConnection().prepareStatement(
                                "INSERT INTO dm.dm_action_categories (id,categoryid) VALUES(?,?)");
                        st.setInt(1, actionid);
                        st.setInt(2, categoryid);
                        st.execute();
                        st.close();

                        int procfuncid = 0;
                        int setcredid = 0;

                        st = getDBConnection()
                                .prepareStatement("select id from dm.dm_fragments where name = ?");
                        st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_role");

                        rs2 = st.executeQuery();
                        while (rs2.next()) {
                            procfuncid = rs2.getInt(1);
                        }
                        rs2.close();
                        //
                        // Check if ansible_set_credentials is set and add it before each
                        // call to the action if present.
                        //
                        st.setString(1, "ansible_set_credentials");
                        rs2 = st.executeQuery();
                        while (rs2.next()) {
                            setcredid = rs2.getInt(1);
                            if (rs2.wasNull())
                                setcredid = 0;
                        }
                        rs2.close();
                        st.close();
                        int windowid = 1;
                        if (setcredid > 0) {
                            // ansible_set_credentials is present
                            MoveNode(actionid, 1, 0, 400, 160, setcredid);
                            AddFlow(actionid, "0", "1", 1);
                            MoveNode(actionid, 2, 0, 400, 360, procfuncid);
                            AddFlow(actionid, "1", "2", 1);
                            windowid = 2;
                        } else {
                            // ansible_set_credentials not present
                            MoveNode(actionid, 1, 0, 400, 160, procfuncid);
                            AddFlow(actionid, "0", "1", 1);
                            windowid = 1;
                        }

                        List<FragmentAttributes> fields = getFragmentAttributes(actionid, windowid, 0);

                        Map<String, String> keyvals = new HashMap<String, String>();

                        //               dm.UpdateFragAttrs(keyvals);
                        //
                        //               fields = dm.getFragmentAttributes(actionid, windowid, 0);

                        keyvals = new HashMap<String, String>();
                        keyvals.put("a", new Integer(actionid).toString());
                        keyvals.put("w", Integer.toString(windowid));

                        if (fields != null) {
                            for (x = 0; x < fields.size(); x++) {
                                FragmentAttributes fa = (FragmentAttributes) fields.get(x);
                                String key = "f" + fa.getAttrId();
                                keyvals.put(key, fa.getDefaultValue());
                            }
                        }

                        UpdateFragAttrs(keyvals);
                    }

                    st = getDBConnection()
                            .prepareStatement("select count(*) from dm.dm_component where name = ?");
                    st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_"));

                    int compcnt = 0;

                    rs2 = st.executeQuery();
                    while (rs2.next()) {
                        compcnt = rs2.getInt(1);
                    }
                    rs2.close();
                    st.close();

                    existingdomain = -1;
                    try {
                        st = getDBConnection()
                                .prepareStatement("select domainid from dm.dm_action where name = ?");
                        st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_action");

                        rs2 = st.executeQuery();
                        while (rs2.next()) {
                            existingdomain = rs2.getInt(1);
                        }
                        rs2.close();
                        st.close();
                    } catch (SQLException e) {
                    }
                    if (existingdomain == -1)
                        existingdomain = domainid;

                    if (compcnt != 0)
                        continue;
                    st = getDBConnection().prepareStatement("select id from dm.dm_category where name = ?");
                    st.setString(1, category);

                    int categoryid = 0;
                    rs2 = st.executeQuery();
                    while (rs2.next()) {
                        categoryid = rs2.getInt(1);
                    }
                    rs2.close();
                    st.close();

                    st = getDBConnection().prepareStatement(
                            "INSERT INTO dm.dm_component (id,name,domainid,ownerid,creatorid,modifierid,created,modified,status,filteritems,deployalways,actionid,comptypeid) VALUES(?,?,?,?,?,?,?,?,'N','Y','N',?,6)");
                    int compid = getID("component");
                    st.setInt(1, compid);
                    st.setString(2, "ansible_" + actionName + "_" + user.replaceAll("-", "_"));
                    st.setInt(3, existingdomain);
                    st.setInt(4, 1);
                    st.setInt(5, 1);
                    st.setInt(6, 1);
                    st.setLong(7, t);
                    st.setLong(8, t);
                    st.setLong(9, actionid);
                    st.execute();
                    st.close();
                    st = getDBConnection().prepareStatement(
                            "INSERT INTO dm.dm_component_categories (id,categoryid) VALUES(?,?)");
                    st.setInt(1, compid);
                    st.setInt(2, categoryid);
                    st.execute();
                    st.close();
                    getDBConnection().commit();

                    AttributeChangeSet changes = new AttributeChangeSet();
                    for (Iterator<Entry<String, String>> iterator = defaultvars.entrySet().iterator(); iterator
                            .hasNext();) {
                        Entry<String, String> entry = iterator.next();
                        String key = (String) entry.getKey();
                        String value = (String) entry.getValue();
                        changes.addAdded(new DMAttribute(key, value));
                    }

                    DMObject dmobj = getObject(ObjectType.COMPONENT, compid);
                    dmobj.updateAttributes(changes);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:dpfmanager.shell.modules.report.util.ReportRow.java

License:Open Source License

/**
 * Create row from json report row.//from   w  w  w  .j  a v a  2s . c  om
 *
 * @param reportDay the report day
 * @param file      the file
 * @return the report row
 */
public static ReportRow createRowFromJson(String reportDay, File file, ResourceBundle bundle) {
    try {
        String sdate = reportDay.substring(6, 8) + "/" + reportDay.substring(4, 6) + "/"
                + reportDay.substring(0, 4);
        File parent = new File(file.getParent());
        int n = countFiles(parent, ".json") - 1 - countFiles(parent, "_fixed.json");
        int passed = 0, errors = 0, warnings = 0, score = 0;
        String json = readFullFile(file.getPath(), Charset.defaultCharset());
        JsonObject jObjRoot = new JsonParser().parse(json).getAsJsonObject();
        String stime = getStime(file.getPath());
        String input = parseInputFiles(file.getParentFile(), file.getAbsolutePath(), ".json");
        JsonObject jObj = jObjRoot.getAsJsonObject("globalreport");

        // Passed
        if (jObj.has("stats")) {
            try {
                JsonObject jStats = jObj.get("stats").getAsJsonObject();
                passed = Integer.parseInt(jStats.get("valid_files").getAsString());
            } catch (Exception e) {
                passed = -1;
            }
        }

        // Errors
        if (jObj.has("stats")) {
            try {
                JsonObject jStats = jObj.get("stats").getAsJsonObject();
                errors = Integer.parseInt(jStats.get("invalid_files").getAsString());
            } catch (Exception e) {
                errors = -1;
            }
        }

        // Warnings
        if (jObj.has("individualreports")) {
            try {
                JsonArray jArray = ((JsonObject) jObj.get("individualreports")).get("report").getAsJsonArray()
                        .getAsJsonArray();
                for (JsonElement element : jArray) {
                    if (element.toString().contains("\"warning\"")) {
                        warnings++;
                    }
                }
            } catch (Exception e) {
                warnings = -1;
            }
        }

        // Score
        if (n > 0) {
            score = passed * 100 / n;
        }

        ReportRow row = new ReportRow(sdate, stime, input, "" + n,
                bundle.getString("errors").replace("%1", "" + errors),
                bundle.getString("warnings").replace("%1", "" + warnings),
                bundle.getString("passed").replace("%1", "" + passed), score + "%", file.getAbsolutePath());
        return row;
    } catch (Exception e) {
        return null;
    }
}

From source file:edu.illinois.cs.cogcomp.core.utilities.JsonSerializer.java

License:Open Source License

private static Pair<Pair<String, Double>, int[]> readSentences(JsonObject json) {
    JsonObject object = json.getAsJsonObject("sentences");

    String generator = readString("generator", object);
    double score = readDouble("score", object);
    int[] endPositions = readIntArray("sentenceEndPositions", object);

    return new Pair<>(new Pair<>(generator, score), endPositions);

}