Example usage for javax.json JsonObject toString

List of usage examples for javax.json JsonObject toString

Introduction

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

Prototype

@Override
String toString();

Source Link

Document

Returns JSON text for this JSON value.

Usage

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java

@Test
public void handleExecuteNestedCleanupError() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());/*w  ww  . j  a v  a 2s.c o m*/
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), anyString(), any()))
            .thenThrow(new DockerException("FAIL1"));
    PowerMockito.doThrow(new DockerException("FAIL2")).when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected failure", Boolean.FALSE, responseBody.getBoolean("success"));
    assertEquals("Wrong message", "FAIL1", responseBody.getString("message"));
}

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java

@Test
public void handleExecuteFailure() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());//from   w w w .j  a  va  2  s . co  m
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), anyString(), any())).thenAnswer(i -> {
        if (i.getArgument(2).equals("chown")) {
            return 0;
        } else {
            return 1;
        }
    });
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected failure", Boolean.FALSE, responseBody.getBoolean("success"));
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", "root", "chown", "-R", "4:5", ".");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", "root", "chown", "-R", "7:8", ".");
}

From source file:io.bibleget.BibleGetDB.java

public boolean renewMetaData() {
    if (instance.connect()) {
        try {//from ww  w.ja  va  2  s .c om
            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:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java

@Test
public void handleExecute() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());/*  w  w  w. ja v  a  2 s  .  c o  m*/
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), any())).thenReturn(0);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    when(DockerUtils.getCommandString(anyString(), any())).thenCallRealMethod();
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config", Json.createObjectBuilder()
                    .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                    .add("COMMAND", Json.createObjectBuilder().add("value", "echo").build())
                    .add("ARGUMENTS", Json.createObjectBuilder().add("value", "Hello\nWorld").build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables",
                            Json.createObjectBuilder().add("TEST1", "value1").add("TEST2", "value2").build())
                    .build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.pullImage("ubuntu:latest");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.createContainer("ubuntu:latest",
            Paths.get(System.getProperty("user.dir"), "pipelines/test").toAbsolutePath().toString(),
            Stream.<Map.Entry<String, String>>builder().add(new SimpleEntry<>("TEST1", "value1"))
                    .add(new SimpleEntry<>("TEST2", "value2")).build()
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.getContainerUid("123");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", "root", "chown", "-R", "4:5", ".");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", null, "echo", "Hello", "World");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", "root", "chown", "-R", "7:8", ".");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.removeContainer("123");
    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected success", Boolean.TRUE, responseBody.getBoolean("success"));
    assertEquals("Wrong message", "Command 'echo 'Hello' 'World'' completed with status 0",
            Json.createReader(new StringReader(response.responseBody())).readObject().getString("message"));
}

From source file:io.bibleget.BibleGetDB.java

