Example usage for javax.json JsonObject getJsonObject

List of usage examples for javax.json JsonObject getJsonObject

Introduction

In this page you can find the example usage for javax.json JsonObject getJsonObject.

Prototype

JsonObject getJsonObject(String name);

Source Link

Document

Returns the object value to which the specified name is mapped.

Usage

From source file:de.tu_dortmund.ub.data.dswarm.Task.java

/**
 * configuration and processing of the task
 *
 * @param inputDataModelID//  w w  w .  j a  va 2  s  .co  m
 * @param projectID
 * @param outputDataModelID
 * @return
 */
private String executeTask(String inputDataModelID, String projectID, String outputDataModelID)
        throws Exception {

    String jsonResponse = null;

    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {

        // Hole Mappings aus dem Projekt mit 'projectID'
        HttpGet httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "projects/" + projectID);

        CloseableHttpResponse httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        String mappings = "";

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                String responseJson = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson);

                JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(responseJson, "UTF-8"));
                JsonObject jsonObject = jsonReader.readObject();

                mappings = jsonObject.getJsonArray("mappings").toString();

                logger.info("[" + config.getProperty("service.name") + "] mappings : " + mappings);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // Hole InputDataModel
        String inputDataModel = "";

        httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + inputDataModelID);

        httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                inputDataModel = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] inputDataModel : " + inputDataModel);

                JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(inputDataModel, "UTF-8"));
                JsonObject jsonObject = jsonReader.readObject();

                String inputResourceID = jsonObject.getJsonObject("data_resource").getString("uuid");

                logger.info("[" + config.getProperty("service.name") + "] mappings : " + mappings);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // Hole OutputDataModel
        String outputDataModel = "";

        httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + outputDataModelID);

        httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                outputDataModel = writer.toString();

                logger.info(
                        "[" + config.getProperty("service.name") + "] outputDataModel : " + outputDataModel);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // erzeuge Task-JSON
        String task = "{";
        task += "\"name\":\"" + "Task Batch-Prozess 'CrossRef'" + "\",";
        task += "\"description\":\"" + "Task Batch-Prozess 'CrossRef' zum InputDataModel '" + inputDataModelID
                + "'\",";
        task += "\"job\": { " + "\"mappings\": " + mappings + "," + "\"uuid\": \"" + UUID.randomUUID() + "\""
                + " },";
        task += "\"input_data_model\":" + inputDataModel + ",";
        task += "\"output_data_model\":" + outputDataModel;
        task += "}";

        logger.info("[" + config.getProperty("service.name") + "] task : " + task);

        // POST /dmp/tasks/
        HttpPost httpPost = new HttpPost(config.getProperty("engine.dswarm.api") + "tasks?persist="
                + config.getProperty("results.persistInDMP"));
        StringEntity stringEntity = new StringEntity(task,
                ContentType.create("application/json", Consts.UTF_8));
        httpPost.setEntity(stringEntity);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPost.getRequestLine());

        httpResponse = httpclient.execute(httpPost);

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                jsonResponse = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] jsonResponse : " + jsonResponse);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

    } finally {
        httpclient.close();
    }

    return jsonResponse;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

JsonObject getResult(HttpResponse response, String body, String type)
        throws HTTPException, ParseException, IOException {

    int respStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    logger.trace(format("response status %d, HttpEntity %s ", respStatusCode, "" + entity));
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;
    logger.trace(format("responseBody: %s ", responseBody));

    // If the status code in the response is greater or equal to the status code set in the client object then an exception will
    // be thrown, otherwise, we continue to read the response and return any error code that is less than 'statusCode'
    if (respStatusCode >= statusCode) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s. Response: %s", type, url, body, responseBody),
                respStatusCode);//from   w  w  w .j  a  v  a2 s. co m
        logger.error(e.getMessage());
        throw e;
    }
    if (responseBody == null) {

        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s with null response body returned.", type, url,
                        body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;

    }

    logger.debug("Status: " + respStatusCode);

    JsonReader reader = Json.createReader(new StringReader(responseBody));
    JsonObject jobj = (JsonObject) reader.read();

    JsonObjectBuilder job = Json.createObjectBuilder();
    job.add("statusCode", respStatusCode);

    JsonArray errors = jobj.getJsonArray("errors");
    // If the status code is greater than or equal to 400 but less than or equal to the client status code setting,
    // then encountered an error and we return back the status code, and log the error rather than throwing an exception.
    if (respStatusCode < statusCode && respStatusCode >= 400) {
        if (errors != null && !errors.isEmpty()) {
            JsonObject jo = errors.getJsonObject(0);
            String errorMsg = format(
                    "[HTTP Status Code: %d] - %s request to %s failed request body %s error message: [Error Code %d] - %s",
                    respStatusCode, type, url, body, jo.getInt("code"), jo.getString("message"));
            logger.error(errorMsg);
        }
        return job.build();
    }
    if (errors != null && !errors.isEmpty()) {
        JsonObject jo = errors.getJsonObject(0);
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s error message: [Error Code %d] - %s", type, url,
                        body, jo.getInt("code"), jo.getString("message")),
                respStatusCode);
        throw e;
    }

    boolean success = jobj.getBoolean("success");
    if (!success) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s Body of response did not contain success", type,
                        url, body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;
    }

    JsonObject result = jobj.getJsonObject("result");
    if (result == null) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s " + "Body of response did not contain result",
                        type, url, body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;
    }

    JsonArray messages = jobj.getJsonArray("messages");
    if (messages != null && !messages.isEmpty()) {
        JsonObject jo = messages.getJsonObject(0);
        String message = format(
                "%s request to %s failed request body %s response message: [Error Code %d] - %s", type, url,
                body, jo.getInt("code"), jo.getString("message"));
        logger.info(message);
    }

    // Construct JSON object that contains the result and HTTP status code
    for (Entry<String, JsonValue> entry : result.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }
    job.add("statusCode", respStatusCode);
    result = job.build();

    logger.debug(format("%s %s, body:%s result: %s", type, url, body, "" + result));
    return result;
}

