List of usage examples for javax.json JsonArray getJsonObject
JsonObject getJsonObject(int index);
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * gets all identities that the registrar is allowed to see * * @param registrar The identity of the registrar (i.e. who is performing the registration). * @return the identity that was requested * @throws IdentityException if adding an identity fails. * @throws InvalidArgumentException Invalid (null) argument specified *//*from www .j a v a 2 s . c o m*/ public Collection<HFCAIdentity> getHFCAIdentities(User registrar) throws IdentityException, InvalidArgumentException { if (registrar == null) { throw new InvalidArgumentException("Registrar should be a valid member"); } logger.debug(format("identity url: %s, registrar: %s", url, registrar.getName())); try { JsonObject result = httpGet(HFCAIdentity.HFCA_IDENTITY, registrar); Collection<HFCAIdentity> allIdentities = new ArrayList<>(); JsonArray identities = result.getJsonArray("identities"); if (identities != null && !identities.isEmpty()) { for (int i = 0; i < identities.size(); i++) { JsonObject identity = identities.getJsonObject(i); HFCAIdentity idObj = new HFCAIdentity(identity); allIdentities.add(idObj); } } logger.debug(format("identity url: %s, registrar: %s done.", url, registrar)); return allIdentities; } catch (HTTPException e) { String msg = format("[HTTP Status Code: %d] - Error while getting all users from url '%s': %s", e.getStatusCode(), url, e.getMessage()); IdentityException identityException = new IdentityException(msg, e); logger.error(msg); throw identityException; } catch (Exception e) { String msg = format("Error while getting all users from url '%s': %s", url, e.getMessage()); IdentityException identityException = new IdentityException(msg, e); logger.error(msg); throw identityException; } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * Gets all certificates that the registrar is allowed to see and based on filter parameters that * are part of the certificate request./* www . j a v a 2 s. c o m*/ * * @param registrar The identity of the registrar (i.e. who is performing the registration). * @param req The certificate request that contains filter parameters * @return HFCACertificateResponse object * @throws HFCACertificateException Failed to process get certificate request */ public HFCACertificateResponse getHFCACertificates(User registrar, HFCACertificateRequest req) throws HFCACertificateException { try { logger.debug(format("certificate url: %s, registrar: %s", HFCA_CERTIFICATE, registrar.getName())); JsonObject result = httpGet(HFCA_CERTIFICATE, registrar, req.getQueryParameters()); int statusCode = result.getInt("statusCode"); Collection<HFCACredential> certs = new ArrayList<>(); if (statusCode < 400) { JsonArray certificates = result.getJsonArray("certs"); if (certificates != null && !certificates.isEmpty()) { for (int i = 0; i < certificates.size(); i++) { String certPEM = certificates.getJsonObject(i).getString("PEM"); certs.add(new HFCAX509Certificate(certPEM)); } } logger.debug(format("certificate url: %s, registrar: %s done.", HFCA_CERTIFICATE, registrar)); } return new HFCACertificateResponse(statusCode, certs); } catch (HTTPException e) { String msg = format("[Code: %d] - Error while getting certificates from url '%s': %s", e.getStatusCode(), HFCA_CERTIFICATE, e.getMessage()); HFCACertificateException certificateException = new HFCACertificateException(msg, e); logger.error(msg); throw certificateException; } catch (Exception e) { String msg = format("Error while getting certificates from url '%s': %s", HFCA_CERTIFICATE, e.getMessage()); HFCACertificateException certificateException = new HFCACertificateException(msg, e); logger.error(msg); throw certificateException; } }
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 ww w . j a v a 2 s. c om*/ 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:wsserver.EKF1TimerSessionBean.java
private void callT1() { Runnable r = new Runnable() { public void run() { try { try { cbLogsFacade.insertLog("INFO", "Start load bx_bsect", "Start load bx_bsect url=" + systemURL); } catch (Exception lge) { }//from w ww .j a va2 s . c om String url = systemURL + "bitrix/ekflibraries/corpbus/get_json_data.php?ENTITY=BSECT"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); con.setConnectTimeout(180000); //add request header con.setRequestProperty("User-Agent", "Mozilla-Firefox"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); try { cbLogsFacade.insertLog("INFO", "Complete load bx_bsect urldata", "Complete load bx_bsect urldata"); } catch (Exception lge) { } JsonReader jsonReader = Json.createReader(new StringReader(response.toString())); bxBsectFacade.clearBxBsect(); int crcnt = 0; int badCnt = 0; JsonArray jarray = jsonReader.readArray(); //JsonParser parser = Json.createParser(in); boolean hasCrashes = false; for (int i = 0; i < jarray.size(); i++) { JsonObject jobject = jarray.getJsonObject(i); BxBsect bsectObj = new BxBsect(); bsectObj.setId(-1); try { bsectObj.setBxId(Tools.parseInt(jobject.getString("ID", "-1"), -1)); } catch (Exception e) { bsectObj.setBxId(-1); } try { String f1cId = jobject.getString("1C_ID", ""); if (f1cId.length() == 36) bsectObj.setF1cId(f1cId); else bsectObj.setF1cId("NULL"); } catch (Exception e) { bsectObj.setF1cId("NULL"); } try { bsectObj.setParentBxId(Tools.parseInt(jobject.getString("PARENT_ID", "-1"), -1)); } catch (Exception e) { bsectObj.setParentBxId(-1); } try { bsectObj.setName(jobject.getString("NAME", "NULL")); } catch (Exception e) { bsectObj.setName("NULL"); } int try_cnt = 0; boolean notSucc = true; String err = ""; while (try_cnt < 10 && notSucc) { try { bxBsectFacade.create(bsectObj); crcnt++; notSucc = false; } catch (Exception e) { notSucc = true; badCnt++; try_cnt++; err += "[[" + Tools.parseInt(jobject.getString("ID", "-1"), -1) + "]]<<==!!||||||!!==>>Error of bxBsectFacade.create " + e; } } try { if (try_cnt > 0) cbLogsFacade.insertLog("ERROR", "Error of bxBSectFacade", err); } catch (Exception lge) { } hasCrashes = hasCrashes | notSucc; } try { cbLogsFacade.insertLog("INFO", "Complete load bx_bsect", "Complete load bx_bsect " + ", all=" + jarray.size() + ",succ=" + crcnt + ",errcnt=" + badCnt); } catch (Exception lge) { } BxBsect bsectObjCompl = new BxBsect(); bsectObjCompl.setId(-1); bsectObjCompl.setBxId(jarray.size()); if (hasCrashes) bsectObjCompl.setF1cId("00000000-0000-0000-0000-00nocomplete"); else bsectObjCompl.setF1cId("00000000-0000-0000-0000-0000complete"); //bsectObjCompl.setF1cId("00000000-0000-0000-0000-0bxinprocess"); //bsectObjCompl.setF1cId("00000000-0000-0000-0000-01?inprocess"); //bsectObjCompl.setF1cId("00000000-0000-0000-0000-bxancomplete"); //bsectObjCompl.setF1cId("00000000-0000-0000-0000-1cancomplete"); bsectObjCompl.setParentBxId(badCnt); bsectObjCompl.setName("jasz=" + jarray.size() + ",crcnt=" + crcnt); int try_cnt22 = 0; boolean notSucc22 = true; while (try_cnt22 < 10 && notSucc22) { try { //bxBsectFacade.create(bsectObjCompl); notSucc22 = false; } catch (Exception e) { notSucc22 = true; //badCnt22++; try_cnt22++; } } } catch (Exception e) { System.out.println("<<==!!||||||!!==>>Error of get-parse json " + e); try { cbLogsFacade.insertLog("ERROR", "Error of get-parse json bx_bsect", "<<==!!||||||!!==>>Error of get-parse json " + e); } catch (Exception lge) { } } finally { callT2(); } } }; Thread t = new Thread(r); t.start(); }
From source file:wsserver.EKF1TimerSessionBean.java
private void callT2() { Runnable r2 = new Runnable() { public void run() { int badCnt2 = 0; boolean success_sql_operation = false; StringBuilder insert_sql_values_sb = new StringBuilder(); int insert_sql_cnt = 0; String requestRes = ""; try { try { cbLogsFacade.insertLog("INFO", " ? ? ekfgroup.com", "? ? ? (Timer condition worked Bad full exchange circle) ? ?? - ?? ? ??? , ?"); } catch (Exception lge) { }//from w ww. ja v a 2 s . c o m String url2 = systemURL + "bitrix/ekflibraries/corpbus/get_json_data.php?ENTITY=1CSECT"; //try { // cbLogsFacade.insertLog("INFO", "Start load bx_1csect", "Start load bx_1csect, url="+systemURL); //} catch(Exception lge) { //} URL obj2 = new URL(url2); HttpURLConnection con2 = (HttpURLConnection) obj2.openConnection(); // optional default is GET con2.setRequestMethod("GET"); con2.setConnectTimeout(180000); con2.setReadTimeout(180000); //add request header con2.setRequestProperty("User-Agent", "Mozilla-Firefox"); int responseCode2 = con2.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url2); System.out.println("Response Code : " + responseCode2); BufferedReader in2 = new BufferedReader(new InputStreamReader(con2.getInputStream())); String inputLine2; StringBuffer response2 = new StringBuffer(); while ((inputLine2 = in2.readLine()) != null) { response2.append(inputLine2); } in2.close(); //try { // cbLogsFacade.insertLog("INFO", "Exchange in process 8", "Exchange in process 8"); //} catch(Exception lge) { } requestRes = response2.toString(); try { cbLogsFacade.insertLog("INFO", "Complete load bx_1csect urldata", "Complete load bx_1csect urldata, url=" + url2); } catch (Exception lge) { } JsonReader jsonReader2 = Json.createReader(new StringReader(response2.toString())); bx1CSectFacade.clearBx1CSect(); JsonArray jarray2 = jsonReader2.readArray(); int crcnt2 = 0; boolean hasCrashes2 = false; String saveBxSectLog = ""; for (int i = 0; i < jarray2.size(); i++) { JsonObject jobject2 = jarray2.getJsonObject(i); Bx1CSect b1cssectObj = new Bx1CSect(); b1cssectObj.setId(-1); if (insert_sql_cnt > 0) insert_sql_values_sb.append(" ,"); insert_sql_values_sb.append("( "); try { b1cssectObj.setBxId(Tools.parseInt(jobject2.getString("ID", "-1"), -1)); } catch (Exception e) { b1cssectObj.setBxId(-1); } try { String f1cId = jobject2.getString("1C_ID", ""); if (f1cId.length() == 36) b1cssectObj.setF1cId(f1cId); else b1cssectObj.setF1cId("NULL"); } catch (Exception e) { b1cssectObj.setF1cId("NULL"); } try { b1cssectObj.setParentBxId(Tools.parseInt(jobject2.getString("PARENT_ID", "-1"), -1)); } catch (Exception e) { b1cssectObj.setParentBxId(-1); } try { String parent1cId = jobject2.getString("PARENT_1CID", "NULL"); if (parent1cId.length() == 36) b1cssectObj.setParent1cId(parent1cId); else b1cssectObj.setParent1cId("NULL"); } catch (Exception e) { b1cssectObj.setParent1cId("NULL"); } try { b1cssectObj.setName(StringEscapeUtils.unescapeHtml4(StringEscapeUtils .unescapeJson(jobject2.getString("NAME", "NULL")).replace(""", "\""))); } catch (Exception e) { b1cssectObj.setName("NULL"); } try { b1cssectObj.setPicture(StringEscapeUtils.unescapeHtml4(StringEscapeUtils .unescapeJson(jobject2.getString("PICTURE", "")).replace(""", "\""))); } catch (Exception e) { b1cssectObj.setPicture(""); } try { b1cssectObj.setMcatalog(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("MASTER_CATALOG", "")) .replace(""", "\""))); } catch (Exception e) { b1cssectObj.setMcatalog(""); } //inputLine2) try { b1cssectObj.setDescription(StringEscapeUtils.unescapeHtml4(StringEscapeUtils .unescapeJson(jobject2.getString("DESCRIPTION", "")).replace(""", "\""))); } catch (Exception e) { b1cssectObj.setDescription(""); } try { b1cssectObj.setFullDescription(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("FULL_DESCRIPTION", "")) .replace(""", "\""))); } catch (Exception e) { b1cssectObj.setFullDescription(""); } try { b1cssectObj.setTypeCompleting(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("TYPE_COMPLETING", "")) .replace(""", "\""))); } catch (Exception e) { b1cssectObj.setTypeCompleting(""); } try { b1cssectObj.setCharGabarits(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("CHAR_GABARITS", "")) .replace(""", "\""))); } catch (Exception e) { b1cssectObj.setCharGabarits(""); } try { b1cssectObj.setDocumentation(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("DOCUMENTATION", "")) .replace(""", "\""))); } catch (Exception e) { b1cssectObj.setDocumentation(""); } try { b1cssectObj.setShortDesription(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("SHORT_DESCRIPTION", "")) .replace(""", "\""))); } catch (Exception e) { b1cssectObj.setShortDesription(""); } try { b1cssectObj.setVideoDescription(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("VIDEO_DESCRIPTION", "")) .replace(""", "\""))); } catch (Exception e) { b1cssectObj.setVideoDescription(""); } insert_sql_values_sb.append(b1cssectObj.getBxId()); insert_sql_values_sb.append(",'"); insert_sql_values_sb.append(b1cssectObj.getName().replace("'", "''")); insert_sql_values_sb.append("',"); insert_sql_values_sb.append(b1cssectObj.getParentBxId()); insert_sql_values_sb.append(",'"); insert_sql_values_sb.append(b1cssectObj.getF1cId().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getParent1cId().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getFullDescription().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getTypeCompleting().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getCharGabarits().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getShortDesription().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getDocumentation().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getDescription().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getPicture().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cssectObj.getVideoDescription().replace("'", "''")); insert_sql_values_sb.append("','");// insert_sql_values_sb.append(b1cssectObj.getMcatalog().replace("'", "''")); insert_sql_values_sb.append("',"); insert_sql_values_sb .append((Tools.parseInt(jobject2.getString("COLLAPSEVC", "0"), 0) == 1 ? 1 : 0)); insert_sql_values_sb.append(",'"); try { insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(StringEscapeUtils .unescapeJson(jobject2.getString("ADVANTS", "")).replace(""", "\""))); } catch (Exception e) { } insert_sql_values_sb.append("','"); try { insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4(StringEscapeUtils .unescapeJson(jobject2.getString("FILTER_PROPS", "")).replace(""", "\""))); } catch (Exception e) { } insert_sql_values_sb.append("','"); try { insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("DESCRIPTS_JSON", "")) .replace(""", "\"").replace("'", "''"))); } catch (Exception e) { } insert_sql_values_sb.append("','"); try { insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("GABARITS_JSON", "")) .replace(""", "\"").replace("'", "''"))); } catch (Exception e) { } insert_sql_values_sb.append("','"); try { insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("DOCS_JSON", "")) .replace(""", "\"").replace("'", "''"))); } catch (Exception e) { } insert_sql_values_sb.append("',"); try { insert_sql_values_sb.append(Tools.parseInt( StringEscapeUtils.unescapeJson(jobject2.getString("SORT_ORDER", "0")), 0)); } catch (Exception e) { } insert_sql_values_sb.append(",'"); try { insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("SEO_ALIAS_URL", "")) .replace(""", "\"").replace("'", "''"))); } catch (Exception e) { } insert_sql_values_sb.append("','"); try { insert_sql_values_sb.append(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject2.getString("SEO_TITLE", "")) .replace(""", "\"").replace("'", "''"))); } catch (Exception e) { } insert_sql_values_sb.append("','"); try { insert_sql_values_sb.append(StringEscapeUtils .unescapeHtml4(StringEscapeUtils.unescapeJson(jobject2.getString("SEO_H1", "")) .replace(""", "\"").replace("'", "''"))); } catch (Exception e) { } insert_sql_values_sb.append("')"); int try_cnt2 = 0; boolean notSucc2 = true; String err = ""; while (try_cnt2 < 10 && notSucc2) { try { //bx1CSectFacade.create(b1cssectObj); //bx1CSectFacade. crcnt2++; notSucc2 = false; } catch (Exception e) { notSucc2 = true; badCnt2++; try_cnt2++; err += "[[" + Tools.parseInt(jobject2.getString("ID", "-1"), -1) + "]]<<==!!||||||!!==>>Error of bx1CsectFacade.create " + e; } } try { if (try_cnt2 > 0) cbLogsFacade.insertLog("ERROR", "Error of bx1CSectFacade", err); } catch (Exception lge) { } hasCrashes2 = hasCrashes2 | notSucc2; insert_sql_cnt++; if (insert_sql_cnt >= 500 || i >= (jarray2.size() - 1)) { try { success_sql_operation = bx1CSectFacade .insertBx1SectMultiply(insert_sql_values_sb.toString(), insert_sql_cnt); } catch (Exception lgesq) { success_sql_operation = false; try { cbLogsFacade.insertLog("INFO", "!!!Unsuccess sending complex sql instruct to bx_1csect", "Err " + lgesq); } catch (Exception lge) { } } if (!success_sql_operation) { try { cbLogsFacade.insertLog("INFO", "!!!Unsuccess complex sql instruct to bx_1csect", "Count record to bx_1csect " + insert_sql_cnt); } catch (Exception lge) { } break; } else { //saveBxSectLog+=("Count record to bx_1cpsect "+insert_sql_cnt+". "); //try { // cbLogsFacade.insertLog("INFO", "Success complex sql instruct to bx_1csect", "Count record to bx_1cpsect "+insert_sql_cnt); //} catch(Exception lge) { //} } insert_sql_cnt = 0; insert_sql_values_sb.setLength(0); } } try { cbLogsFacade.insertLog("INFO", "Complete load bx_1csect", saveBxSectLog + " Complete load bx_1csect " + ", all=" + jarray2.size() + ",succ=" + crcnt2 + ",errcnt=" + badCnt2); } catch (Exception lge) { } if (badCnt2 <= 0 && success_sql_operation) callT3(); else exchangeInProcess = false; } catch (Exception e) { exchangeInProcess = false; try { cbLogsFacade.insertLog("ERROR", "Error of get-parse json bx_1csect", "<<==!!||||||!!==>>Error of get-parse json " + e + ",server reply[" + requestRes.substring(0, 200) + "]"); } catch (Exception lge) { } } finally { } } }; Thread t2 = new Thread(r2); t2.start(); }
From source file:wsserver.EKF1TimerSessionBean.java
private void callT3() { Runnable r3 = new Runnable() { public void run() { int badCnt3 = 0; int crcnt = 0; int allcnt = -1; boolean success_sql_operation = false; StringBuilder insert_sql_values_sb = new StringBuilder(); int insert_sql_cnt = 0; try { String url = systemURL + "bitrix/ekflibraries/corpbus/get_json_data.php?ENTITY=1CPROD"; //try { // cbLogsFacade.insertLog("INFO", "Start load bx_1cprod", "Start load bx_1cprod, url="+systemURL); //} catch(Exception lge) { //} URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); con.setConnectTimeout(180000); con.setReadTimeout(180000); //add request header con.setRequestProperty("User-Agent", "Mozilla-Firefox"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); }// w w w .ja va 2 s. c om in.close(); try { cbLogsFacade.insertLog("INFO", "Complete load bx_1cprod urldata", "Complete load bx_1cprod urldata, url=" + systemURL); } catch (Exception lge) { } JsonReader jsonReader = Json.createReader(new StringReader(response.toString())); //int icnt = 0;//bx1CProdFacade.insertBx1ProdMultiply(); //try { // cbLogsFacade.insertLog("INFO", "Complete persist test bx_1cprod urldata ", "Complete persist test bx_1cprod urldata "+icnt); //} catch(Exception lge) { //} bx1CProdFacade.clearBx1CProd(); JsonArray jarray = jsonReader.readArray(); boolean hasCrashes = false; String saveBxDataLog = ""; for (int i = 0; i < jarray.size(); i++) { JsonObject jobject = jarray.getJsonObject(i); Bx1CProd b1cprodObj = new Bx1CProd(); b1cprodObj.setId(-1); if (insert_sql_cnt > 0) insert_sql_values_sb.append(" ,"); insert_sql_values_sb.append("( "); try { b1cprodObj.setBxId(Tools.parseInt(jobject.getString("ID", "-1"), -1)); } catch (Exception e) { b1cprodObj.setBxId(-1); } try { String f1cId = jobject.getString("1C_ID", "NULL"); if (f1cId.length() == 36) b1cprodObj.setF1cId(f1cId); else b1cprodObj.setF1cId("NULL"); } catch (Exception e) { b1cprodObj.setF1cId("NULL"); } try { b1cprodObj.setParentBxId(Tools.parseInt(jobject.getString("PARENT_ID", "-1"), -1)); } catch (Exception e) { b1cprodObj.setParentBxId(-1); } try { String parent1cId = jobject.getString("PARENT_1CID", "NULL"); if (parent1cId.length() == 36) b1cprodObj.setParent1cId(parent1cId); else b1cprodObj.setParent1cId("NULL"); } catch (Exception e) { b1cprodObj.setParent1cId("NULL"); } try { b1cprodObj.setName(StringEscapeUtils.unescapeHtml4(StringEscapeUtils .unescapeJson(jobject.getString("NAME", "NULL")).replace(""", "\""))); } catch (Exception e) { b1cprodObj.setName("NULL"); } try { b1cprodObj.setArtikul(StringEscapeUtils.unescapeHtml4( StringEscapeUtils.unescapeJson(jobject.getString("ARTICUL", "NULL")))); } catch (Exception e) { b1cprodObj.setArtikul("NULL"); } insert_sql_values_sb.append(b1cprodObj.getBxId()); insert_sql_values_sb.append(",'"); insert_sql_values_sb.append(b1cprodObj.getName().replace("'", "''")); insert_sql_values_sb.append("',"); insert_sql_values_sb.append(b1cprodObj.getParentBxId()); insert_sql_values_sb.append(",'"); insert_sql_values_sb.append(b1cprodObj.getF1cId().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cprodObj.getParent1cId().replace("'", "''")); insert_sql_values_sb.append("','"); insert_sql_values_sb.append(b1cprodObj.getArtikul().replace("'", "''")); insert_sql_values_sb.append("',"); try { b1cprodObj.setPrice(new BigDecimal(jobject.getString("PRICE", "0"))); insert_sql_values_sb.append(jobject.getString("PRICE", "0").replace(",", ".")); } catch (Exception e) { b1cprodObj.setPrice(new BigDecimal(0)); insert_sql_values_sb.append("0"); } insert_sql_values_sb.append(","); try { b1cprodObj.setAmount(new BigDecimal(jobject.getString("QUANTITY", "0"))); insert_sql_values_sb.append(jobject.getString("QUANTITY", "0").replace(",", ".")); } catch (Exception e) { b1cprodObj.setAmount(new BigDecimal(0)); insert_sql_values_sb.append("0"); } insert_sql_values_sb.append(","); try { b1cprodObj.setBprice(new BigDecimal(jobject.getString("BPRICE", "0"))); insert_sql_values_sb.append(jobject.getString("BPRICE", "0").replace(",", ".")); } catch (Exception e) { b1cprodObj.setBprice(new BigDecimal(0)); insert_sql_values_sb.append("0"); } insert_sql_values_sb.append(","); try { //b1cprodObj.setBprice(new BigDecimal(jobject.getString("SORT_ORDER", "0"))); insert_sql_values_sb.append(jobject.getString("SORT_ORDER", "0").replace(",", ".")); } catch (Exception e) { //b1cprodObj.setBprice(new BigDecimal(0)); insert_sql_values_sb.append("0"); } insert_sql_values_sb.append(",'"); try { insert_sql_values_sb.append(StringEscapeUtils .unescapeHtml4( StringEscapeUtils.unescapeJson(jobject.getString("MAIN_PICT", ""))) .replace("'", "''")); } catch (Exception e) { } insert_sql_values_sb.append("',"); try { //b1cprodObj.setBprice(new BigDecimal(jobject.getString("SORT_ORDER", "0"))); insert_sql_values_sb.append("" + jobject.getInt("PROP_CNT", 0)); } catch (Exception e) { //b1cprodObj.setBprice(new BigDecimal(0)); insert_sql_values_sb.append("0"); } insert_sql_values_sb.append(")"); int try_cnt = 0; boolean notSucc = true; String err = ""; while (try_cnt < 10 && notSucc) { try { //bx1CSectFacade. //bx1CProdFacade.create(b1cprodObj); crcnt++; notSucc = false; } catch (Exception e) { notSucc = true; badCnt3++; try_cnt++; err += "[[" + Tools.parseInt(jobject.getString("ID", "-1"), -1) + "]]<<==!!||||||!!==>>Error of bx1CProdFacade.create " + e; } } try { if (try_cnt > 0) { cbLogsFacade.insertLog("ERROR", "Error of bx1CProdFacade", err); } } catch (Exception lge) { } hasCrashes = hasCrashes | notSucc; insert_sql_cnt++; if (insert_sql_cnt >= 500 || i >= (jarray.size() - 1)) { try { success_sql_operation = bx1CProdFacade .insertBx1ProdMultiply(insert_sql_values_sb.toString(), insert_sql_cnt); } catch (Exception lgesq) { success_sql_operation = false; try { cbLogsFacade.insertLog("INFO", "!!!Unsuccess sending complex sql instruct to bx_1cprod", "Err " + lgesq); } catch (Exception lge) { } } if (!success_sql_operation) { try { cbLogsFacade.insertLog("INFO", "!!!Unsuccess complex sql instruct to bx_1cprod", "Count record to bx_1cprods " + insert_sql_cnt); } catch (Exception lge) { } break; } else { saveBxDataLog += ("Succ " + insert_sql_cnt);//complex sql instruct to bx_1cprod. "+ // "Count record to bx_1cprods "+insert_sql_cnt); //try { // cbLogsFacade.insertLog("INFO", "Success complex sql instruct to bx_1cprod", "Count record to bx_1cprods "+insert_sql_cnt); //} catch(Exception lge) { //} } insert_sql_cnt = 0; insert_sql_values_sb.setLength(0); } } try { allcnt = jarray.size(); cbLogsFacade.insertLog("INFO", "Complete load bx_1cprod", saveBxDataLog + " Complete load bx_1cprods " + ", all=" + allcnt + ",succ=" + crcnt + ",errcnt=" + badCnt3); } catch (Exception lge) { } if (badCnt3 <= 20 && (allcnt == crcnt) && success_sql_operation) { //sendCompareData(); //sendCompareSectDataDel(); //sendCompareSectDataUpd(); boolean repeat_load = true; int repeat_counter = 0; while (repeat_load && repeat_counter < 10) { repeat_counter++; String selectExchngDataLog = ""; try { if (tablesOperatingStateFacade.getEkfGrExchDataCorrupt() && false) { Thread.sleep(30000); try { cbLogsFacade.insertLog("INFO", "getEkfGrExchDataCorrupt", "Wait on 30 sec, attempt " + repeat_counter + " of 10..."); } catch (Exception lgex) { } } else { repeat_load = false; int ekfProdCount = cbLogsFacade.ekfProdCount(); int ekfProdSectCount = cbLogsFacade.ekfProdSectCount(); if (ekfProdCount >= 1000 && ekfProdCount <= 100000 && ekfProdSectCount >= 200 && ekfProdSectCount <= 10000) { if (tablesOperatingStateFacade.setEkfGrExchDataCorrupt()) { //try { // cbLogsFacade.insertLog("INFO", "Start of request cbNewPrFrom1cWpropsFacade", "Start of request cbNewPrFrom1cWpropsFacade"); //} catch(Exception lge) { } selectExchngDataLog += "Start of request cbNewPrFrom1cWpropsFacade "; npwps_ = cbNewPrFrom1cWpropsFacade.findAll(); //try { // cbLogsFacade.insertLog("INFO", "Start of request cbEkfgroupDel1csectFromBxFacade", "Complete prev, Start of request cbEkfgroupDel1csectFromBxFacade"); //} catch(Exception lge) { } selectExchngDataLog += "Complete prev, Start of request cbEkfgroupDel1csectFromBxFacade "; dswps_ = cbEkfgroupDel1csectFromBxFacade.findAll(); //try { // cbLogsFacade.insertLog("INFO", "Start of request cbEkfgroupUpd1csectToBxFacade", "Complete prev, Start of request cbEkfgroupUpd1csectToBxFacade"); //} catch(Exception lge) { } selectExchngDataLog += "Complete prev, Start of request cbEkfgroupUpd1csectToBxFacade "; uswps_ = cbEkfgroupUpd1csectToBxFacade.findAll(); //try { // cbLogsFacade.insertLog("INFO", "Start of request cbEkfgroupAdd1csectToBxFacade", "Complete prev, Start of request cbEkfgroupAdd1csectToBxFacade"); //} catch(Exception lge) { } selectExchngDataLog += "Complete prev, Start of request cbEkfgroupAdd1csectToBxFacade "; nswps_ = cbEkfgroupAdd1csectToBxFacade.findAll(); //try { // cbLogsFacade.insertLog("INFO", "Start of request cbEkfroupDelFromBxViewFacade", "Complete prev, Start of request cbEkfroupDelFromBxViewFacade"); //} catch(Exception lge) { } selectExchngDataLog += "Complete prev, Start of request cbEkfroupDelFromBxViewFacade "; dpwps_ = cbEkfroupDelFromBxViewFacade.findAll(); //try { // cbLogsFacade.insertLog("INFO", "Start of request CbEkfgroupToUpdatedBx1cFacade", "Complete prev, Start of request CbEkfgroupToUpdatedBx1cFacade"); //} catch(Exception lge) { } selectExchngDataLog += "Complete prev, Start of request CbEkfgroupToUpdatedBx1cFacade "; upwps_ = cbEkfgroupToUpdatedBx1cFacade.findAll(); try { cbLogsFacade.insertLog("INFO", "End of request CbEkfgroupToUpdatedBx1cFacade", selectExchngDataLog + " End of request CbEkfgroupToUpdatedBx1cFacade"); } catch (Exception lge) { } if (npwps_.size() == 0 && upwps_.size() == 0 && dpwps_.size() == 0) { if (cbSettingsFacade.updExchanheLastDt()) { //try { // cbLogsFacade.insertLog("INFO", "Success update exchange last datetime", // "Success update exchange last datetime"); //} catch(Exception lge) { //} } else { try { cbLogsFacade.insertLog("ERROR", "Unsuccess update exchange last datetime", "Unsuccess update exchange last datetime"); } catch (Exception lge) { } } } if (tablesOperatingStateFacade.setEkfGrExchDataUnCorrupt()) { sendCompareSectDataAdd(); } else { exchangeInProcess = false; try { cbLogsFacade.insertLog("ERROR", "Unsuccess setEkfGrExchDataCorrupt 0", "Unsuccess setEkfGrExchDataCorrupt 0"); } catch (Exception lgex) { } } } else { exchangeInProcess = false; try { cbLogsFacade.insertLog("ERROR", "Unsuccess setEkfGrExchDataCorrupt 1", "Unsuccess setEkfGrExchDataCorrupt 1"); } catch (Exception lgex) { } } } else { exchangeInProcess = false; try { cbLogsFacade.insertLog("ERROR", "Invalid data sizes, exchange stopped", "Data sizes mismatch conditions 200<=ekfProdSectCount<=10000, " + "1000<=ekfProdCount<=100000"); } catch (Exception lgex) { } } } } catch (Exception lge) { exchangeInProcess = false; repeat_load = false; try { cbLogsFacade.insertLog("ERROR", "Error of getEkfGrExchDataCorrupt or setEkfGrExchDataCorrupt or MDS data load", "Error of getEkfGrExchDataCorrupt, detail: " + selectExchngDataLog); } catch (Exception lgex) { } } } if (repeat_load) { hasLong1CWait = true; exchangeInProcess = false; } } else exchangeInProcess = false; } catch (Exception e) { exchangeInProcess = false; System.out.println("<<==!!||||||!!==>>Error of get-parse bx_1cprod json " + e); try { cbLogsFacade.insertLog("ERROR", "Error of get-parse json bx_1cprod", "<<==!!||||||!!==>>Error of get-parse json " + e); } catch (Exception lge) { } } finally { try { //tablesOperatingStateFacade.setEkfGrExchDataUnDelta(); if (tablesOperatingStateFacade.setEkfGrExchDataUnCorrupt()) { } else { try { cbLogsFacade.insertLog("ERROR", "Unsuccess setEkfGrExchDataCorrupt 0", "Unsuccess setEkfGrExchDataCorrupt 0"); } catch (Exception lgex) { } } } catch (Exception lgex) { } } } }; Thread t3 = new Thread(r3); t3.start(); }
From source file:fr.ortolang.diffusion.core.CoreServiceBean.java
@TransactionAttribute(TransactionAttributeType.SUPPORTS) private void buildHandleList(String wsalias, String tag, String key, Set<OrtolangObjectPid> pids, PathBuilder path, String apiUrlBase, String marketUrlBase) throws CoreServiceException, KeyNotFoundException, OrtolangException, InvalidPathException { try {//from w w w . jav a 2s . c o m OrtolangObject object = findObject(key); LOGGER.log(Level.FINE, "Generating pid for key: " + key); String target = ((path.isRoot()) ? marketUrlBase : apiUrlBase) + "/" + wsalias + "/" + tag + ((path.isRoot()) ? "" : path.build()); String dynHandle = OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.HANDLE_PREFIX) + "/" + wsalias + ((path.isRoot()) ? "" : path.build()); String staticHandle = OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.HANDLE_PREFIX) + "/" + wsalias + "/" + tag + ((path.isRoot()) ? "" : path.build()); OrtolangObjectPid dpid = new OrtolangObjectPid(OrtolangObjectPid.Type.HANDLE, dynHandle, key, target, false); boolean adddpid = true; for (OrtolangObjectPid pid : pids) { if (pid.getName().equals(dpid.getName()) && pid.isUserbased()) { adddpid = false; break; } } if (adddpid) { pids.add(dpid); } OrtolangObjectPid spid = new OrtolangObjectPid(OrtolangObjectPid.Type.HANDLE, staticHandle, key, target, false); boolean addspid = true; for (OrtolangObjectPid pid : pids) { if (pid.getName().equals(spid.getName()) && pid.isUserbased()) { addspid = false; break; } } if (addspid) { pids.add(spid); } if (object instanceof MetadataSource) { MetadataElement mde = ((MetadataSource) object).findMetadataByName(MetadataFormat.PID); if (mde != null) { LOGGER.log(Level.FINE, "PID metadata found, load json and generate corresponding pids"); MetadataObject md = readMetadataObject(mde.getKey()); try { JsonReader reader = Json.createReader(binarystore.get(md.getStream())); JsonObject json = reader.readObject(); if (json.containsKey("pids")) { JsonArray jpids = json.getJsonArray("pids"); for (int i = 0; i < jpids.size(); i++) { JsonObject jpid = jpids.getJsonObject(i); LOGGER.log(Level.FINE, "Generating metadata based pid for key: " + key); String ctarget = ((path.isRoot()) ? marketUrlBase : apiUrlBase) + "/" + wsalias + "/" + tag + ((path.isRoot()) ? "" : path.build()); OrtolangObjectPid upid = new OrtolangObjectPid(OrtolangObjectPid.Type.HANDLE, jpid.getString("value"), key, ctarget, true); Iterator<OrtolangObjectPid> iter = pids.iterator(); while (iter.hasNext()) { OrtolangObjectPid pid = iter.next(); if (pid.getName().equals(upid.getName())) { iter.remove(); } } pids.add(upid); } } reader.close(); } catch (BinaryStoreServiceException | DataNotFoundException e) { LOGGER.log(Level.SEVERE, "unable to read pid metadata", e); } } } if (object instanceof Collection) { for (CollectionElement element : ((Collection) object).getElements()) { buildHandleList(wsalias, tag, element.getKey(), pids, path.clone().path(element.getName()), apiUrlBase, marketUrlBase); } } } catch (AccessDeniedException e) { LOGGER.log(Level.INFO, "Unable to generate a PID for an object that has been set private."); } }
From source file:org.bsc.confluence.rest.AbstractRESTConfluenceService.java
protected Stream<JsonObject> mapToStream(Response res) { final ResponseBody body = res.body(); try (Reader r = body.charStream()) { final JsonReader rdr = Json.createReader(r); final JsonObject root = rdr.readObject(); final Stream.Builder<JsonObject> stream = Stream.builder(); // Check for Array if (root.containsKey("results")) { final JsonArray results = root.getJsonArray("results"); if (results != null) { for (int ii = 0; ii < results.size(); ++ii) stream.add(results.getJsonObject(ii)); }/* w w w.ja v a 2s.com*/ } else { stream.add(root); } return stream.build(); } catch (IOException | JsonParsingException e) { throw new Error(e); } }
From source file:org.grogshop.services.endpoints.impl.ShopItemsServiceImpl.java
@Override public Response newItem(@NotNull @FormParam("user_id") Long userId, @NotNull @FormParam("club_id") Long clubId, @NotNull @FormParam("type") String type, @NotNull @NotEmpty @FormParam("name") String name, @NotNull @NotEmpty @FormParam("description") String description, @NotNull @NotEmpty @FormParam("tags") String tags, @FormParam("minPrice") String minPrice, @FormParam("maxPrice") String maxPrice) throws ServiceException { JsonReader reader = Json.createReader(new ByteArrayInputStream(tags.getBytes())); JsonArray array = reader.readArray(); reader.close();//from w w w . j av a2 s .co m List<String> interestsList = new ArrayList<String>(); if (array != null) { for (int i = 0; i < array.size(); i++) { log.info("Tag[" + i + "]: " + array.getJsonObject(i).getString("text")); interestsList.add(array.getJsonObject(i).getString("text")); } } Long newItem = itemsService.newItem(userId, clubId, type, name, description, interestsList, (minPrice == null) ? new BigDecimal(0) : new BigDecimal(minPrice), (maxPrice == null) ? new BigDecimal(0) : new BigDecimal(maxPrice)); return Response.ok(newItem).build(); }
From source file:org.grogshop.services.endpoints.impl.ShopUserProfileServiceImpl.java
public Response setInterests(@NotNull @PathParam("user_id") Long user_id, @FormParam("interests") String interests) throws ServiceException { log.info("Storing from the database: (" + user_id + ") " + interests); if (interests != null) { JsonReader reader = Json.createReader(new ByteArrayInputStream(interests.getBytes())); JsonArray array = reader.readArray(); reader.close();//from w ww. j ava 2s. co m List<Interest> interestsList = new ArrayList<Interest>(array.size()); if (array != null) { for (int i = 0; i < array.size(); i++) { log.info("Interest[" + i + "]: " + array.getJsonObject(i).getString("name")); interestsList.add(interestService.get(array.getJsonObject(i).getString("name"))); } } profileService.setInterests(user_id, interestsList); } return Response.ok().build(); }