public boolean initialize() {

    try {/*from  w ww.j a v a  2 s.  c om*/
        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:at.porscheinformatik.sonarqube.licensecheck.webservice.mavendependency.MavenDependencyEditAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json/*from  ww w.j  a  va2 s .  com*/
            .createReader(new StringReader(request.param(MavenDependencyConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();

    boolean oldKeyIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_OLD_KEY));
    boolean newKeyIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_NEW_KEY));
    boolean newLicenseIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_NEW_LICENSE));

    if (oldKeyIsNotBlank && newKeyIsNotBlank && newLicenseIsNotBlank) {
        MavenDependency newMavenDependency = new MavenDependency(
                jsonObject.getString(MavenDependencyConfiguration.PROPERTY_NEW_KEY),
                jsonObject.getString(MavenDependencyConfiguration.PROPERTY_NEW_LICENSE));

        if (!mavenDependencySettingsService.hasDependency(newMavenDependency)) {
            mavenDependencySettingsService
                    .deleteMavenDependency(jsonObject.getString(MavenDependencyConfiguration.PROPERTY_OLD_KEY));
            mavenDependencySettingsService.addMavenDependency(newMavenDependency);
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
            LOGGER.info(MavenDependencyConfiguration.INFO_EDIT_SUCCESS + jsonObject.toString());
        } else {
            LOGGER.error(MavenDependencyConfiguration.ERROR_EDIT_ALREADY_EXISTS + jsonObject.toString());
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
        }

    } else {
        LOGGER.error(MavenDependencyConfiguration.ERROR_ADD_INVALID_INPUT + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}

From source file:at.porscheinformatik.sonarqube.licensecheck.webservice.mavenlicense.MavenLicenseEditAction.java

@Override
public void handle(Request request, Response response) throws Exception {
    JsonReader jsonReader = Json.createReader(new StringReader(request.param(MavenLicenseConfiguration.PARAM)));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();/*from   w  w  w.  j  a v  a2  s .c om*/

    boolean oldRegexIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_OLD_REGEX));
    boolean newRegexIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_NEW_REGEX));
    boolean newKeyIsNotBlank = StringUtils
            .isNotBlank(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_NEW_KEY));

    if (oldRegexIsNotBlank && newRegexIsNotBlank && newKeyIsNotBlank) {
        MavenLicense newMavenLicense = new MavenLicense(
                jsonObject.getString(MavenLicenseConfiguration.PROPERTY_NEW_REGEX),
                jsonObject.getString(MavenLicenseConfiguration.PROPERTY_NEW_KEY));

        if (!mavenLicenseSettingsService.checkIfListContains(newMavenLicense)) {
            mavenLicenseSettingsService
                    .deleteMavenLicense(jsonObject.getString(MavenLicenseConfiguration.PROPERTY_OLD_REGEX));
            mavenLicenseSettingsService.addMavenLicense(newMavenLicense);
            mavenLicenseSettingsService.sortMavenLicenses();
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_OK);
            LOGGER.info(MavenLicenseConfiguration.INFO_EDIT_SUCCESS + jsonObject.toString());
        } else {
            LOGGER.error(MavenLicenseConfiguration.ERROR_EDIT_ALREADY_EXISTS + jsonObject.toString());
            response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
        }

    } else {
        LOGGER.error(MavenLicenseConfiguration.ERROR_EDIT_INVALID_INPUT + jsonObject.toString());
        response.stream().setStatus(HTTPConfiguration.HTTP_STATUS_NOT_MODIFIED);
    }
}

From source file:edu.umich.ctools.sectionsUtilityTool.FriendServlet.java

private void friendApiConnectionLogic(HttpServletRequest request, HttpServletResponse response, Friend myFriend)
        throws IOException {
    String pathInfo = request.getPathInfo();
    PrintWriter out = response.getWriter();
    JsonObject json;
    switch (pathInfo) {
    case "/friendCreate":
        String friendInviteEmail = request.getParameter(PARAMETER_ID);
        String friendInstructorEmail = request.getParameter(PARAMETER_INSTRUCTOR_EMAIL);
        String friendInstructorFirstName = request.getParameter(PARAMETER_INSTRUCTOR_FIRST_NAME);
        String friendInstructorLastName = request.getParameter(PARAMETER_INSTRUCTOR_LAST_NAME);
        String friendNotifyInstructor = request.getParameter(PARAMETER_NOTIFY_INSTRUCTOR);
        if (friendInviteEmail == null || friendInstructorEmail == null || friendInstructorFirstName == null
                || friendInstructorLastName == null) {
            response.setStatus(400);/*  www  .  ja v a2s .  com*/
            json = Json.createObjectBuilder().add("message", "requestError")
                    .add("detailedMessage", "request error: required parameters for request not specified")
                    .add("FriendURL", Friend.friendUrl).build();
        } else {
            json = doFriendLogic(myFriend, friendInviteEmail, friendInstructorEmail, friendInstructorFirstName,
                    friendInstructorLastName, friendNotifyInstructor);
        }
        break;
    default:
        response.setStatus(400);
        json = Json.createObjectBuilder().add("message", "request error").build();
        break;
    }
    out.print(json.toString());
    out.flush();
}

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

/**
 * Return information on the Fabric Certificate Authority.
 * No credentials are needed for this API.
 *
 * @return {@link HFCAInfo}//from   ww  w . j  a va  2s  . c o m
 * @throws InfoException
 * @throws InvalidArgumentException
 */

