List of usage examples for com.google.gson JsonObject isJsonObject
public boolean isJsonObject()
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
License:Apache License
public String extractDateFormatParameter(final JsonObject element) { String value = null;// w w w . java2 s .c o m if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); final String dateFormatParameter = "dateFormat"; if (object.has(dateFormatParameter) && object.get(dateFormatParameter).isJsonPrimitive()) { final JsonPrimitive primitive = object.get(dateFormatParameter).getAsJsonPrimitive(); value = primitive.getAsString(); } } return value; }
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
License:Apache License
public String extractTimeFormatParameter(final JsonObject element) { String value = null;/* w w w .ja v a2 s .co m*/ if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); final String timeFormatParameter = "timeFormat"; if (object.has(timeFormatParameter) && object.get(timeFormatParameter).isJsonPrimitive()) { final JsonPrimitive primitive = object.get(timeFormatParameter).getAsJsonPrimitive(); value = primitive.getAsString(); } } return value; }
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
License:Apache License
public String extractMonthDayFormatParameter(final JsonObject element) { String value = null;/*from w ww. j ava2 s . c om*/ if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); final String monthDayFormatParameter = "monthDayFormat"; if (object.has(monthDayFormatParameter) && object.get(monthDayFormatParameter).isJsonPrimitive()) { final JsonPrimitive primitive = object.get(monthDayFormatParameter).getAsJsonPrimitive(); value = primitive.getAsString(); } } return value; }
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
License:Apache License
public Locale extractLocaleParameter(final JsonObject element) { Locale clientApplicationLocale = null; if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); String locale = null;// w ww. j av a 2 s . c om final String localeParameter = "locale"; if (object.has(localeParameter) && object.get(localeParameter).isJsonPrimitive()) { final JsonPrimitive primitive = object.get(localeParameter).getAsJsonPrimitive(); locale = primitive.getAsString(); clientApplicationLocale = localeFromString(locale); } } return clientApplicationLocale; }
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
License:Apache License
public MonthDay extractMonthDayNamed(final String parameterName, final JsonObject element, final String dateFormat, final Locale clientApplicationLocale) { MonthDay value = null;/* www. java 2 s .com*/ if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); final String valueAsString = primitive.getAsString(); if (StringUtils.isNotBlank(valueAsString)) { try { final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat) .withLocale(clientApplicationLocale); value = MonthDay.parse(valueAsString.toLowerCase(clientApplicationLocale), formatter); } catch (final IllegalArgumentException e) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.invalid.month.day", "The parameter " + parameterName + " is invalid based on the monthDayFormat: '" + dateFormat + "' and locale: '" + clientApplicationLocale + "' provided:", parameterName, valueAsString, dateFormat); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } } } } return value; }
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
License:Apache License
public LocalDateTime extractLocalTimeNamed(final String parameterName, final JsonObject element, final String timeFormat, final Locale clientApplicationLocale, final Set<String> parametersPassedInCommand) { LocalDateTime value = null;// w w w. j a va 2 s. com String timeValueAsString = null; if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { parametersPassedInCommand.add(parameterName); try { DateTimeFormatter timeFormtter = DateTimeFormat.forPattern(timeFormat); final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); timeValueAsString = primitive.getAsString(); if (StringUtils.isNotBlank(timeValueAsString)) { value = LocalDateTime.parse(timeValueAsString, timeFormtter); } } catch (IllegalArgumentException e) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final String defaultMessage = new StringBuilder( "The parameter '" + timeValueAsString + "' is not in correct format.").toString(); final ApiParameterError error = ApiParameterError .parameterError("validation.msg.invalid.TimeFormat", defaultMessage, parameterName); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } } } return value; }
From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java
License:Apache License
public LocalDate extractLocalDateNamed(final String parameterName, final JsonObject element, final String dateFormat, final Locale clientApplicationLocale, final Set<String> parametersPassedInCommand) { LocalDate value = null;/*from ww w . j a v a 2 s. c o m*/ if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { parametersPassedInCommand.add(parameterName); final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); final String valueAsString = primitive.getAsString(); if (StringUtils.isNotBlank(valueAsString)) { value = convertFrom(valueAsString, parameterName, dateFormat, clientApplicationLocale); } } } return value; }
From source file:dmadmin.DMSession.java
License:Open Source License
@SuppressWarnings("deprecation") public void SyncAnsible(ServletContext context) { internalLogin(context);/*from w w w . jav a 2s. co m*/ int domainid = -1; try { PreparedStatement st; st = getDBConnection().prepareStatement("select id from dm.dm_domain where name = 'Infrastructure'"); ResultSet rs2 = st.executeQuery(); while (rs2.next()) { domainid = rs2.getInt(1); } rs2.close(); st.close(); } catch (SQLException e) { } if (domainid == -1) { try { PreparedStatement st; st = getDBConnection().prepareStatement( "insert into dm.dm_domain (id,name,domainid,ownerid,status) (select max(id)+1,'Infrastructure', 1, 1,'N' from dm.dm_domain)"); st.execute(); st.close(); st = getDBConnection() .prepareStatement("select id from dm.dm_domain where name = 'Infrastructure'"); ResultSet rs2 = st.executeQuery(); while (rs2.next()) { domainid = rs2.getInt(1); } rs2.close(); st.close(); } catch (SQLException e) { } } if (domainid == -1) domainid = 1; int download_filter = 120; // Number of downloads before we consider it worthy of import String om_filter = System.getenv("OM_ANSIBLE_DOWNLOAD_FILTER"); if (om_filter != null) { try { download_filter = Integer.parseInt(om_filter); } catch (NumberFormatException e) { System.out.println("Invalid value " + om_filter + " for OM_ANSIBLE_DOWNLOAD_FILTER value"); } } int numpages = 0; try { String json = readUrl("https://galaxy.ansible.com/api/v1/roles/?format=json"); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(json); JsonObject ansible = je.getAsJsonObject(); numpages = ansible.get("num_pages").getAsInt(); } catch (Exception localException1) { } File tempdir = new File("temp/roles"); tempdir.mkdirs(); System.out.println("ROLES=" + tempdir.getAbsoluteFile()); // Base64 b64 = new Base64(); for (int page = 1; page < numpages; page++) { try { String json = readUrl("https://galaxy.ansible.com/api/v1/roles/?page=" + page + "&format=json"); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(json); JsonObject ansible = je.getAsJsonObject(); JsonArray results = (JsonArray) ansible.get("results"); for (int i = 0; i < results.size(); i++) { JsonObject role = results.get(i).getAsJsonObject(); String name = role.get("name").getAsString(); String namespace = role.get("namespace").getAsString(); String fullName = namespace + "." + name; String actionName = name.replaceAll(" ", "_"); actionName = actionName.replaceAll("-", "_"); String user = role.get("github_user").getAsString(); String repo = role.get("github_repo").getAsString(); String summ = role.get("description").getAsString(); int dlcnt = role.get("download_count").getAsInt(); if (dlcnt >= download_filter) { summ = StringEscapeUtils.escapeXml(summ); JsonObject summfields = role.getAsJsonObject("summary_fields"); JsonArray tags = summfields.get("tags").getAsJsonArray(); String category = "General"; try { JsonObject tag = tags.get(0).getAsJsonObject(); category = tag.get("name").getAsString(); category = capitalize(category); } catch (IndexOutOfBoundsException localIndexOutOfBoundsException) { } String default_vars_str = readUrl("https://raw.githubusercontent.com/" + user + "/" + repo + "/master/defaults/main.yml"); JsonObject default_vars_json = convertToJson(default_vars_str); PrintWriter writer = new PrintWriter("temp/roles/" + user + "_" + repo + ".xml"); writer.println("<action name=\"ansible_" + actionName + "_" + user.replaceAll("-", "_") + "\" summary=\"" + summ + "\" isGraphical=\"N\" category=\"" + category + "\">"); writer.println("<kind copy=\"N\">3</kind>"); writer.println("<scripts>"); writer.println("<scriptbody filename=\"omansible.sh\">"); writer.println("</scriptbody>"); writer.println("</scripts>"); writer.println("<cmdline>"); writer.println("<script name=\"${DMHOME}/scripts/omansible.sh\" />"); writer.println("<flag name=\"Target\" switch=\"--ansible_target\" pad=\"false\" />"); writer.println("<flag name=\"TargetArg\" switch=\"${server.hostname}\" pad=\"false\" />"); writer.println("<flag name=\"GalaxyRole\" switch=\"--galaxy_role\" pad=\"false\" />"); writer.println("<flag name=\"GalaxyRoleArg\" switch=\"" + fullName + "\" pad=\"false\" />"); writer.println( "<flag name=\"AnsibleSshUser\" switch=\"--ansible_ssh_user\" pad=\"false\" />"); writer.println( "<flag name=\"AnsibleSshUserArg\" switch=\"'${AnsibleSshUser}'\" pad=\"false\" />"); writer.println( "<flag name=\"AnsibleSshPassword\" switch=\"--ansible_ssh_pass\" pad=\"false\" />"); writer.println( "<flag name=\"AnsibleSshPasswordArg\" switch=\"'${AnsibleSshPassword}'\" pad=\"false\" />"); writer.println( "<flag name=\"AnsibleSudoPassword\" switch=\"--ansible_sudo_pass\" pad=\"false\" />"); writer.println( "<flag name=\"AnsibleSudoPasswordArg\" switch=\"'${AnsibleSudoPassword}'\" pad=\"false\" />"); writer.println( "<argument name=\"AnsibleVariableFile\" type=\"Entry\" inpos=\"0\" switchmode=\"S\" switch=\"--ansible_variable_file\" negswitch=\"\" pad=\"false\" required=\"false\" />"); if (default_vars_json.isJsonObject()) { Set<Entry<String, JsonElement>> ens = default_vars_json.entrySet(); if (ens != null) { for (Iterator<Entry<String, JsonElement>> iterator = ens.iterator(); iterator .hasNext();) { Entry<String, JsonElement> en = iterator.next(); if (!((JsonElement) en.getValue()).isJsonPrimitive()) continue; writer.println("<argument name=\"" + capitalize((String) en.getKey()) + "\" type=\"Entry\" inpos=\"0\" switchmode=\"S\" switch=\"--" + (String) en.getKey() + "\" negswitch=\"\" pad=\"false\" required=\"false\" />"); } } } writer.println("</cmdline>"); writer.println("<fragment name=\"ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_role\" summary=\"" + summ + "\">"); writer.println( "<parameter name=\"AnsibleVariableFile\" type=\"Entry\" required=\"N\" default_value=\"${ansible_variable_file}\"/>"); HashMap<String, String> defaultvars = new HashMap<String, String>(); if (default_vars_json.isJsonObject()) { Set<Entry<String, JsonElement>> ens = default_vars_json.entrySet(); if (ens != null) { for (Iterator<Entry<String, JsonElement>> iterator = ens.iterator(); iterator .hasNext();) { Entry<String, JsonElement> en = iterator.next(); if (!((JsonElement) en.getValue()).isJsonPrimitive()) continue; defaultvars.put((String) en.getKey(), ((JsonElement) en.getValue()).toString().replaceAll("^\"|\"$", "")); writer.println("<parameter name=\"" + capitalize((String) en.getKey()) + "\" type=\"Entry\" required=\"N\" default_value=\"${" + (String) en.getKey() + "}\" />"); } } } writer.println("</fragment>"); writer.println(" </action>"); writer.close(); int existingdomain = -1; try { PreparedStatement st; st = getDBConnection() .prepareStatement("select domainid from dm.dm_action where name = ?"); st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_")); ResultSet rs2 = st.executeQuery(); while (rs2.next()) { existingdomain = rs2.getInt(1); } rs2.close(); st.close(); } catch (SQLException e) { } if (existingdomain == -1) existingdomain = domainid; System.out.println("Import Domain=" + existingdomain); ImportFunction(existingdomain, new File("temp/roles/" + user + "_" + repo + ".xml").getAbsolutePath()); long t = timeNow(); PreparedStatement st = getDBConnection() .prepareStatement("select id from dm.dm_action where name = ?"); st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_action"); int actionid = 0; ResultSet rs2 = st.executeQuery(); while (rs2.next()) { actionid = rs2.getInt(1); } rs2.close(); st.close(); existingdomain = -1; try { st = getDBConnection() .prepareStatement("select domainid from dm.dm_action where name = ?"); st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_action"); rs2 = st.executeQuery(); while (rs2.next()) { existingdomain = rs2.getInt(1); } rs2.close(); st.close(); } catch (SQLException e) { } if (existingdomain == -1) existingdomain = domainid; int x; if (actionid == 0) { st = getDBConnection().prepareStatement( "INSERT INTO dm.dm_action (id,name,domainid,function,graphical,ownerid,creatorid,modifierid,created,modified,status,kind) VALUES(?,?,?,'N','Y',?,?,?,?,?,'N',6)"); actionid = getID("action"); st.setInt(1, actionid); st.setString(2, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_action"); st.setInt(3, existingdomain); st.setInt(4, 1); st.setInt(5, 1); st.setInt(6, 1); st.setLong(7, t); st.setLong(8, t); st.execute(); st.close(); st = getDBConnection().prepareStatement("select id from dm.dm_category where name = ?"); st.setString(1, category); int categoryid = 0; rs2 = st.executeQuery(); while (rs2.next()) { categoryid = rs2.getInt(1); } rs2.close(); st.close(); st = getDBConnection().prepareStatement( "INSERT INTO dm.dm_action_categories (id,categoryid) VALUES(?,?)"); st.setInt(1, actionid); st.setInt(2, categoryid); st.execute(); st.close(); int procfuncid = 0; int setcredid = 0; st = getDBConnection() .prepareStatement("select id from dm.dm_fragments where name = ?"); st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_role"); rs2 = st.executeQuery(); while (rs2.next()) { procfuncid = rs2.getInt(1); } rs2.close(); // // Check if ansible_set_credentials is set and add it before each // call to the action if present. // st.setString(1, "ansible_set_credentials"); rs2 = st.executeQuery(); while (rs2.next()) { setcredid = rs2.getInt(1); if (rs2.wasNull()) setcredid = 0; } rs2.close(); st.close(); int windowid = 1; if (setcredid > 0) { // ansible_set_credentials is present MoveNode(actionid, 1, 0, 400, 160, setcredid); AddFlow(actionid, "0", "1", 1); MoveNode(actionid, 2, 0, 400, 360, procfuncid); AddFlow(actionid, "1", "2", 1); windowid = 2; } else { // ansible_set_credentials not present MoveNode(actionid, 1, 0, 400, 160, procfuncid); AddFlow(actionid, "0", "1", 1); windowid = 1; } List<FragmentAttributes> fields = getFragmentAttributes(actionid, windowid, 0); Map<String, String> keyvals = new HashMap<String, String>(); // dm.UpdateFragAttrs(keyvals); // // fields = dm.getFragmentAttributes(actionid, windowid, 0); keyvals = new HashMap<String, String>(); keyvals.put("a", new Integer(actionid).toString()); keyvals.put("w", Integer.toString(windowid)); if (fields != null) { for (x = 0; x < fields.size(); x++) { FragmentAttributes fa = (FragmentAttributes) fields.get(x); String key = "f" + fa.getAttrId(); keyvals.put(key, fa.getDefaultValue()); } } UpdateFragAttrs(keyvals); } st = getDBConnection() .prepareStatement("select count(*) from dm.dm_component where name = ?"); st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_")); int compcnt = 0; rs2 = st.executeQuery(); while (rs2.next()) { compcnt = rs2.getInt(1); } rs2.close(); st.close(); existingdomain = -1; try { st = getDBConnection() .prepareStatement("select domainid from dm.dm_action where name = ?"); st.setString(1, "ansible_" + actionName + "_" + user.replaceAll("-", "_") + "_action"); rs2 = st.executeQuery(); while (rs2.next()) { existingdomain = rs2.getInt(1); } rs2.close(); st.close(); } catch (SQLException e) { } if (existingdomain == -1) existingdomain = domainid; if (compcnt != 0) continue; st = getDBConnection().prepareStatement("select id from dm.dm_category where name = ?"); st.setString(1, category); int categoryid = 0; rs2 = st.executeQuery(); while (rs2.next()) { categoryid = rs2.getInt(1); } rs2.close(); st.close(); st = getDBConnection().prepareStatement( "INSERT INTO dm.dm_component (id,name,domainid,ownerid,creatorid,modifierid,created,modified,status,filteritems,deployalways,actionid,comptypeid) VALUES(?,?,?,?,?,?,?,?,'N','Y','N',?,6)"); int compid = getID("component"); st.setInt(1, compid); st.setString(2, "ansible_" + actionName + "_" + user.replaceAll("-", "_")); st.setInt(3, existingdomain); st.setInt(4, 1); st.setInt(5, 1); st.setInt(6, 1); st.setLong(7, t); st.setLong(8, t); st.setLong(9, actionid); st.execute(); st.close(); st = getDBConnection().prepareStatement( "INSERT INTO dm.dm_component_categories (id,categoryid) VALUES(?,?)"); st.setInt(1, compid); st.setInt(2, categoryid); st.execute(); st.close(); getDBConnection().commit(); AttributeChangeSet changes = new AttributeChangeSet(); for (Iterator<Entry<String, String>> iterator = defaultvars.entrySet().iterator(); iterator .hasNext();) { Entry<String, String> entry = iterator.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); changes.addAdded(new DMAttribute(key, value)); } DMObject dmobj = getObject(ObjectType.COMPONENT, compid); dmobj.updateAttributes(changes); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:fm.audiobox.sync.stream.SocketClient.java
License:Open Source License
@Override public void onMessage(JsonElement json, IOAcknowledge arg1) { try {/* w w w .j ava 2 s.c o m*/ log.info("Action received"); // {action: {name: "stream", id: 123, args:{filename: "", rangemin: 0, rangemax: 1000, etag: ""}} } JsonObject jobj = json.getAsJsonObject(); if (jobj != null && jobj.isJsonObject()) { log.debug("message is: " + jobj.toString()); Action action = new Action(this.configuration); JParser jp = new JParser(action); jp.parse(jobj); // Message received: notify observers Event event = new Event(action, Event.States.ENTITY_REFRESHED); this.setChanged(); this.notifyObservers(event); } else { log.error("Invalid message received: " + json.toString()); } } catch (Exception e) { log.error("Error while reveiving message: " + json.toString(), e); } }
From source file:gov.pnnl.goss.gridappsd.testmanager.CompareResults.java
License:Open Source License
public void loadSimResult_old(String sim_output, SimulationOutput simOutProperties, String expected_output) { JsonParser parser = new JsonParser(); try {/*from w w w .j ava 2 s . c om*/ BufferedReader br = new BufferedReader(new FileReader(sim_output)); JsonElement elm = parser.parse(br); if (elm.isJsonObject()) { JsonObject jsonObject = elm.getAsJsonObject(); JsonObject output = jsonObject.get("output").getAsJsonObject(); JsonObject f2 = output.get("ieee8500").getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet = f2.entrySet(); for (Map.Entry<String, JsonElement> simOutputEle : entrySet) { if (simOutputEle.getValue().isJsonObject()) { JsonObject simOutputObj = simOutputEle.getValue().getAsJsonObject(); for (String prop : propsArray) { if (simOutputObj.has(prop)) System.out.println(prop + " : " + simOutputObj.get(prop)); } } System.out.println("key >>> " + simOutputEle.getKey()); System.out.println("val >>> " + simOutputEle.getValue()); } if (f2.isJsonObject()) { JsonObject f2Obj = f2.getAsJsonObject(); JsonElement f3 = f2Obj.get("f3"); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }