List of usage examples for javax.json JsonObjectBuilder build
JsonObject build();
From source file:skillpro.asset.views.wizardpages.ConfirmationPage.java
private void registerSEE(SEE see) throws ClientProtocolException, IOException { System.out.println("SEE[seeID: " + see.getSeeID() + ", opcuaMES: " + see.getMESCommunication().getSecondElement() + "opcua: " + see.getOpcUAAddress() + ", amlFile: " + !see.getAmlDescription().isEmpty() + "]"); String serviceName = "registerSEE"; JsonObjectBuilder jsonBuilder = Json.createObjectBuilder(); if (see.getSeeID() != null && !see.getSeeID().trim().isEmpty()) { jsonBuilder.add("seeId", see.getSeeID() == null ? UUID.randomUUID().toString() : see.getSeeID()); }/*from w ww .ja v a 2 s . c om*/ if (see.getMESCommunication().getFirstElement() == MESCommType.OPCUA) { jsonBuilder.add("opcuaAddress", see.getMESCommunication().getSecondElement()); } if (see.getResource() != null) { jsonBuilder.add("assetTypeNames", see.getResource().getName()); } jsonBuilder.add("simulation", see.isSimulation() + ""); if (see.getAmlDescription() != null && !see.getAmlDescription().trim().isEmpty()) { jsonBuilder.add("amlFile", see.getAmlDescription()); } HttpPost request = new HttpPost(AMSServiceUtility.serviceAddress + serviceName); request.setEntity(new StringEntity(jsonBuilder.build().toString(), "UTF-8")); System.out.println(request.getRequestLine() + " ====================================="); request.setHeader("Content-type", "application/json"); HttpClient client = HttpClientBuilder.create().build(); ; client.execute(request); }
From source file:com.open.shift.support.controller.SupportResource.java
@GET @Produces(MediaType.APPLICATION_JSON)/*ww w. ja v a 2s . c o m*/ @Path("areachart") public JsonObject generateAreaChart() throws Exception { System.out.println("The injected hashcode is " + this.supportDAO); int usa[] = { 0, 0, 0, 0, 0, 6, 11, 32, 110, 235, 369, 640, 1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468, 20434, 24126, 27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662, 26956, 27912, 28999, 28965, 27826, 25579, 25722, 24826, 24605, 24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344, 23586, 22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950, 10871, 10824, 10577, 10527, 10475, 10421, 10358, 10295, 10104 }; int ussr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471, 3322, 4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478, 15915, 17385, 19055, 21205, 23044, 25393, 27935, 30062, 32049, 33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000, 35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000, 21000, 20000, 19000, 18000, 18000, 17000, 16000 }; URL u = ctx.getResource("/WEB-INF/classes/templates/area.json"); String areaJson = null; if (OS.indexOf("win") >= 0) { areaJson = u.toString().substring(6); } else if (OS.indexOf("nux") >= 0) { areaJson = u.toString().substring(5); } System.out.println("The areaJson is " + areaJson); JsonReader reader = Json.createReader(new FileReader(areaJson)); JsonObject main = reader.readObject(); JsonObject yaxis = main.getJsonObject("yAxis"); JsonObjectBuilder title = Json.createObjectBuilder().add("text", "US and USSR Deposits"); JsonObjectBuilder ytitle = Json.createObjectBuilder().add("text", "Amount Deposisted"); JsonArrayBuilder usaData = Json.createArrayBuilder(); for (Integer usa1 : usa) { usaData.add(usa1); } JsonArrayBuilder ussrData = Json.createArrayBuilder(); for (Integer uss1 : ussr) { ussrData.add(uss1); } JsonObjectBuilder usaSeries = Json.createObjectBuilder().add("name", "USA").add("data", usaData); JsonObjectBuilder ussrSeries = Json.createObjectBuilder().add("name", "USSR").add("data", ussrData); JsonArrayBuilder series = Json.createArrayBuilder().add(usaSeries).add(ussrSeries); //main json object builder JsonObjectBuilder mainJsonObj = Json.createObjectBuilder(); for (Map.Entry<String, JsonValue> mainObj : main.entrySet()) { String key = mainObj.getKey(); JsonValue value = mainObj.getValue(); if (key.equalsIgnoreCase("yAxis")) { String yaxisLabel = "labels"; mainJsonObj.add(key, Json.createObjectBuilder().add(yaxisLabel, yaxis.getJsonObject(yaxisLabel)) .add("title", ytitle.build())); } else { mainJsonObj.add(key, value); } } mainJsonObj.add("title", title.build()).add("series", series.build()); return mainJsonObj.build(); }
From source file:io.hops.hopsworks.api.pythonDeps.PythonDepsService.java
@GET @Path("/environmentTypes") @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) @Produces(MediaType.APPLICATION_JSON)/*from w w w. ja v a2 s .c o m*/ public Response environmentTypes() throws ServiceException { JsonObjectBuilder response = Json.createObjectBuilder(); String cpuHost = hostsFacade.findCPUHost(); if (cpuHost != null) { response.add("CPU", true); } else { response.add("CPU", false); } String gpuHost = hostsFacade.findGPUHost(); if (gpuHost != null) { response.add("GPU", true); } else { response.add("GPU", false); } if (cpuHost == null && gpuHost == null) { throw new ServiceException(RESTCodes.ServiceErrorCode.HOST_NOT_FOUND, Level.WARNING, "Could not find any CPU or GPU host"); } return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(response.build()).build(); }
From source file:org.grogshop.services.endpoints.impl.ShopItemsServiceImpl.java
@Override public Response get(@PathParam("id") Long item_id) throws ServiceException { Item i = itemsService.getById(item_id); JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); jsonObjectBuilder.add("id", (i.getId() == null) ? "" : i.getId().toString()) .add("user_id", (i.getUser().getId() == null) ? "" : i.getUser().getId().toString()) .add("user_email", (i.getUser().getEmail() == null) ? "" : i.getUser().getEmail()) .add("club_id", (i.getClub().getId() == null) ? "" : i.getClub().getId().toString()) .add("type", (i.getType() == null) ? "" : i.getType().toString()) .add("name", (i.getName() == null) ? "" : i.getName()) .add("description", (i.getDescription() == null) ? "" : i.getDescription()) .add("hasImage", i.hasImage()) .add("minPrice", (i.getMinPrice() == null) ? "" : i.getMinPrice().toString()) .add("maxPrice", (i.getMaxPrice() == null) ? "" : i.getMaxPrice().toString()); if (i.getTags() != null) { JsonArrayBuilder jsonArrayBuilderInterest = Json.createArrayBuilder(); for (String s : i.getTags()) { jsonArrayBuilderInterest.add(Json.createObjectBuilder().add("text", s)); }/*from w w w. j a v a2 s . c o m*/ jsonObjectBuilder.add("tags", jsonArrayBuilderInterest); } JsonObject build = jsonObjectBuilder.build(); return Response.ok(build.toString()).build(); }
From source file:io.bibleget.BibleGetDB.java
public boolean renewMetaData() { if (instance.connect()) { try {/*from w ww. j a v a 2 s.com*/ 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:eu.forgetit.middleware.component.Condensator.java
public void videoClustering(Exchange exchange) { System.out.println("New message retrieved"); logger.debug("New message retrieved"); JsonObject jsonBody = MessageTools.getBody(exchange); JsonObjectBuilder job = Json.createObjectBuilder(); for (Entry<String, JsonValue> entry : jsonBody.entrySet()) { job.add(entry.getKey(), entry.getValue()); }/*w ww.ja v a2 s .c o m*/ if (jsonBody != null) { String videoXMLPath = jsonBody.getString("video_xmls"); System.out.println("Retrieved Video XMLs Path: " + videoXMLPath); //String method = jsonBody.getString("method"); //System.out.println("Retrieved VAM: "+method); // ONE video per call if (videoXMLPath != null && !videoXMLPath.isEmpty()) { System.out.println("Executing Video Clustering Method: "); String response_temp = service.video_clustering_request(videoXMLPath); System.out.println("Clustering method result:\n" + response_temp); // callid is returned at the response String callid; String[] callid_tmp = response_temp.split("::"); callid = callid_tmp[1].trim(); String response = service.video_clustering_result(callid); logger.debug("Video Clustering result:\n" + response); job.add("result", response); } else { System.out.println("Unable to process video xmls, wrong request"); job.add("result", "Unable to process video, wrong request"); } exchange.getOut().setBody(job.build().toString()); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); } }
From source file:io.bibleget.BibleGetDB.java
public JsonObject getOptions() { if (instance.connect()) { try {/*from w w w.ja v a 2s .c om*/ JsonObjectBuilder myOptionsTable; JsonArrayBuilder myRows; try (Statement stmt = instance.conn.createStatement(); ResultSet rsOps = stmt.executeQuery("SELECT * FROM OPTIONS")) { Iterator itColNames = colNames.iterator(); Iterator itDataTypes = colDataTypes.iterator(); myOptionsTable = Json.createObjectBuilder(); myRows = Json.createArrayBuilder(); while (rsOps.next()) { //System.out.println("Getting a row from the table."); JsonObjectBuilder thisRow = Json.createObjectBuilder(); while (itColNames.hasNext() && itDataTypes.hasNext()) { String colName = (String) itColNames.next(); Class dataType = (Class) itDataTypes.next(); if (dataType == String.class) { thisRow.add(colName, rsOps.getString(colName)); } if (dataType == Integer.class) { thisRow.add(colName, rsOps.getInt(colName)); } if (dataType == Boolean.class) { thisRow.add(colName, rsOps.getBoolean(colName)); } //System.out.println(colName + " <" + dataType + ">"); } thisRow.build(); myRows.add(thisRow); } rsOps.close(); stmt.close(); instance.disconnect(); myRows.build(); return myOptionsTable.add("rows", myRows).build(); } } catch (SQLException ex) { Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex); return null; } } return null; }
From source file:io.hops.hopsworks.api.jobs.JobService.java
@GET @Path("/getLogByJobId/{jobId}/{submissionTime}/{type}") @Produces(MediaType.APPLICATION_JSON)/*from w w w . j a va 2 s .c om*/ @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response getLogByJobId(@PathParam("jobId") Integer jobId, @PathParam("submissionTime") String submissionTime, @PathParam("type") String type) throws GenericException, JobException { if (jobId == null || jobId <= 0) { throw new IllegalArgumentException("jobId must be a non-null positive integer number."); } if (submissionTime == null) { throw new IllegalArgumentException("submissionTime was not provided."); } Jobs job = jobFacade.find(jobId); if (job == null) { throw new JobException(RESTCodes.JobErrorCode.JOB_NOT_FOUND, Level.FINE, "JobId:" + jobId); } SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy"); Date date; try { date = sdf.parse(submissionTime); } catch (ParseException ex) { throw new GenericException(RESTCodes.GenericErrorCode.INCOMPLETE_REQUEST, Level.WARNING, "Cannot get log. Incorrect submission time. Error offset:" + ex.getErrorOffset(), ex.getMessage(), ex); } Execution execution = exeFacade.findByJobIdAndSubmissionTime(date, job); if (execution == null) { throw new JobException(RESTCodes.JobErrorCode.JOB_EXECUTION_NOT_FOUND, Level.FINE, "JobId " + jobId); } if (!execution.getState().isFinalState()) { throw new JobException(RESTCodes.JobErrorCode.JOB_EXECUTION_INVALID_STATE, Level.FINE, "Job still running."); } if (!execution.getJob().getProject().equals(this.project)) { throw new JobException(RESTCodes.JobErrorCode.JOB_ACCESS_ERROR, Level.FINE, "Requested execution does not belong to a job of project: " + project.getName()); } JsonObjectBuilder arrayObjectBuilder = Json.createObjectBuilder(); DistributedFileSystemOps dfso = null; try { dfso = dfs.getDfsOps(); readLog(execution, type, dfso, arrayObjectBuilder); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } finally { if (dfso != null) { dfso.close(); } } return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(arrayObjectBuilder.build()) .build(); }
From source file:io.hops.hopsworks.api.jobs.JobService.java
@GET @Path("/getLog/{appId}/{type}") @Produces(MediaType.APPLICATION_JSON)/*from ww w. j a va 2s . com*/ @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response getLog(@PathParam("appId") String appId, @PathParam("type") String type) throws JobException { if (Strings.isNullOrEmpty(appId)) { throw new IllegalArgumentException("appId cannot be null or empty."); } Execution execution = exeFacade.findByAppId(appId); if (execution == null) { throw new JobException(RESTCodes.JobErrorCode.JOB_EXECUTION_NOT_FOUND, Level.FINE, "AppId: " + appId); } if (!execution.getState().isFinalState()) { throw new JobException(RESTCodes.JobErrorCode.JOB_EXECUTION_INVALID_STATE, Level.FINE, "Job still running."); } if (!execution.getJob().getProject().equals(this.project)) { throw new JobException(RESTCodes.JobErrorCode.JOB_ACCESS_ERROR, Level.FINE, "Requested execution does not belong to a job of project: " + project.getName()); } JsonObjectBuilder arrayObjectBuilder = Json.createObjectBuilder(); DistributedFileSystemOps dfso = null; try { dfso = dfs.getDfsOps(); readLog(execution, type, dfso, arrayObjectBuilder); } catch (IOException ex) { Logger.getLogger(JobService.class.getName()).log(Level.SEVERE, null, ex); } finally { if (dfso != null) { dfso.close(); } } return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(arrayObjectBuilder.build()) .build(); }
From source file:io.bibleget.BibleGetDB.java
public boolean initialize() { try {//from w ww. j a va 2s. 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; } } }