public HFCAInfo info() throws InfoException, InvalidArgumentException {

    logger.debug(format("info url:%s", url));
    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    setUpSSL();

    try {

        JsonObjectBuilder factory = Json.createObjectBuilder();

        if (caName != null) {
            factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
        }
        JsonObject body = factory.build();

        String responseBody = httpPost(url + HFCA_INFO, body.toString(), (UsernamePasswordCredentials) null);

        logger.debug("response:" + responseBody);

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

        boolean success = jsonst.getBoolean("success");
        logger.debug(format("[HFCAClient] enroll success:[%s]", success));

        if (!success) {
            throw new EnrollmentException(format("FabricCA failed info %s", url));
        }

        JsonObject result = jsonst.getJsonObject("result");
        if (result == null) {
            throw new InfoException(
                    format("FabricCA info error  - response did not contain a result url %s", url));
        }

        String caName = result.getString("CAName");
        String caChain = result.getString("CAChain");
        String version = null;
        if (result.containsKey("Version")) {
            version = result.getString("Version");
        }
        String issuerPublicKey = null;
        if (result.containsKey("IssuerPublicKey")) {
            issuerPublicKey = result.getString("IssuerPublicKey");
        }
        String issuerRevocationPublicKey = null;
        if (result.containsKey("IssuerRevocationPublicKey")) {
            issuerRevocationPublicKey = result.getString("IssuerRevocationPublicKey");
        }

        logger.info(format("CA Name: %s, Version: %s, issuerPublicKey: %s, issuerRevocationPublicKey: %s",
                caName, caChain, issuerPublicKey, issuerRevocationPublicKey));
        return new HFCAInfo(caName, caChain, version, issuerPublicKey, issuerRevocationPublicKey);

    } catch (Exception e) {
        InfoException ee = new InfoException(format("Url:%s, Failed to get info", url), e);
        logger.error(e.getMessage(), e);
        throw ee;
    }

}

From source file:eu.forgetit.middleware.component.Condensator.java

public void imageClustering_bkp(Exchange exchange) {

    logger.debug("New message retrieved");

    JsonObject headers = MessageTools.getHeaders(exchange);

    long taskId = headers.getInt("taskId");
    scheduler.updateTask(taskId, TaskStatus.RUNNING, "IMAGE CLUSTERING", null);

    MessageTools.setHeaders(exchange, headers);

    JsonObject jsonBody = MessageTools.getBody(exchange);

    if (jsonBody != null) {

        try {/*from  w  w w  .  ja va  2s.com*/

            String jsonNofImagesElement = jsonBody.getString("numOfImages");
            String minCLusteringImages = headers.getString("minClusteringImages");

            int nofImages = 0;
            int minNofImages = 0;

            if (jsonNofImagesElement != null)
                nofImages = Integer.parseInt(jsonNofImagesElement);

            if (minCLusteringImages != null)
                minNofImages = Integer.parseInt(minCLusteringImages);
            else
                minNofImages = 0;

            String jsonImageAnalysisResult = jsonBody.getString("imageAnalysis-all");
            if (jsonImageAnalysisResult != null)
                imageAnalysisResult = jsonImageAnalysisResult;
            logger.debug("Retrieved Image Analysis Result: " + imageAnalysisResult);

            String jsonMetadataDir = jsonBody.getString("sipMetadataDir");
            if (jsonMetadataDir != null)
                sipMetadataDirPath = jsonMetadataDir;
            logger.debug("Retrieved SIP Metadata Directory: " + sipMetadataDirPath);

            if (nofImages >= minNofImages) {

                logger.debug("Executing Image Collection Clustering");

                String response = service.request(imageAnalysisResult);

                logger.debug("Clustering result:\n" + response);

                File resultFile = new File(sipMetadataDirPath, "clustering.xml");

                FileUtils.writeStringToFile(resultFile, response);

                JsonObjectBuilder job = Json.createObjectBuilder();

                job.add("clustering", resultFile.getAbsolutePath());

                for (Entry<String, JsonValue> entry : jsonBody.entrySet()) {
                    job.add(entry.getKey(), entry.getValue());
                }

                exchange.getIn().setBody(jsonBody.toString());

            } else {

                logger.debug("Found only " + nofImages + " images, below threshold (" + minCLusteringImages
                        + ")... skipping.");
            }

        } catch (NumberFormatException | IOException e) {

            e.printStackTrace();
        }

    } else {

        JsonObjectBuilder job = Json.createObjectBuilder().add("taskStatus", TaskStatus.FAILED.toString());

        for (Entry<String, JsonValue> entry : headers.entrySet()) {
            job.add(entry.getKey(), entry.getValue());
        }

        MessageTools.setHeaders(exchange, headers);

    }

}