List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
From source file:account.SalesRegisterDetailCardWise.java
private void jbtnViewActionPerformedRoutine() { try {/*w ww . j a v a 2s .c o m*/ AccountAPI accountAPI = lb.getRetrofit().create(AccountAPI.class); if (ac_cd == null) { ac_cd = ""; } if (!jCheckBox1.isSelected()) { ac_cd = ""; } JsonObject call = accountAPI.CardWiseSalesDetailStatement(ac_cd).execute().body(); lb.addGlassPane(this); if (call != null) { JsonObject result = call; if (result.get("result").getAsInt() == 1) { JsonArray array = call.getAsJsonArray("data"); dtm.setRowCount(0); dtm.setRowCount(0); double basic_amt = 0.00, tax_amt = 0.00, net_amt = 0.00, buy_back_amt = 0.00, ins_amt = 0.00, bajaj = 0.00; double cash = 0.00, bank = 0.00, card = 0.00; String tax_name = ""; String buy_back_model = ""; String old_ref_no = ""; for (int i = 0; i < array.size(); i++) { if (!old_ref_no.equalsIgnoreCase("") && !old_ref_no .equalsIgnoreCase(array.get(i).getAsJsonObject().get("ref_no").getAsString())) { Vector row = new Vector(); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(basic_amt); row.add(lb.Convert2DecFmtForRs(tax_amt)); row.add(net_amt); row.add(tax_name); row.add(cash); row.add(bank); row.add(card); row.add(bajaj); row.add(buy_back_amt); row.add(buy_back_model); row.add(ins_amt); row.add(lb.Convert2DecFmtForRs( basic_amt + tax_amt - cash - bank - card - buy_back_amt + ins_amt - bajaj)); basic_amt = 0.00; dtm.addRow(row); } Vector row = new Vector(); row.add(array.get(i).getAsJsonObject().get("ref_no").getAsString()); if (basic_amt == 0.00) { row.add(array.get(i).getAsJsonObject().get("v_type").getAsString()); row.add(array.get(i).getAsJsonObject().get("inv_no").getAsInt()); row.add(lb.ConvertDateFormetForDisplay( array.get(i).getAsJsonObject().get("v_date").getAsString())); row.add((array.get(i).getAsJsonObject().get("fname") == null) ? "" : array.get(i).getAsJsonObject().get("fname").getAsString()); } else { row.add(""); row.add(""); row.add(""); row.add(""); } row.add(array.get(i).getAsJsonObject().get("SR_ALIAS").getAsString()); row.add(array.get(i).getAsJsonObject().get("SR_NAME").getAsString()); row.add(array.get(i).getAsJsonObject().get("IMEI_NO").getAsString()); row.add(array.get(i).getAsJsonObject().get("SERAIL_NO").getAsString()); row.add(array.get(i).getAsJsonObject().get("QTY").getAsInt()); row.add(array.get(i).getAsJsonObject().get("RATE").getAsDouble()); row.add(array.get(i).getAsJsonObject().get("AMT").getAsDouble()); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); dtm.addRow(row); basic_amt = array.get(i).getAsJsonObject().get("det_tot").getAsDouble(); tax_amt = array.get(i).getAsJsonObject().get("tax_amt").getAsDouble() + array.get(i).getAsJsonObject().get("add_tax_amt").getAsDouble(); net_amt = array.get(i).getAsJsonObject().get("net_amt").getAsDouble(); cash = array.get(i).getAsJsonObject().get("CASH_AMT").getAsDouble(); bank = array.get(i).getAsJsonObject().get("BANK_AMT").getAsDouble(); card = array.get(i).getAsJsonObject().get("CARD_AMT").getAsDouble(); tax_name = array.get(i).getAsJsonObject().get("tax_name").getAsString(); buy_back_model = array.get(i).getAsJsonObject().get("buy_back_model").getAsString(); buy_back_amt = array.get(i).getAsJsonObject().get("buy_back_amt").getAsDouble(); ins_amt = array.get(i).getAsJsonObject().get("ins_amt").getAsDouble(); bajaj = array.get(i).getAsJsonObject().get("bajaj_amt").getAsDouble(); old_ref_no = array.get(i).getAsJsonObject().get("ref_no").getAsString(); } Vector row = new Vector(); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(basic_amt); row.add(lb.Convert2DecFmtForRs(tax_amt)); row.add(net_amt); row.add(tax_name); row.add(cash); row.add(bank); row.add(card); row.add(bajaj); row.add(buy_back_amt); row.add(buy_back_model); row.add(ins_amt); row.add(lb.Convert2DecFmtForRs( basic_amt + tax_amt + ins_amt - cash - bank - card - buy_back_amt - bajaj)); basic_amt = 0.00; dtm.addRow(row); double tot_basic = 0.00, tot_tax = 0.00, tot_cash = 0.00, tot_bank = 0.00, tot_card = 0.00, tot_buyBack = 0.00, tot_deb = 0.00, tot_ins_amt = 0.00, tot_bajaj_amt = 0.00, tot_net_amt = 0.00; for (int i = 0; i < jTable1.getRowCount(); i++) { tot_basic += lb.isNumber2(jTable1.getValueAt(i, 12).toString()); tot_tax += lb.isNumber2(jTable1.getValueAt(i, 13).toString()); tot_net_amt += lb.isNumber2(jTable1.getValueAt(i, 14).toString()); tot_cash += lb.isNumber2(jTable1.getValueAt(i, 16).toString()); tot_card += lb.isNumber2(jTable1.getValueAt(i, 18).toString()); tot_bajaj_amt += lb.isNumber2(jTable1.getValueAt(i, 19).toString()); tot_buyBack += lb.isNumber2(jTable1.getValueAt(i, 20).toString()); tot_ins_amt += lb.isNumber2(jTable1.getValueAt(i, 22).toString()); tot_deb += lb.isNumber2(jTable1.getValueAt(i, 23).toString()); } row = new Vector(); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(""); row.add(lb.Convert2DecFmtForRs(tot_basic)); row.add(lb.Convert2DecFmtForRs(tot_tax)); row.add(lb.Convert2DecFmtForRs(tot_net_amt)); row.add(""); row.add(lb.Convert2DecFmtForRs(tot_cash)); row.add(lb.Convert2DecFmtForRs(tot_bank)); row.add(lb.Convert2DecFmtForRs(tot_card)); row.add(lb.Convert2DecFmtForRs(tot_bajaj_amt)); row.add(lb.Convert2DecFmtForRs(tot_buyBack)); row.add(""); row.add(lb.Convert2DecFmtForRs(tot_ins_amt)); row.add(lb.Convert2DecFmtForRs(tot_deb)); dtm.addRow(row); lb.setColumnSizeForTable(jTable1, jPanel1.getWidth()); lb.removeGlassPane(SalesRegisterDetailCardWise.this); } else { lb.removeGlassPane(SalesRegisterDetailCardWise.this); lb.showMessageDailog(call.get("Cause").getAsString()); } } } catch (IOException ex) { Logger.getLogger(SalesRegisterDetailCardWise.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:account.SalesRegisterDetailCardWise.java
private void jtxtCardNoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtxtCardNoKeyPressed // TODO add your handling code here: if (lb.isEnter(evt) && !lb.isBlank(jtxtCardNo)) { try {/*from w w w.j a v a2 s .c o m*/ lb.addGlassPane(this); JsonObject call = lb.getRetrofit().create(SalesAPI.class) .GetDataFromServer(jtxtCardNo.getText(), "22").execute().body(); lb.removeGlassPane(SalesRegisterDetailCardWise.this); if (call != null) { JsonArray array = call.getAsJsonArray("data"); if (array.size() > 0) { ac_cd = (array.get(0).getAsJsonObject().get("AC_CD").getAsString()); jtxtAcAlias.setText(ac_cd); jtxtAcName.setText(array.get(0).getAsJsonObject().get("FNAME").getAsString()); jtxtCardNo.setText(array.get(0).getAsJsonObject().get("CARD_NO").getAsString()); } } } catch (IOException ex) { Logger.getLogger(SalesRegisterDetailCardWise.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:ai.nitro.bot4j.integration.slack.receive.impl.SlackReceiveActionMessageFactoryImpl.java
License:Open Source License
protected void handleActions(final JsonArray jsonArray, final ReceiveMessage result) { if (jsonArray.size() > 0) { final JsonObject jsonObject = jsonArray.get(0).getAsJsonObject(); handleAction(jsonObject, result); }// w ww. ja v a 2s.co m }
From source file:allout58.mods.techtree.tree.TechNodeGSON.java
License:Open Source License
@Override public TechNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject obj = json.getAsJsonObject(); final int id = obj.get("id").getAsInt(); final String name = obj.get("name").getAsString(); final int science = obj.get("scienceRequired").getAsInt(); final String description = obj.get("description").getAsString(); final ItemStack[] items = context.deserialize(obj.get("lockedItems"), ItemStack[].class); final TechNode node = new TechNode(id); // ItemStack[] items = new ItemStack[] { new ItemStack(Items.apple), new ItemStack(Items.arrow), new ItemStack(Items.bow) }; node.setup(name, science, description, items); final JsonArray jsonParentArray = obj.getAsJsonArray("parents"); for (int i = 0; i < jsonParentArray.size(); i++) { node.addParentNode(jsonParentArray.get(i).getAsInt()); }/*www . j a va2 s .c o m*/ return node; }
From source file:ambari.interaction.NodeController.java
public static ArrayList<ComponentInformation> getListOfNodes() throws Exception { String url = "http://127.0.0.1:8080/api/v1/clusters/mycluster/services/HDFS/components/DATANODE?fields=host_components/HostRoles/desired_admin_state,host_components/HostRoles/state"; String responseJson = HttpURLConnectionExample.sendGet(url); System.out.print(responseJson); JsonParser jsonParser = new JsonParser(); JsonElement jsonTree = jsonParser.parse(responseJson); ArrayList<ComponentInformation> listOfCompoents = new ArrayList<ComponentInformation>(); if (jsonTree.isJsonObject()) { JsonObject jsonObject = jsonTree.getAsJsonObject(); JsonElement hostComponents = jsonObject.get("host_components"); if (hostComponents.isJsonArray()) { JsonArray hostComponentsJsonArray = hostComponents.getAsJsonArray(); System.out.println("\nStart"); System.out.println(hostComponentsJsonArray); for (int i = 0; i < hostComponentsJsonArray.size(); i++) { JsonElement hostComponentsElem = hostComponentsJsonArray.get(i); if (hostComponentsElem.isJsonObject()) { JsonObject jsonObjectElem = hostComponentsElem.getAsJsonObject(); JsonElement hostRolesElem = jsonObjectElem.get("HostRoles"); if (hostRolesElem.isJsonObject()) { JsonObject hostRolesObjs = hostRolesElem.getAsJsonObject(); JsonElement componentNameElem = hostRolesObjs.get("component_name"); JsonElement hostNameElem = hostRolesObjs.get("host_name"); JsonElement stateElem = hostRolesObjs.get("state"); listOfCompoents.add(new ComponentInformation(componentNameElem.toString(), hostNameElem.toString(), stateElem.toString())); }/* w w w.j a va 2s .com*/ } } } } return listOfCompoents; }
From source file:angularBeans.remote.InvocationHandler.java
License:LGPL
private void genericInvoke(Object service, String methodName, JsonObject params, Map<String, Object> returns, long reqID, String UID, HttpServletRequest request) throws SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { Object mainReturn = null;//from w ww. j a v a 2s . co m Method m = null; JsonElement argsElem = params.get("args"); if (reqID > 0) { returns.put("reqId", reqID); } if (argsElem != null) { JsonArray args = params.get("args").getAsJsonArray(); for (Method mt : service.getClass().getMethods()) { if (mt.getName().equals(methodName)) { m = mt; Type[] parameters = mt.getParameterTypes(); if (parameters.length == args.size()) { List<Object> argsValues = new ArrayList<>(); for (int i = 0; i < parameters.length; i++) { Class typeClass; String typeString = ((parameters[i]).toString()); if (typeString.startsWith("interface")) { typeString = typeString.substring(10); typeClass = Class.forName(typeString); } else { if (typeString.startsWith("class")) { typeString = typeString.substring(6); typeClass = Class.forName(typeString); } else { typeClass = builtInMap.get(typeString); } } JsonElement element = args.get(i); if (element.isJsonPrimitive()) { String val = element.getAsString(); argsValues.add(CommonUtils.convertFromString(val, typeClass)); } else if (element.isJsonArray()) { JsonArray arr = element.getAsJsonArray(); argsValues.add(util.deserialise(arrayTypesMap.get(typeString), arr)); } else { argsValues.add(util.deserialise(typeClass, element)); } } if (!CommonUtils.isGetter(mt)) { update(service, params); } try { mainReturn = mt.invoke(service, argsValues.toArray()); } catch (Exception e) { handleException(mt, e); e.printStackTrace(); } } } } } else { for (Method mt : service.getClass().getMethods()) { if (mt.getName().equals(methodName)) { Type[] parameters = mt.getParameterTypes(); // handling methods that took HttpServletRequest as parameter if (parameters.length == 1) { // if(mt.getParameters()[0].getType()==HttpServletRequest.class) // { // System.out.println("hehe..."); // mt.invoke(service, request); // // } } else { if (!CommonUtils.isGetter(m)) { update(service, params); } mainReturn = mt.invoke(service); } } } } ModelQueryImpl qImpl = (ModelQueryImpl) modelQueryFactory.get(service.getClass()); Map<String, Object> scMap = new HashMap<>(qImpl.getData()); returns.putAll(scMap); qImpl.getData().clear(); if (!modelQueryFactory.getRootScope().getRootScopeMap().isEmpty()) { returns.put("rootScope", new HashMap<>(modelQueryFactory.getRootScope().getRootScopeMap())); modelQueryFactory.getRootScope().getRootScopeMap().clear(); } String[] updates = null; if (m.isAnnotationPresent(NGReturn.class)) { if (mainReturn == null) mainReturn = ""; NGReturn ngReturn = m.getAnnotation(NGReturn.class); updates = ngReturn.updates(); if (ngReturn.model().length() > 0) { returns.put(ngReturn.model(), mainReturn); Map<String, String> binding = new HashMap<>(); binding.put("boundTo", ngReturn.model()); mainReturn = binding; } } if (m.isAnnotationPresent(NGPostConstruct.class)) { NGPostConstruct ngPostConstruct = m.getAnnotation(NGPostConstruct.class); updates = ngPostConstruct.updates(); } if (updates != null) { if ((updates.length == 1) && (updates[0].equals("*"))) { List<String> upd = new ArrayList<>(); for (Method met : service.getClass().getDeclaredMethods()) { if (CommonUtils.isGetter(met)) { String fieldName = (met.getName()).substring(3); String firstCar = fieldName.substring(0, 1); upd.add((firstCar.toLowerCase() + fieldName.substring(1))); } } updates = new String[upd.size()]; for (int i = 0; i < upd.size(); i++) { updates[i] = upd.get(i); } } } if (updates != null) { for (String up : updates) { String getterName = GETTER_PREFIX + up.substring(0, 1).toUpperCase() + up.substring(1); Method getter; try { getter = service.getClass().getMethod(getterName); } catch (NoSuchMethodException e) { getter = service.getClass() .getMethod((getterName.replace(GETTER_PREFIX, BOOLEAN_GETTER_PREFIX))); } Object result = getter.invoke(service); returns.put(up, result); } } returns.put("mainReturn", mainReturn); if (!logger.getLogPool().isEmpty()) { returns.put("log", logger.getLogPool().toArray()); logger.getLogPool().clear(); } }
From source file:app.abhijit.iter.data.source.StudentDataSource.java
License:Open Source License
private void processStudentSubjects(String response) { mFetchStudentSubjectsAsyncTask = null; JsonObject student = mJsonParser.parse(mLocalStore.getString(mSelectedRegistrationNumber, null)) .getAsJsonObject();// w ww . j a v a 2 s. c o m JsonObject subjects = new JsonObject(); try { JsonArray studentSubjects = mJsonParser.parse(response).getAsJsonArray(); for (int i = 0; i < studentSubjects.size(); i++) { if (!studentSubjects.get(i).getAsJsonObject().has("subjectcode") || !studentSubjects.get(i).getAsJsonObject().has("subject") || !studentSubjects.get(i).getAsJsonObject().has("totalpresentclass") || !studentSubjects.get(i).getAsJsonObject().has("totalclasses")) { continue; } String code = studentSubjects.get(i).getAsJsonObject().get("subjectcode").getAsString(); String name = studentSubjects.get(i).getAsJsonObject().get("subject").getAsString(); int presentClasses = studentSubjects.get(i).getAsJsonObject().get("totalpresentclass").getAsInt(); int totalClasses = studentSubjects.get(i).getAsJsonObject().get("totalclasses").getAsInt(); if (totalClasses <= 0 || presentClasses < 0 || presentClasses > totalClasses) continue; long lastUpdated = new Date().getTime(); int oldPresentClasses = presentClasses; int oldTotalClasses = totalClasses; if (student.has(STUDENT_SUBJECTS_KEY) && student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().has(code)) { oldPresentClasses = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code) .getAsJsonObject().get(STUDENT_SUBJECT_PRESENT_CLASSES_KEY).getAsInt(); oldTotalClasses = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code) .getAsJsonObject().get(STUDENT_SUBJECT_TOTAL_CLASSES_KEY).getAsInt(); if (presentClasses == oldPresentClasses && totalClasses == oldTotalClasses) { lastUpdated = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code) .getAsJsonObject().get(STUDENT_SUBJECT_LAST_UPDATED_KEY).getAsLong(); } } JsonObject subject = new JsonObject(); subject.addProperty(STUDENT_SUBJECT_CODE_KEY, code); subject.addProperty(STUDENT_SUBJECT_NAME_KEY, name); subject.addProperty(STUDENT_SUBJECT_PRESENT_CLASSES_KEY, presentClasses); subject.addProperty(STUDENT_SUBJECT_TOTAL_CLASSES_KEY, totalClasses); subject.addProperty(STUDENT_SUBJECT_OLD_PRESENT_CLASSES_KEY, oldPresentClasses); subject.addProperty(STUDENT_SUBJECT_OLD_TOTAL_CLASSES_KEY, oldTotalClasses); subject.addProperty(STUDENT_SUBJECT_LAST_UPDATED_KEY, lastUpdated); subjects.add(code, subject); } } catch (Exception e) { if (student.has(STUDENT_SUBJECTS_KEY)) { subjects = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject(); } else { subjects = new JsonObject(); } } student.add(STUDENT_SUBJECTS_KEY, subjects); student.addProperty(STUDENT_TIMESTAMP_KEY, new Date().getTime()); mLocalStore.edit().putString(mSelectedRegistrationNumber, student.toString()).apply(); fetch(); }
From source file:application.Genius.java
License:Open Source License
public static ArrayList<Lyrics> search(String query) { ArrayList<Lyrics> results = new ArrayList<>(); query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");/*from www. j a v a2s . c o m*/ JsonObject response = null; try { URL queryURL = new URL( String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8"))); Connection connection = Jsoup.connect(queryURL.toExternalForm()) .header("Authorization", "Bearer " + Keys.GENIUS).ignoreContentType(true); Document document = connection.userAgent(USER_AGENT).get(); response = new JsonParser().parse(document.text()).getAsJsonObject(); } catch (IOException e) { e.printStackTrace(); } if (response == null || response.getAsJsonObject("meta").get("status").getAsInt() != 200) return results; JsonArray hits = response.getAsJsonObject("response").getAsJsonArray("hits"); int processed = 0; while (processed < hits.size()) { JsonObject song = hits.get(processed).getAsJsonObject().getAsJsonObject("result"); String artist = song.getAsJsonObject("primary_artist").get("name").getAsString(); String title = song.get("title").getAsString(); String url = "http://genius.com/songs/" + song.get("id").getAsString(); Lyrics l = new Lyrics(); l.mArtist = artist; l.mTitle = title; l.mSourceUrl = url; l.mSource = "Genius"; results.add(l); processed++; } return results; }
From source file:asteroidtracker.AsteroidTrackerSpeechlet.java
License:Open Source License
/** * Parse JSON-formatted list of events/births/deaths from Wikipedia, extract list of events and * split the events into a String array of individual events. Run Regex matchers to make the * list pretty by adding a comma after the year to add a pause, and by removing a unicode char. * //w ww. j av a2s .c o m * @param text * the JSON formatted list of events/births/deaths for a certain date * @return String array of events for that date, 1 event per element of the array */ private ArrayList<String> parseJson(String text, String date) { ArrayList<String> events = new ArrayList<String>(); if (text.isEmpty()) { return events; } JsonParser parser = new JsonParser(); JsonObject object = parser.parse(text).getAsJsonObject(); JsonArray asteroidArray = object.get("near_earth_objects").getAsJsonObject().get(date).getAsJsonArray(); for (int i = 0; i < object.get("element_count").getAsInt(); i++) { JsonObject thisAsteroid = asteroidArray.get(i).getAsJsonObject(); String asteroidName = thisAsteroid.get("name").getAsString(); float absoluteMagnitude = thisAsteroid.get("absolute_magnitude_h").getAsFloat(); JsonObject estimatedDiameterKilometers = thisAsteroid.get("estimated_diameter").getAsJsonObject() .get("kilometers").getAsJsonObject(); float minimumDiameter = estimatedDiameterKilometers.get("estimated_diameter_min").getAsFloat(); float maximumDiameter = estimatedDiameterKilometers.get("estimated_diameter_max").getAsFloat(); boolean isDangerousObject = thisAsteroid.get("is_potentially_hazardous_asteroid") .getAsString() == "false"; JsonObject closeApproachData = thisAsteroid.get("close_approach_data").getAsJsonArray().get(0) .getAsJsonObject(); float speed = closeApproachData.get("relative_velocity").getAsJsonObject().get("kilometers_per_hour") .getAsFloat(); Number missDistance = closeApproachData.get("miss_distance").getAsJsonObject().get("kilometers") .getAsNumber(); String orbitingBody = closeApproachData.get("orbiting_body").getAsString(); DecimalFormat df = new DecimalFormat("#.##"); String asteroidIdText = "Asteroid " + i + ", name is " + asteroidName + ","; String magnitudeText = "The absolute magnitude is " + absoluteMagnitude; String sizeText = ", the estimated diameter is from " + df.format(minimumDiameter) + " to " + df.format(maximumDiameter) + " kilometers,"; String dangerousnessText; if (isDangerousObject) { dangerousnessText = "This object is dangerous!"; } else { dangerousnessText = "This object is not dangerous,"; } String speedText = "It is traveling at " + df.format(speed) + " kilometers per hour"; String distanceText = " at a distance of " + missDistance + " kilometers"; String orbitingBodyText = " and is orbiting " + orbitingBody; String eventText = asteroidIdText + magnitudeText + sizeText + dangerousnessText + speedText + distanceText + orbitingBodyText; events.add(eventText); } return events; }
From source file:at.ac.dbisinformatik.snowprofile.web.svgcreator.SVGCreator.java
License:Open Source License
/** * creates a SVG-Graph for given jsonDocument which includes ExtJS-SVG-Objects. The created SVG-Document will be converted in the given export type. * /*from w w w. ja v a 2 s . co m*/ * @param jsonDocument * @param exportType * @param profileID * @return * @throws TransformerException * @throws URISyntaxException * @throws TranscoderException * @throws IOException */ public static ByteArrayOutputStream svgDocument(JsonArray jsonDocument, String exportType, String profileID) throws TransformerException, URISyntaxException, TranscoderException, IOException { ByteArrayOutputStream ret = null; DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI; Document doc = impl.createDocument(svgNS, "svg", null); // Get the root element (the 'svg' element). Element svgRoot = doc.getDocumentElement(); // Set the width and height attributes on the root 'svg' element. svgRoot.setAttributeNS(null, "width", "1500"); svgRoot.setAttributeNS(null, "height", "1500"); JsonArray items = jsonDocument; for (int i = 0; i < items.size(); ++i) { String type = items.get(i).getAsJsonObject().get("type").getAsString(); Element element = null; org.w3c.dom.Text test = null; String path = ""; String width = ""; String height = ""; String x = ""; String y = ""; String fill = ""; String text = ""; String font = ""; String fontFamily = ""; String fontSize = ""; String degrees = ""; String stroke = ""; String opacity = ""; String src = ""; switch (type) { case "rect": width = items.get(i).getAsJsonObject().get("width").getAsString(); height = items.get(i).getAsJsonObject().get("height").getAsString(); x = items.get(i).getAsJsonObject().get("x").getAsString(); y = items.get(i).getAsJsonObject().get("y").getAsString(); fill = items.get(i).getAsJsonObject().get("fill").getAsString(); stroke = items.get(i).getAsJsonObject().get("stroke").getAsString(); opacity = items.get(i).getAsJsonObject().get("opacity").getAsString(); // Create the rectangle. element = doc.createElementNS(svgNS, "rect"); element.setAttributeNS(null, "width", width); element.setAttributeNS(null, "height", height); element.setAttributeNS(null, "x", x); element.setAttributeNS(null, "y", y); element.setAttributeNS(null, "fill", fill); element.setAttributeNS(null, "stroke", stroke); element.setAttributeNS(null, "opacity", opacity); break; case "path": path = items.get(i).getAsJsonObject().get("path").getAsString(); fill = items.get(i).getAsJsonObject().get("fill").getAsString(); stroke = items.get(i).getAsJsonObject().get("stroke").getAsString(); // Create the path. element = doc.createElementNS(svgNS, "path"); element.setAttributeNS(null, "d", path); element.setAttributeNS(null, "fill", fill); element.setAttributeNS(null, "stroke", stroke); break; case "image": x = items.get(i).getAsJsonObject().get("x").getAsString(); y = items.get(i).getAsJsonObject().get("y").getAsString(); width = items.get(i).getAsJsonObject().get("width").getAsString(); height = items.get(i).getAsJsonObject().get("height").getAsString(); src = System.class.getResource("/at/ac/dbisinformatik/snowprofile/web/resources/" + items.get(i).getAsJsonObject().get("src").getAsString()).toString(); // Create the path. element = doc.createElementNS(svgNS, "image"); element.setAttributeNS(null, "x", x); element.setAttributeNS(null, "y", y); element.setAttributeNS(null, "width", width); element.setAttributeNS(null, "height", height); element.setAttributeNS(null, "xlink:href", src); break; case "text": text = items.get(i).getAsJsonObject().get("text").getAsString(); fill = items.get(i).getAsJsonObject().get("fill").getAsString(); font = items.get(i).getAsJsonObject().get("font").getAsString(); x = items.get(i).getAsJsonObject().get("x").getAsString(); y = items.get(i).getAsJsonObject().get("y").getAsString(); // Transformation if (items.get(i).getAsJsonObject().get("rotate") != null) { JsonObject temp = items.get(i).getAsJsonObject().get("rotate").getAsJsonObject(); degrees = temp.get("degrees").getAsString(); } fontSize = font.split(" ")[0]; fontFamily = font.split(" ")[1]; // Create the text. test = doc.createTextNode(text); element = doc.createElementNS(svgNS, "text"); element.setAttributeNS(null, "text", text); element.setAttributeNS(null, "fill", fill); element.setAttributeNS(null, "font-family", fontFamily); element.setAttributeNS(null, "font-size", fontSize); element.setAttributeNS(null, "x", x); element.setAttributeNS(null, "y", y); if (!degrees.equals("")) { // element.setAttributeNS(null, "transform", // "rotate(270 "+500+","+80+")"); } element.appendChild(test); break; default: break; } // Attach the rectangle to the root 'svg' element. svgRoot.appendChild(element); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(outputStream); transformer.transform(source, result); InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); switch (exportType) { case "png": ret = createPNG(inputStream); break; case "jpg": ret = createJPG(inputStream); break; case "pdf": ret = createPDF(inputStream); break; default: break; } return ret; }