From source file:io.bibleget.BibleGetDB.java

public boolean renewMetaData() {
    if (instance.connect()) {
        try {/*from  w ww.  j  a  v  a  2 s.  co  m*/
            DatabaseMetaData dbMeta;
            dbMeta = instance.conn.getMetaData();
            try (ResultSet rs3 = dbMeta.getTables(null, null, "METADATA", null)) {
                if (rs3.next()) {
                    //System.out.println("Table METADATA exists...");
                    try (Statement stmt = instance.conn.createStatement()) {
                        HTTPCaller myHTTPCaller = new HTTPCaller();
                        String myResponse;
                        myResponse = myHTTPCaller.getMetaData("biblebooks");
                        if (myResponse != null) {
                            JsonReader jsonReader = Json.createReader(new StringReader(myResponse));
                            JsonObject json = jsonReader.readObject();
                            JsonArray arrayJson = json.getJsonArray("results");
                            if (arrayJson != null) {
                                ListIterator pIterator = arrayJson.listIterator();
                                while (pIterator.hasNext()) {
                                    try (Statement stmt1 = instance.conn.createStatement()) {
                                        int index = pIterator.nextIndex();
                                        JsonArray currentJson = (JsonArray) pIterator.next();
                                        String biblebooks_str = currentJson.toString(); //.replaceAll("\"", "\\\\\"");
                                        //System.out.println("BibleGetDB line 267: BIBLEBOOKS"+Integer.toString(index)+"='"+biblebooks_str+"'");
                                        String stmt_str = "UPDATE METADATA SET BIBLEBOOKS"
                                                + Integer.toString(index) + "='" + biblebooks_str
                                                + "' WHERE ID=0";
                                        //System.out.println("executing update: "+stmt_str);
                                        int update = stmt1.executeUpdate(stmt_str);
                                        //System.out.println("executeUpdate resulted in: "+Integer.toString(update));
                                        stmt1.close();
                                    }
                                }
                            }

                            arrayJson = json.getJsonArray("languages");
                            if (arrayJson != null) {
                                try (Statement stmt2 = instance.conn.createStatement()) {
                                    String languages_str = arrayJson.toString(); //.replaceAll("\"", "\\\\\"");
                                    String stmt_str = "UPDATE METADATA SET LANGUAGES='" + languages_str
                                            + "' WHERE ID=0";
                                    int update = stmt2.executeUpdate(stmt_str);
                                    stmt2.close();
                                }
                            }
                        }

                        myResponse = myHTTPCaller.getMetaData("bibleversions");
                        if (myResponse != null) {
                            JsonReader jsonReader = Json.createReader(new StringReader(myResponse));
                            JsonObject json = jsonReader.readObject();
                            JsonObject objJson = json.getJsonObject("validversions_fullname");
                            if (objJson != null) {
                                String bibleversions_str = objJson.toString(); //.replaceAll("\"", "\\\\\"");
                                try (Statement stmt3 = instance.conn.createStatement()) {
                                    String stmt_str = "UPDATE METADATA SET VERSIONS='" + bibleversions_str
                                            + "' WHERE ID=0";
                                    int update = stmt3.executeUpdate(stmt_str);
                                    stmt3.close();
                                }

                                Set<String> versionsabbrev = objJson.keySet();
                                if (!versionsabbrev.isEmpty()) {
                                    String versionsabbrev_str = "";
                                    for (String s : versionsabbrev) {
                                        versionsabbrev_str += ("".equals(versionsabbrev_str) ? "" : ",") + s;
                                    }

                                    myResponse = myHTTPCaller
                                            .getMetaData("versionindex&versions=" + versionsabbrev_str);
                                    if (myResponse != null) {
                                        jsonReader = Json.createReader(new StringReader(myResponse));
                                        json = jsonReader.readObject();
                                        objJson = json.getJsonObject("indexes");
                                        if (objJson != null) {
                                            for (String name : objJson.keySet()) {
                                                JsonObjectBuilder tempBld = Json.createObjectBuilder();
                                                JsonObject book_num = objJson.getJsonObject(name);
                                                tempBld.add("book_num", book_num.getJsonArray("book_num"));
                                                tempBld.add("chapter_limit",
                                                        book_num.getJsonArray("chapter_limit"));
                                                tempBld.add("verse_limit",
                                                        book_num.getJsonArray("verse_limit"));
                                                JsonObject temp = tempBld.build();
                                                String versionindex_str = temp.toString(); //.replaceAll("\"", "\\\\\"");
                                                //add new column to METADATA table name+"IDX" VARCHAR(5000)
                                                //update METADATA table SET name+"IDX" = versionindex_str
                                                try (ResultSet rs1 = dbMeta.getColumns(null, null, "METADATA",
                                                        name + "IDX")) {
                                                    boolean updateFlag = false;
                                                    if (rs1.next()) {
                                                        //column already exists
                                                        updateFlag = true;
                                                    } else {
                                                        try (Statement stmt4 = instance.conn
                                                                .createStatement()) {
                                                            String sql = "ALTER TABLE METADATA ADD COLUMN "
                                                                    + name + "IDX VARCHAR(5000)";
                                                            boolean colAdded = stmt4.execute(sql);
                                                            if (colAdded == false) {
                                                                int count = stmt4.getUpdateCount();
                                                                if (count == -1) {
                                                                    //System.out.println("The result is a ResultSet object or there are no more results.");
                                                                } else if (count == 0) {
                                                                    //0 rows affected
                                                                    updateFlag = true;
                                                                }
                                                            }
                                                            stmt4.close();
                                                        }
                                                    }
                                                    if (updateFlag) {
                                                        try (Statement stmt5 = instance.conn
                                                                .createStatement()) {
                                                            String sql1 = "UPDATE METADATA SET " + name
                                                                    + "IDX='" + versionindex_str
                                                                    + "' WHERE ID=0";
                                                            boolean rowsUpdated = stmt5.execute(sql1);
                                                            stmt5.close();
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }

                                }

                            }
                        }

                        stmt.close();
                    }
                }
                rs3.close();
            }
            instance.disconnect();
        } catch (SQLException ex) {
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        return true;
    }
    return false;
}

From source file:httputils.RavelloHttpClient.java

public JsonObject publishBlueprint(String applicationName, int blueprintId, int stopTime, int startupDelay,
        String preferredCloud, String preferredRegion, boolean startAllVms, boolean costOptimized)
        throws RavelloException, InterruptedException {
    JsonObject value = null;
    HttpResponse response = null;/* w  w  w.jav a 2s.c  om*/

    try {
        response = this.getBlueprint(blueprintId);
        if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
            EntityUtils.consumeQuietly(response.getEntity());
            throw new RavelloException("Failed to get blueprint number " + blueprintId + " error: "
                    + response.getStatusLine().toString());
        }
        JsonObject vmTemp = HttpUtil.convertResponseToJson(response);
        EntityUtils.consume(response.getEntity());

        JsonBuilderFactory factory = Json.createBuilderFactory(null);
        Iterator<Map.Entry<String, JsonValue>> it = vmTemp.entrySet().iterator();
        JsonObjectBuilder builder = factory.createObjectBuilder();
        Map.Entry<String, JsonValue> ent;
        while (it.hasNext()) {
            ent = it.next();
            if (!ent.getKey().equals("id") && !ent.getKey().equals("owner")) {
                builder.add(ent.getKey(), ent.getValue());
            }
        }
        builder.add("name", applicationName);
        value = builder.build();
        vmTemp = null;

        response = this.createApplication(value);
        this.verifyResponseAndConsume(response, "Failed to create application - error: ");

        value = HttpUtil.convertResponseToJson(response);
        EntityUtils.consumeQuietly(response.getEntity());

        int appId = value.getInt("id");

        if (costOptimized) {
            value = factory.createObjectBuilder().add("startAllVms", startAllVms).build();
        } else {
            value = factory.createObjectBuilder().add("startAllVms", startAllVms)
                    .add("preferredCloud", preferredCloud).add("preferredRegion", preferredRegion)
                    .add("optimizationLevel", "PERFORMANCE_OPTIMIZED").build();
        }
        response = this.post("/applications/" + appId + "/publish", value);
        this.verifyResponseAndConsume(response, "Failed to publish application - error: ");

        value = factory.createObjectBuilder().add("expirationFromNowSeconds", stopTime).build();
        response = this.post("/applications/" + appId + "/setExpiration", value);
        if (!HttpUtil.verifyResponseAndConsume(response)) {
            throw new RavelloException("Failed to set expiration time for application - error: "
                    + response.getStatusLine().toString() + "\n"
                    + "THIS ERROR MAY CAUSE APPLICATION TO RUN INDEFINITELY - MAKE SURE TO CHECK IT STOPPED");
        }

        if (!startAllVms) {
            response = this.getApplication(appId);
            if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                EntityUtils.consumeQuietly(response.getEntity());
                throw new RavelloException(
                        "Failed to get application status - error: " + response.getStatusLine().toString());
            }
            value = HttpUtil.convertResponseToJson(response);

            return value;
        }

        String state;
        JsonArray jArr;
        boolean allStarted;
        while (true) {
            allStarted = true;
            response = this.getApplication(appId);
            if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                EntityUtils.consumeQuietly(response.getEntity());
                throw new RavelloException(
                        "Failed to get application status - error: " + response.getStatusLine().toString());
            }
            value = HttpUtil.convertResponseToJson(response);

            jArr = value.getJsonObject("deployment").getJsonArray("vms");
            for (int jt = 0; jt < jArr.size(); jt++) {
                state = jArr.getJsonObject(jt).getString("state");
                allStarted = state.equals("STARTED");
                if (state.equals("ERROR")) {
                    throw new RavelloException(
                            "vm" + jArr.getJsonObject(jt).getString("name") + " failed to start");
                }
                if (!allStarted) {
                    break;
                }
            }

            if (allStarted) {
                break;
            } else {
                EntityUtils.consumeQuietly(response.getEntity());
                Thread.sleep(20000);
            }
        }

    } catch (ClientProtocolException e) {
        throw new RavelloException("ClientProtocolException - " + e.getMessage());
    } catch (IOException e) {
        throw new RavelloException("IOException - " + e.getMessage());
    } catch (NullPointerException e) {
        throw new RavelloException("NullPointerException - " + e.getMessage());
    }

    Thread.sleep(startupDelay * 1000);

    return value;
}

From source file:io.bibleget.BibleGetDB.java

public boolean initialize() {

    try {//from w w w . ja va2 s  .  com
        instance.conn = DriverManager.getConnection("jdbc:derby:BIBLEGET;create=true", "bibleget", "bibleget");
        if (instance.conn == null) {
            System.out.println("Careful there! Connection not established! BibleGetDB.java line 81");
        } else {
            System.out.println("conn is not null, which means a connection was correctly established.");
        }
        DatabaseMetaData dbMeta;
        dbMeta = instance.conn.getMetaData();
        try (ResultSet rs1 = dbMeta.getTables(null, null, "OPTIONS", null)) {
            if (rs1.next()) {
                //System.out.println("Table "+rs1.getString("TABLE_NAME")+" already exists !!");
                listColNamesTypes(dbMeta, rs1);
            } else {
                //System.out.println("Table OPTIONS does not yet exist, now attempting to create...");
                try (Statement stmt = instance.conn.createStatement()) {

                    String defaultFont = "";
                    if (SystemUtils.IS_OS_WINDOWS) {
                        defaultFont = "Times New Roman";
                    } else if (SystemUtils.IS_OS_MAC_OSX) {
                        defaultFont = "Helvetica";
                    } else if (SystemUtils.IS_OS_LINUX) {
                        defaultFont = "Arial";
                    }

                    String tableCreate = "CREATE TABLE OPTIONS (" + "PARAGRAPHALIGNMENT VARCHAR(15), "
                            + "PARAGRAPHLINESPACING INT, " + "PARAGRAPHFONTFAMILY VARCHAR(50), "
                            + "PARAGRAPHLEFTINDENT INT, " + "TEXTCOLORBOOKCHAPTER VARCHAR(15), "
                            + "BGCOLORBOOKCHAPTER VARCHAR(15), " + "BOLDBOOKCHAPTER BOOLEAN, "
                            + "ITALICSBOOKCHAPTER BOOLEAN, " + "UNDERSCOREBOOKCHAPTER BOOLEAN, "
                            + "FONTSIZEBOOKCHAPTER INT, " + "VALIGNBOOKCHAPTER VARCHAR(15), "
                            + "TEXTCOLORVERSENUMBER VARCHAR(15), " + "BGCOLORVERSENUMBER VARCHAR(15), "
                            + "BOLDVERSENUMBER BOOLEAN, " + "ITALICSVERSENUMBER BOOLEAN, "
                            + "UNDERSCOREVERSENUMBER BOOLEAN, " + "FONTSIZEVERSENUMBER INT, "
                            + "VALIGNVERSENUMBER VARCHAR(15), " + "TEXTCOLORVERSETEXT VARCHAR(15), "
                            + "BGCOLORVERSETEXT VARCHAR(15), " + "BOLDVERSETEXT BOOLEAN, "
                            + "ITALICSVERSETEXT BOOLEAN, " + "UNDERSCOREVERSETEXT BOOLEAN, "
                            + "FONTSIZEVERSETEXT INT, " + "VALIGNVERSETEXT VARCHAR(15), "
                            + "PREFERREDVERSIONS VARCHAR(50), " + "NOVERSIONFORMATTING BOOLEAN" + ")";

                    String tableInsert;
                    tableInsert = "INSERT INTO OPTIONS (" + "PARAGRAPHALIGNMENT," + "PARAGRAPHLINESPACING,"
                            + "PARAGRAPHFONTFAMILY," + "PARAGRAPHLEFTINDENT," + "TEXTCOLORBOOKCHAPTER,"
                            + "BGCOLORBOOKCHAPTER," + "BOLDBOOKCHAPTER," + "ITALICSBOOKCHAPTER,"
                            + "UNDERSCOREBOOKCHAPTER," + "FONTSIZEBOOKCHAPTER," + "VALIGNBOOKCHAPTER,"
                            + "TEXTCOLORVERSENUMBER," + "BGCOLORVERSENUMBER," + "BOLDVERSENUMBER,"
                            + "ITALICSVERSENUMBER," + "UNDERSCOREVERSENUMBER," + "FONTSIZEVERSENUMBER,"
                            + "VALIGNVERSENUMBER," + "TEXTCOLORVERSETEXT," + "BGCOLORVERSETEXT,"
                            + "BOLDVERSETEXT," + "ITALICSVERSETEXT," + "UNDERSCOREVERSETEXT,"
                            + "FONTSIZEVERSETEXT," + "VALIGNVERSETEXT," + "PREFERREDVERSIONS, "
                            + "NOVERSIONFORMATTING" + ") VALUES (" + "'justify',100,'" + defaultFont + "',0,"
                            + "'#0000FF','#FFFFFF',true,false,false,14,'initial',"
                            + "'#AA0000','#FFFFFF',false,false,false,10,'super',"
                            + "'#696969','#FFFFFF',false,false,false,12,'initial'," + "'NVBSE'," + "false"
                            + ")";
                    boolean tableCreated = stmt.execute(tableCreate);
                    boolean rowsInserted;
                    int count;
                    if (tableCreated == false) {
                        //is false when it's an update count!
                        count = stmt.getUpdateCount();
                        if (count == -1) {
                            //System.out.println("The result is a ResultSet object or there are no more results.");
                        } else {
                            //this is our expected behaviour: 0 rows affected
                            //System.out.println("The Table Creation statement produced results: "+count+" rows affected.");
                            try (Statement stmt2 = instance.conn.createStatement()) {
                                rowsInserted = stmt2.execute(tableInsert);
                                if (rowsInserted == false) {
                                    count = stmt2.getUpdateCount();
                                    if (count == -1) {
                                        //System.out.println("The result is a ResultSet object or there are no more results.");
                                    } else {
                                        //this is our expected behaviour: n rows affected
                                        //System.out.println("The Row Insertion statement produced results: "+count+" rows affected.");
                                        dbMeta = instance.conn.getMetaData();
                                        try (ResultSet rs2 = dbMeta.getTables(null, null, "OPTIONS", null)) {
                                            if (rs2.next()) {
                                                listColNamesTypes(dbMeta, rs2);
                                            }
                                            rs2.close();
                                        }
                                    }
                                } else {
                                    //is true when it returns a resultset, which shouldn't be the case here
                                    try (ResultSet rx = stmt2.getResultSet()) {
                                        while (rx.next()) {
                                            //System.out.println("This isn't going to happen anyways, so...");
                                        }
                                        rx.close();
                                    }
                                }
                                stmt2.close();
                            }
                        }

                    } else {
                        //is true when it returns a resultset, which shouldn't be the case here
                        try (ResultSet rx = stmt.getResultSet()) {
                            while (rx.next()) {
                                //System.out.println("This isn't going to happen anyways, so...");
                            }
                            rx.close();
                        }
                    }
                    stmt.close();
                }
            }
            rs1.close();
        }
        //System.out.println("Finished with first ResultSet resource, now going on to next...");
        try (ResultSet rs3 = dbMeta.getTables(null, null, "METADATA", null)) {
            if (rs3.next()) {
                //System.out.println("Table "+rs3.getString("TABLE_NAME")+" already exists !!");
            } else {
                //System.out.println("Table METADATA does not exist, now attempting to create...");
                try (Statement stmt = instance.conn.createStatement()) {
                    String tableCreate = "CREATE TABLE METADATA (";
                    tableCreate += "ID INT, ";
                    for (int i = 0; i < 73; i++) {
                        tableCreate += "BIBLEBOOKS" + Integer.toString(i) + " VARCHAR(2000), ";
                    }
                    tableCreate += "LANGUAGES VARCHAR(500), ";
                    tableCreate += "VERSIONS VARCHAR(2000)";
                    tableCreate += ")";
                    boolean tableCreated = stmt.execute(tableCreate);
                    boolean rowsInserted;
                    int count;
                    if (tableCreated == false) {
                        //this is the expected result, is false when it's an update count!
                        count = stmt.getUpdateCount();
                        if (count == -1) {
                            //System.out.println("The result is a ResultSet object or there are no more results.");
                        } else {
                            //this is our expected behaviour: 0 rows affected
                            //System.out.println("The Table Creation statement produced results: "+count+" rows affected.");
                            //Insert a dummy row, because you cannot update what has not been inserted!                                
                            try (Statement stmtX = instance.conn.createStatement()) {
                                stmtX.execute("INSERT INTO METADATA (ID) VALUES (0)");
                                stmtX.close();
                            }

                            HTTPCaller myHTTPCaller = new HTTPCaller();
                            String myResponse;
                            myResponse = myHTTPCaller.getMetaData("biblebooks");
                            if (myResponse != null) {
                                JsonReader jsonReader = Json.createReader(new StringReader(myResponse));
                                JsonObject json = jsonReader.readObject();
                                JsonArray arrayJson = json.getJsonArray("results");
                                if (arrayJson != null) {

                                    ListIterator pIterator = arrayJson.listIterator();
                                    while (pIterator.hasNext()) {
                                        try (Statement stmt2 = instance.conn.createStatement()) {
                                            int index = pIterator.nextIndex();
                                            JsonArray currentJson = (JsonArray) pIterator.next();
                                            String biblebooks_str = currentJson.toString(); //.replaceAll("\"", "\\\\\"");
                                            //System.out.println("BibleGetDB line 267: BIBLEBOOKS"+Integer.toString(index)+"='"+biblebooks_str+"'");
                                            String stmt_str = "UPDATE METADATA SET BIBLEBOOKS"
                                                    + Integer.toString(index) + "='" + biblebooks_str
                                                    + "' WHERE ID=0";
                                            try {
                                                //System.out.println("executing update: "+stmt_str);
                                                int update = stmt2.executeUpdate(stmt_str);
                                                //System.out.println("executeUpdate resulted in: "+Integer.toString(update));
                                            } catch (SQLException ex) {
                                                Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE,
                                                        null, ex);
                                            }
                                            stmt2.close();
                                        }
                                    }
                                }

                                arrayJson = json.getJsonArray("languages");
                                if (arrayJson != null) {
                                    try (Statement stmt2 = instance.conn.createStatement()) {

                                        String languages_str = arrayJson.toString(); //.replaceAll("\"", "\\\\\"");
                                        String stmt_str = "UPDATE METADATA SET LANGUAGES='" + languages_str
                                                + "' WHERE ID=0";
                                        try {
                                            int update = stmt2.executeUpdate(stmt_str);
                                        } catch (SQLException ex) {
                                            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null,
                                                    ex);
                                        }
                                        stmt2.close();
                                    }
                                }
                            }

                            myResponse = myHTTPCaller.getMetaData("bibleversions");
                            if (myResponse != null) {
                                JsonReader jsonReader = Json.createReader(new StringReader(myResponse));
                                JsonObject json = jsonReader.readObject();
                                JsonObject objJson = json.getJsonObject("validversions_fullname");
                                if (objJson != null) {
                                    String bibleversions_str = objJson.toString(); //.replaceAll("\"", "\\\\\"");
                                    try (Statement stmt2 = instance.conn.createStatement()) {
                                        String stmt_str = "UPDATE METADATA SET VERSIONS='" + bibleversions_str
                                                + "' WHERE ID=0";
                                        try {
                                            int update = stmt2.executeUpdate(stmt_str);
                                        } catch (SQLException ex) {
                                            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null,
                                                    ex);
                                        }
                                        stmt2.close();
                                    }

                                    Set<String> versionsabbrev = objJson.keySet();
                                    if (!versionsabbrev.isEmpty()) {
                                        String versionsabbrev_str = "";
                                        for (String s : versionsabbrev) {
                                            versionsabbrev_str += ("".equals(versionsabbrev_str) ? "" : ",")
                                                    + s;
                                        }

                                        myResponse = myHTTPCaller
                                                .getMetaData("versionindex&versions=" + versionsabbrev_str);
                                        if (myResponse != null) {
                                            jsonReader = Json.createReader(new StringReader(myResponse));
                                            json = jsonReader.readObject();
                                            objJson = json.getJsonObject("indexes");
                                            if (objJson != null) {

                                                for (String name : objJson.keySet()) {
                                                    JsonObjectBuilder tempBld = Json.createObjectBuilder();
                                                    JsonObject book_num = objJson.getJsonObject(name);
                                                    tempBld.add("book_num", book_num.getJsonArray("book_num"));
                                                    tempBld.add("chapter_limit",
                                                            book_num.getJsonArray("chapter_limit"));
                                                    tempBld.add("verse_limit",
                                                            book_num.getJsonArray("verse_limit"));
                                                    JsonObject temp = tempBld.build();
                                                    String versionindex_str = temp.toString(); //.replaceAll("\"", "\\\\\"");
                                                    //add new column to METADATA table name+"IDX" VARCHAR(5000)
                                                    //update METADATA table SET name+"IDX" = versionindex_str
                                                    try (Statement stmt3 = instance.conn.createStatement()) {
                                                        String sql = "ALTER TABLE METADATA ADD COLUMN " + name
                                                                + "IDX VARCHAR(5000)";
                                                        boolean colAdded = stmt3.execute(sql);
                                                        if (colAdded == false) {
                                                            count = stmt3.getUpdateCount();
                                                            if (count == -1) {
                                                                //System.out.println("The result is a ResultSet object or there are no more results.");
                                                            } else if (count == 0) {
                                                                //0 rows affected
                                                                stmt3.close();

                                                                try (Statement stmt4 = instance.conn
                                                                        .createStatement()) {
                                                                    String sql1 = "UPDATE METADATA SET " + name
                                                                            + "IDX='" + versionindex_str
                                                                            + "' WHERE ID=0";
                                                                    boolean rowsUpdated = stmt4.execute(sql1);
                                                                    if (rowsUpdated == false) {
                                                                        count = stmt4.getUpdateCount();
                                                                        if (count == -1) {
                                                                            //System.out.println("The result is a ResultSet object or there are no more results.");
                                                                        } else {
                                                                            //should have affected only one row
                                                                            if (count == 1) {
                                                                                //System.out.println(sql1+" seems to have returned true");
                                                                                stmt4.close();
                                                                            }
                                                                        }
                                                                    } else {
                                                                        //returns true only when returning a resultset; should not be the case here
                                                                    }

                                                                }

                                                            }
                                                        } else {
                                                            //returns true only when returning a resultset; should not be the case here
                                                        }

                                                        stmt3.close();
                                                    }
                                                }

                                            }
                                        }

                                    }

                                }
                            }

                        }
                    } else {
                        //is true when it returns a resultset, which shouldn't be the case here
                        ResultSet rx = stmt.getResultSet();
                        while (rx.next()) {
                            //System.out.println("This isn't going to happen anyways, so...");
                        }
                    }
                    stmt.close();
                }
            }
            rs3.close();
        }
        instance.conn.close();
        return true;
    } catch (SQLException ex) {
        if (ex.getSQLState().equals("X0Y32")) {
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.INFO, null,
                    "Table OPTIONS or Table METADATA already exists.  No need to recreate");
            return true;
        } else if (ex.getNextException().getErrorCode() == 45000) {
            //this means we already have a connection, so this is good too
            return true;
        } else {
            //Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex.getMessage() + " : " + Arrays.toString(ex.getStackTrace()));
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
}

From source file:csg.files.CSGFiles.java

@Override
public void loadData(AppDataComponent data, AppDataComponent recData, AppDataComponent schData,
        AppDataComponent projectData, AppDataComponent courseData, String filePath) throws IOException {
    // CLEAR THE OLD DATA OUT
    TAData dataManager = (TAData) data;//ww w  . j  a  v a 2s. com
    ScheduleData schDataManager = (ScheduleData) schData;
    RecitationData recDataManager = (RecitationData) recData;
    ProjectData projectDataManager = (ProjectData) projectData;
    CourseData courseDataManager = (CourseData) courseData;
    workspace = (CSGWorkspace) app.getWorkspaceComponent();

    // LOAD THE JSON FILE WITH ALL THE DATA
    JsonObject json = loadJSONFile(filePath);

    // LOAD THE START AND END HOURS
    String startHour = json.getString(JSON_START_HOUR);
    String endHour = json.getString(JSON_END_HOUR);
    dataManager.initHours(startHour, endHour);

    // NOW RELOAD THE WORKSPACE WITH THE LOADED DATA
    app.getWorkspaceComponent().reloadWorkspace(app.getTADataComponent());

    int startDay = json.getInt(JSON_STARTDAY);
    int startMonth = json.getInt(JSON_STARTMONTH);
    int startYear = json.getInt(JSON_STARTYEAR);

    courseDataManager.setStartDay(startDay);
    courseDataManager.setStartMonth(startMonth);
    courseDataManager.setStartYear(startYear);

    if (startDay != 0 && startMonth != 0 && startYear != 0) {
        LocalDate startDate = LocalDate.of(startYear, startMonth, startDay);
        workspace.getMonStartDatePicker().setValue(startDate);
    } else {
        workspace.getMonStartDatePicker().setValue(null);
    }

    int endDay = json.getInt(JSON_ENDDAY);
    int endMonth = json.getInt(JSON_ENDMONTH);
    int endYear = json.getInt(JSON_ENDYEAR);

    courseDataManager.setEndDay(endDay);
    courseDataManager.setEndMonth(endMonth);
    courseDataManager.setEndYear(endYear);

    if (endDay != 0 && endMonth != 0 && endYear != 0) {
        LocalDate endDate = LocalDate.of(endYear, endMonth, endDay);
        workspace.getFriEndDatePicker().setValue(endDate);
    } else {
        workspace.getFriEndDatePicker().setValue(null);
    }

    // NOW LOAD ALL THE UNDERGRAD TAs
    JsonArray jsonTAArray = json.getJsonArray(JSON_UNDERGRAD_TAS);
    for (int i = 0; i < jsonTAArray.size(); i++) {
        JsonObject jsonTA = jsonTAArray.getJsonObject(i);
        String name = jsonTA.getString(JSON_NAME);
        String email = jsonTA.getString(JSON_EMAIL);
        boolean ug = jsonTA.getBoolean(JSON_UG);
        BooleanProperty isUndergrad = new SimpleBooleanProperty();
        isUndergrad.setValue(ug);
        dataManager.addTA(name, email, isUndergrad);
    }

    // AND THEN ALL THE OFFICE HOURS
    JsonArray jsonOfficeHoursArray = json.getJsonArray(JSON_OFFICE_HOURS);
    for (int i = 0; i < jsonOfficeHoursArray.size(); i++) {
        JsonObject jsonOfficeHours = jsonOfficeHoursArray.getJsonObject(i);
        String day = jsonOfficeHours.getString(JSON_DAY);
        String time = jsonOfficeHours.getString(JSON_TIME);
        String name = jsonOfficeHours.getString(JSON_NAME);
        dataManager.addOfficeHoursReservation(day, time, name);
    }

    JsonArray jsonRecitationArray = json.getJsonArray(JSON_RECITATION);
    for (int i = 0; i < jsonRecitationArray.size(); i++) {
        JsonObject jsonRec = jsonRecitationArray.getJsonObject(i);
        String section = jsonRec.getString(JSON_SECTION);
        String instructor = jsonRec.getString(JSON_INSTRUCTOR);
        String dayTime = jsonRec.getString(JSON_DAYTIME);
        String location = jsonRec.getString(JSON_LOCATION);
        String firstTA = jsonRec.getString(JSON_FIRSTTA);
        String secondTA = jsonRec.getString(JSON_SECONDTA);
        recDataManager.addRecitation(section, instructor, dayTime, location, firstTA, secondTA);
    }

    JsonArray jsonScheduleArray = json.getJsonArray(JSON_SCHEDULEITEM);
    for (int i = 0; i < jsonScheduleArray.size(); i++) {
        JsonObject jsonSch = jsonScheduleArray.getJsonObject(i);
        String type = jsonSch.getString(JSON_TYPE);
        int month = jsonSch.getInt(JSON_MONTH);
        int day = jsonSch.getInt(JSON_DAY);
        int year = jsonSch.getInt(JSON_YEAR);
        String time = jsonSch.getString(JSON_TIME);
        String title = jsonSch.getString(JSON_TITLE);
        String topic = jsonSch.getString(JSON_TOPIC);
        String link = jsonSch.getString(JSON_LINK);
        String criteria = jsonSch.getString(JSON_CRITERIA);
        schDataManager.addScheduleItem(type, LocalDate.of(year, month, day), time, title, topic, link,
                criteria);
    }

    JsonArray jsonTeamArray = json.getJsonArray(JSON_TEAMS);
    for (int i = 0; i < jsonTeamArray.size(); i++) {
        JsonObject jsonTeam = jsonTeamArray.getJsonObject(i);
        String name = jsonTeam.getString(JSON_NAME);
        String color = jsonTeam.getString(JSON_COLOR);
        String textColor = jsonTeam.getString(JSON_TEXTCOLOR);
        String link = jsonTeam.getString(JSON_LINK);
        projectDataManager.addTeam(name, color, textColor, link);
    }

    JsonArray jsonStudentArray = json.getJsonArray(JSON_STUDENTS);
    for (int i = 0; i < jsonStudentArray.size(); i++) {
        JsonObject jsonStudent = jsonStudentArray.getJsonObject(i);
        String firstName = jsonStudent.getString(JSON_FIRSTNAME);
        String lastName = jsonStudent.getString(JSON_LASTNAME);
        String team = jsonStudent.getString(JSON_TEAM);
        String role = jsonStudent.getString(JSON_ROLE);
        projectDataManager.addStudent(firstName, lastName, team, role);
    }

    JsonArray jsonTemplateArray = json.getJsonArray(JSON_COURSETEMPLATE);
    courseDataManager.getTemplates().clear();
    for (int i = 0; i < jsonTemplateArray.size(); i++) {
        JsonObject jsonTemplate = jsonTemplateArray.getJsonObject(i);
        boolean use = jsonTemplate.getBoolean(JSON_USE);
        String navbar = jsonTemplate.getString(JSON_NAVBAR);
        String fileName = jsonTemplate.getString(JSON_FILENAME);
        String script = jsonTemplate.getString(JSON_SCRIPT);
        courseDataManager.addTemplate(use, navbar, fileName, script);
    }

    JsonObject courseJson = json.getJsonObject(JSON_COURSE);
    courseDataManager.setNumber(courseJson.getString(JSON_NUMBER));
    courseDataManager.setSemester(courseJson.getString(JSON_SEMESTER));
    courseDataManager.setSubject(courseJson.getString(JSON_SUBJECT));
    courseDataManager.setYear(courseJson.getString(JSON_YEAR));
    courseDataManager.setTitle(courseJson.getString(JSON_TITLE));
    courseDataManager.setInsName(courseJson.getString(JSON_INSTRUCTORNAME));
    courseDataManager.setInsHome(courseJson.getString(JSON_INSTRUCTORHOME));
    courseDataManager.setBannerLink(courseJson.getString(JSON_BANNER));
    courseDataManager.setLeftFooterLink(courseJson.getString(JSON_LEFTFOOTER));
    courseDataManager.setRightFooterLink(courseJson.getString(JSON_RIGHTFOOTER));
    courseDataManager.setTemplateDir(courseJson.getString(JSON_TEMPLATEDIR));
    courseDataManager.setExportDir(courseJson.getString(JSON_EXPORTDIR));
    courseDataManager.setStyleSheet(courseJson.getString(JSON_STYLESHEET));

    workspace.getSubjectCombo().setValue(courseDataManager.getSubject());
    workspace.getNumCombo().setValue(courseDataManager.getNumber());
    workspace.getSemCombo().setValue(courseDataManager.getSemester());
    workspace.getYearCombo().setValue(courseDataManager.getYear());
    workspace.getTitleTextField().setText(courseDataManager.getTitle());
    workspace.getInsNameTextField().setText(courseDataManager.getInsName());
    workspace.getInsHomeTextField().setText(courseDataManager.getInsHome());
    workspace.getStyleSheetCombo().setValue(courseDataManager.getStyleSheet());

    if (!courseDataManager.getBannerLink().isEmpty()) {
        FileInputStream bannerLocation = new FileInputStream(courseJson.getString(JSON_BANNER));
        Image newImg = new Image(bannerLocation);
        workspace.getBannerImage().setImage(newImg);
    } else {
        workspace.getBannerImage().setImage(null);
    }

    if (!courseDataManager.getLeftFooterLink().isEmpty()) {
        FileInputStream leftFooterLocation = new FileInputStream(courseJson.getString(JSON_LEFTFOOTER));
        Image newImg2 = new Image(leftFooterLocation);
        workspace.getLeftFooterImage().setImage(newImg2);
    } else {
        workspace.getLeftFooterImage().setImage(null);
    }

    if (!courseDataManager.getRightFooterLink().isEmpty()) {
        FileInputStream rightFooterLocation = new FileInputStream(courseJson.getString(JSON_RIGHTFOOTER));
        Image newImg3 = new Image(rightFooterLocation);
        workspace.getRightFooterImage().setImage(newImg3);
    } else {
        workspace.getRightFooterImage().setImage(null);
    }
    workspace.getCourseTemplateLocLabel().setText(courseJson.getString(JSON_TEMPLATEDIR));
    workspace.getExportLabel().setText(courseJson.getString(JSON_EXPORTDIR));

}