List of usage examples for com.google.gson JsonObject JsonObject
JsonObject
From source file:ch.iterate.openstack.swift.Client.java
License:Open Source License
/** * @param container The name of the container * @param name The name of the object * @param entity The name of the request entity (make sure to set the Content-Type * @param metadata The metadata for the object * @param md5sum The 32 character hex encoded MD5 sum of the data * @param objectSize The total size in bytes of the object to be stored * @param segmentSize Optional size in bytes of the object segments to be stored (forces large object support) default 4G * @param dynamicLargeObject Optional setting to use dynamic large objects, False/null will use static large objects if required * @param segmentContainer Optional name of container to store file segments, defaults to storing chunks in the same container as the file sill appear * @param segmentFolder Optional name of folder for storing file segments, defaults to ".chunks/" * @param leaveSegments Optional setting to leave segments of large objects in place when the manifest is overwrtten/changed * @return The ETAG if the save was successful, null otherwise * @throws GenericException There was a protocol level error talking to CloudFiles *//*w ww . j a v a 2s. com*/ public String storeObject(Region region, String container, String name, HttpEntity entity, Map<String, String> metadata, String md5sum, Long objectSize, Long segmentSize, Boolean dynamicLargeObject, String segmentContainer, String segmentFolder, Boolean leaveSegments) throws IOException, InterruptedException { /* * Default values for large object support. We also use the defaults combined with the inputs * to determine whether to store as a large object. */ /* * The maximum size of a single object (5GiB). */ long singleObjectSizeLimit = (long) (5 * Math.pow(1024, 3)); /* * The default minimum segment size (1MiB). */ long minSegmentSize = 1024L * 1024L; /* * Set the segment size. * * Defaults to 4GiB segments, and will not permit smaller than 1MiB segments. */ long actualSegmentSize = (segmentSize == null) ? (long) (4 * Math.pow(1024, 3)) : Math.max(segmentSize, minSegmentSize); /* * Determines if we will store using large objects - we may do this for 3 reasons: * * - A segmentSize has been specified and the object size is greater than the minimum segment size * - If an objectSize is provided and is larger than the single object size limit of 5GiB * - A segmentSize has been specified, but no objectSize given (we take this as a request for segmentation) * * The last case may fail if the user does not provide at least as much data as the minimum segment * size configured on the server, and will always produce a large object structure (even if only one * small segment is required). */ objectSize = (objectSize == null) ? -1 : objectSize; boolean useLargeObject = ((segmentSize != null) && (objectSize > actualSegmentSize)) || (objectSize > singleObjectSizeLimit) || ((segmentSize != null) && (objectSize == -1)); if (!useLargeObject) { return storeObject(region, container, name, entity, metadata, md5sum); } else { /* * We need to upload a large object as defined by the method * parameters. For now this is done sequentially, but a parallel * version using appropriate random access to the underlying data * may be desirable. * * We make the assumption that the given file size will not be * greater than int.MAX_VALUE * segmentSize * */ leaveSegments = (leaveSegments == null) ? Boolean.FALSE : leaveSegments; dynamicLargeObject = (dynamicLargeObject == null) ? Boolean.FALSE : dynamicLargeObject; segmentFolder = (segmentFolder == null) ? ".file-segments" : segmentFolder; segmentContainer = (segmentContainer == null) ? container : segmentContainer; /* * If we have chosen not to leave existing large object segments in place (default) * then we need to collect information about any existing file segments so that we can * deal with them after we complete the upload of the new manifest. * * We should only delete existing segments after a successful upload of a new manifest file * because this constitutes an object update and the older file should remain available * until the new file can be downloaded. */ Map<String, List<StorageObject>> oldSegmentsToRemove = null; if (!leaveSegments) { oldSegmentsToRemove = listObjectSegments(region, container, name); } /* * Upload the new segments and manifest */ int segmentNumber = 1; long timeStamp = System.currentTimeMillis() / 1000L; String segmentBase = String.format("%s/%d/%d", segmentFolder, timeStamp, objectSize); /* * Create subInputStream from the OutputStream we will pass to the * HttpEntity for writing content. */ final PipedInputStream contentInStream = new PipedInputStream(64 * 1024); final PipedOutputStream contentOutStream = new PipedOutputStream(contentInStream); SubInputStream segmentStream = new SubInputStream(contentInStream, actualSegmentSize, false); /* * Fork the call to entity.writeTo() that allows us to grab any exceptions raised */ final HttpEntity e = entity; final Callable<Boolean> writer = new Callable<Boolean>() { public Boolean call() throws Exception { e.writeTo(contentOutStream); return Boolean.TRUE; } }; ExecutorService writeExecutor = Executors.newSingleThreadExecutor(); final Future<Boolean> future = writeExecutor.submit(writer); /* * Check the future for exceptions after we've finished uploading segments */ Map<String, List<StorageObject>> newSegmentsAdded = new HashMap<String, List<StorageObject>>(); List<StorageObject> newSegments = new LinkedList<StorageObject>(); JsonArray manifestSLO = new JsonArray(); boolean finished = false; /* * Upload each segment of the file by reading sections of the content input stream * until the entire underlying stream is complete */ while (!finished) { String segmentName = String.format("%s/%08d", segmentBase, segmentNumber); String etag; try { etag = storeObject(region, segmentContainer, segmentStream, "application/octet-stream", segmentName, new HashMap<String, String>()); } catch (IOException ex) { // Finished storing the object ex.printStackTrace(); throw ex; } String segmentPath = segmentContainer + "/" + segmentName; long bytesUploaded = segmentStream.getBytesProduced(); /* * Create the appropriate manifest structure if we're making a static large * object. * * ETAG returned by the simple upload * total size of segment uploaded * path of segment */ if (!dynamicLargeObject) { JsonObject segmentJSON = new JsonObject(); segmentJSON.addProperty("path", segmentPath); segmentJSON.addProperty("etag", etag); segmentJSON.addProperty("size_bytes", bytesUploaded); manifestSLO.add(segmentJSON); newSegments.add(new StorageObject(segmentName)); } segmentNumber++; if (!finished) { finished = segmentStream.endSourceReached(); } newSegmentsAdded.put(segmentContainer, newSegments); segmentStream.readMoreBytes(actualSegmentSize); } /* * Attempts to retrieve the return value from the write operation * Any exceptions raised can then be handled appropriately */ try { future.get(); } catch (InterruptedException ex) { /* * The write was interrupted... should we delete the segments? * For now we'll leave orphaned segments, but we should re-visit this later */ } catch (ExecutionException ex) { /* * This should always be an IOException or a RuntimeException * because the call to entity.writeTo() only throws IOException */ Throwable t = ex.getCause(); if (t instanceof IOException) { throw (IOException) t; } else { throw (RuntimeException) t; } } /* * Create an appropriate manifest depending on our DLO/SLO choice */ String manifestEtag; if (dynamicLargeObject) { /* * Empty manifest with header detailing the shared prefix of object segments */ long manifestTimeStamp = System.currentTimeMillis() / 1000L; metadata.put(Constants.X_OBJECT_META + "mtime", String.format("%s", manifestTimeStamp)); manifestEtag = createDLOManifestObject(region, container, entity.getContentType().getValue(), name, segmentBase, metadata); } else { /* * Manifest containing json list specifying details of the object segments. */ manifestEtag = createSLOManifestObject(region, container, entity.getContentType().getValue(), name, manifestSLO.toString(), metadata); } /* * Delete stale segments of overwritten large object if requested. */ if (!leaveSegments) { /* * Before deleting old segments, remove any objects from the delete list * that are also part of a new static large object that were updated during the upload. */ if (!(oldSegmentsToRemove == null)) { for (String c : oldSegmentsToRemove.keySet()) { List<StorageObject> rmv = oldSegmentsToRemove.get(c); if (newSegmentsAdded.containsKey(c)) { rmv.removeAll(newSegmentsAdded.get(c)); } List<String> rmvNames = new LinkedList<String>(); for (StorageObject s : rmv) { rmvNames.add(s.getName()); } deleteObjects(region, c, rmvNames); } } } return manifestEtag; } }
From source file:ch.jamiete.hilda.configuration.Configuration.java
License:Apache License
public void load() { if (!this.file.exists()) { this.json = new JsonObject(); return;//from ww w . ja v a 2 s.c om } Charset charset = null; try { charset = Charset.forName("UTF-8"); } catch (final Exception e) { charset = Charset.defaultCharset(); } try { this.json = new JsonParser().parse(FileUtils.readFileToString(this.file, charset)).getAsJsonObject(); } catch (final IOException e) { Hilda.getLogger().log(Level.WARNING, "Encountered an exception while loading configuration " + this.file.getName(), e); this.json = new JsonObject(); } if (new Gson().toJson(this.json).equals("{}")) { try { this.file.delete(); } catch (final Exception e) { // Ignore } } }
From source file:ch.jamiete.hilda.configuration.Configuration.java
License:Apache License
public void reset() { this.json = new JsonObject(); }
From source file:ch.luklanis.esscan.codesend.ESRSenderHttp.java
License:Apache License
public void sendToListener(final String dataToSend, final long itemId, final int position) { AsyncTask<Object, Integer, JsonObject> asyncTask = new AsyncTask<Object, Integer, JsonObject>() { @Override//from w w w.j ava 2s. c om protected JsonObject doInBackground(Object... objects) { try { JsonObject json = new JsonObject(); json.addProperty("hash", hash); json.addProperty("id", emailAddress); String[] encrypted = Crypto.encrypt(Crypto.getSecretKey(password, emailAddress), dataToSend); json.addProperty("iv", encrypted[0]); json.addProperty("message", encrypted[1]); return json; } catch (Exception e) { e.printStackTrace(); if (mDataSentHandler != null) { Message message = Message.obtain(mDataSentHandler, R.id.es_send_failed); message.obj = itemId; message.arg1 = position; message.sendToTarget(); } return null; } } @Override protected void onPostExecute(JsonObject json) { if (json != null) { Ion.with(context, url).setJsonObjectBody(json).asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String result) { if (mDataSentHandler != null) { Message message = Message.obtain(mDataSentHandler, "OK".equals(result) ? R.id.es_send_succeeded : R.id.es_send_failed); message.obj = itemId; message.arg1 = position; message.sendToTarget(); } } }); } } }; asyncTask.execute(); }
From source file:ch.usz.c3pro.c3_pro_android_framework.dataqueue.EncryptedDataQueue.java
License:Open Source License
/** * Encrypts a FHIR resource and wraps it in a C3-PRO json object that can be sent to a C3-PRO server. *///from www . j a va 2 s .c om public JsonObject encryptResource(IBaseResource resourceToEncrypt) throws CertificateException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidAlgorithmParameterException { // convert resource to json String resourceString = Pyro.getFhirContext().newJsonParser().encodeResourceToString(resourceToEncrypt); // encrypt jsson byte[] encryptedResource = aesUtility.encryptData(resourceString.getBytes()); // encrypt secret key byte[] encryptedKey = rsaUtility.getSecretKeyWrapped(aesUtility.getSecretKey()); // create new resource JsonObject jsonToSend = new JsonObject(); jsonToSend.addProperty("key_id", "some_key_id"); // put encrypted private key jsonToSend.addProperty("symmetric_key", Base64.encodeToString(encryptedKey, Base64.DEFAULT)); // put encrypted resource jsonToSend.addProperty("message", Base64.encodeToString(encryptedResource, Base64.DEFAULT)); // put details jsonToSend.addProperty("version", C3PROFHIRVersion); // return return jsonToSend; }
From source file:cl.emendare.cleancodegenerator.external.adapter.GsonJsonConverter.java
@Override public Configuration toConfigurationObject() { JsonObject jsonObject = new JsonObject(); try {//from www . j a v a2s .com JsonElement jsonElement = parser.parse(new FileReader(filePath)); jsonObject = jsonElement.getAsJsonObject(); } catch (Exception e) { } Configuration config = factory.create(jsonObject.get("language").toString().replace("\"", ""), jsonObject.get("domain").toString().replace("\"", ""), jsonObject.get("persistence").toString().replace("\"", ""), jsonObject.get("usecase").toString().replace("\"", ""), jsonObject.get("module").toString().replace("\"", ""), jsonObject.get("package").toString().replace("\"", ""), jsonObject.get("author").toString().replace("\"", "")); return config; }
From source file:cl.expertchoice.svl.Svl_RiskTier.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www. j av a 2 s .c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { response.setContentType("text/html;charset=UTF-8"); try { String accion = request.getParameter("accion"); JsonObject json = new JsonObject(); switch (accion) { case "listar": { ArrayList<RiskTier> arr = new BnRiskTier().listar(); //ArrayList<RiskTier> arr = null; if (arr != null) { json.addProperty("estado", D.EST_OK); json.add("datos", new Gson().toJsonTree(arr)); } else { json.addProperty("estado", D.EST_NORESULTADO); json.addProperty("descripcion", "Sin datos"); } response.getWriter().print(json); break; } case "listar-riskindicator": { ArrayList<TablaRiskIndicator> arr = new BnTablaRiskIndicator().listar2(); ArrayList<ValorTablaCore> vtc = new BnValorTablaCore().listar(); if (arr != null) { json.addProperty("estado", D.EST_OK); json.add("datos", new Gson().toJsonTree(arr)); json.add("def", new Gson().toJsonTree(vtc)); // json.add("def", vtc); } else { json.addProperty("estado", D.EST_NORESULTADO); json.addProperty("descripcion", "Sin datos"); } response.getWriter().print(json); break; } case "guardar-risktier": { JSONObject jsonRiskTier = new JSONObject(request.getParameter("obRiskTier")); int idTipoRiskTier = jsonRiskTier.getInt("tipoRiskTier"); int numFilas = jsonRiskTier.getInt("filas"); int numCols = jsonRiskTier.getInt("columnas"); int idOrigenX = jsonRiskTier.getJSONObject("variableX").getInt("id"); int idOrigenY = jsonRiskTier.getJSONObject("variableY").getInt("id"); JSONArray origenX = jsonRiskTier.getJSONObject("variableX").getJSONArray("datos"); JSONArray origenY = jsonRiskTier.getJSONObject("variableY").getJSONArray("datos"); JSONArray jsonClasificacion = jsonRiskTier.getJSONArray("datos"); TablaRiskIndicator riskIndicator = new TablaRiskIndicator(BigInteger.ZERO, new Variable(idOrigenX, null), new Variable(idOrigenY, null), numFilas, numCols); json = new JsonObject(); if (new BnTablaRiskIndicator().guardarRiskInidcator(riskIndicator, origenX, origenY, jsonClasificacion, idTipoRiskTier)) { json.addProperty("estado", D.EST_OK); json.add("datos", new JsonObject()); } else { json.addProperty("estado", D.EST_NORESULTADO); json.addProperty("descripcion", "Error al guardar Risk Tier"); } response.getWriter().print(json); break; } case "listar-admin-risktier": { json = new JsonObject(); ArrayList<AdminRiskTier> arr = new BnAdminRiskTier().listar(); if (arr.size() > 0) { json.addProperty("estado", D.EST_OK); json.add("datos", new Gson().toJsonTree(arr)); } else { json.addProperty("estado", D.EST_NORESULTADO); json.addProperty("descripcion", "Sin datos"); } response.getWriter().print(json); break; } case "update-detalle-admin": { JSONArray jsonData = new JSONArray(request.getParameter("detalles")); for (int i = 0; i < jsonData.length(); i++) { JSONObject ob = jsonData.getJSONObject(i); new BnAdminRiskTier().actualizar(ob.getString("valor"), ob.getInt("idDetalleAdminRiskTier")); } json = new JsonObject(); json.addProperty("estado", D.EST_OK); response.getWriter().print(json); break; } case "listar-detalle-admin-risktier": { json = new JsonObject(); int idAdminRiskTier = Integer.parseInt(request.getParameter("idAdminRiskTier")); ArrayList<DetalleAdminRiskTier> arr = new BnAdminRiskTier().listarDetalles(idAdminRiskTier); if (arr.size() > 0) { json.addProperty("estado", D.EST_OK); json.add("datos", new Gson().toJsonTree(arr)); } else { json.addProperty("estado", D.EST_NORESULTADO); json.addProperty("descripcion", "Error al listar Risk Tier"); } response.getWriter().print(json); break; } case "listar-depuracion-renta": { json = new JsonObject(); // ArrayList<DepuracionRenta> arr = new BnDepuracionRenta().listar(); // if (arr.size() > 0) { // json.addProperty("estado", D.EST_OK); // json.add("datos", new Gson().toJsonTree(arr)); // } else { // json.addProperty("estado", D.EST_NORESULTADO); // json.addProperty("descripcion", "No data"); // } // response.getWriter().print(json); break; } case "guardar-depuracion-renta": { json = new JsonObject(); // ArrayList<DepuracionRenta> arr = new ArrayList<>(); // // DepuracionRenta dr = new DepuracionRenta(); // dr.setId(Integer.parseInt(request.getParameter("id_deuda_cred_hipotecario"))); // dr.setPorcentajeRenta(request.getParameter("deuda_cred_hipotecario")); // arr.add(dr); // // dr = new DepuracionRenta(); // dr.setId(Integer.parseInt(request.getParameter("id_deuda_comercial"))); // dr.setPorcentajeRenta(request.getParameter("deuda_comercial")); // arr.add(dr); // // dr = new DepuracionRenta(); // dr.setId(Integer.parseInt(request.getParameter("id_deuda_credito_consumo"))); // dr.setPorcentajeRenta(request.getParameter("deuda_credito_consumo")); // arr.add(dr); // // boolean flag = new BnDepuracionRenta().actualizar(arr); // if (flag) { // json.addProperty("estado", D.EST_OK); // } else { // json.addProperty("estado", D.EST_NORESULTADO); // json.addProperty("descripcion", "Error al guardar datos"); // } // // response.getWriter().print(json); break; } case "arbol-risk-tier": { json = new JsonObject(); JsonObject resp = new BnRiskTier().listarArbol2(); if (resp != null) { json.addProperty("estado", D.EST_OK); json.add("datos", resp); } else { json.addProperty("estado", D.EST_NORESULTADO); json.addProperty("descripcion", "Sin datos"); } response.getWriter().print(json); break; } } } catch (JSONException ex) { Logger.getLogger(Svl_RiskTier.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:cl.expertchoice.svl.Svl_Scoring.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w. ja v a2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try { String accion = request.getParameter("accion"); JsonObject json = new JsonObject(); switch (accion) { case "scoring": { int rut = Integer.parseInt(request.getParameter("rut")); String dv = request.getParameter("dv"); JsonObject jsonCalculos = new JsonObject(); int mesActual = BnScore.obtenerScoring(rut, dv, 0); int mes2 = BnScore.obtenerScoring(rut, dv, 1); int mes3 = BnScore.obtenerScoring(rut, dv, 2); int mes4 = BnScore.obtenerScoring(rut, dv, 3); jsonCalculos.addProperty("mes1", mesActual); jsonCalculos.addProperty("mes2", mes2); jsonCalculos.addProperty("mes3", mes3); jsonCalculos.addProperty("mes4", mes4); json.addProperty("estado", 200); json.add("datos", jsonCalculos); response.getWriter().print(json); break; } //Codigo A.M: case "ObtenerScore": { int score = Integer.parseInt(request.getParameter("score")); JsonObject jsonCalculos = new JsonObject(); Metodos metodo = new Metodos(); String scoreText = metodo.ObtenerScore(score); jsonCalculos.addProperty("scoreText", scoreText); json.addProperty("estado", 200); json.add("datos", jsonCalculos); response.getWriter().print(json); break; } } } catch (Exception ex) { // response.getWriter().print("{ \"estado\" : " + D.EST_ERROR + ", \"descripcion\" : \"" + ex + "\" }"); // D.escribirLog(ex, "Svl_Cliente"); // ex.printStackTrace(); } }
From source file:client.commands.TwitchAPICommands.java
License:Apache License
@Override public void run() { if (!this.isAllowed()) return;/* www . j a va 2 s . com*/ if (this.m.getMessage().startsWith("!game")) { String[] arr = this.m.getMessage().split(" ", 2); if (arr.length > 1) { JsonObject innerbody = new JsonObject(); innerbody.addProperty("game", this.m.getMessage().split(" ", 2)[1]); JsonObject obj = new JsonObject(); obj.add("channel", innerbody); System.out.println(obj.toString()); TwitchAPI api = new TwitchAPI(s.getClientid(), s.getOauth()); api.PUT("https://api.twitch.tv/kraken/channels/" + this.m.getChannel(), obj.toString()); } else { TwitchAPI api = new TwitchAPI(s.getClientid(), s.getOauth()); this.mq.offer(new MessageOut(this.m.getChannel().toLowerCase(), api.GET("https://api.twitch.tv/kraken/channels/" + this.m.getChannel()).get("game") .toString())); } } }
From source file:clientcommunicator.Server.Cookie.java
private JsonObject getUserJsonObject(JsonElement element, boolean setNew) throws MalformedCookieException { JsonObject jobject = element.getAsJsonObject(); if (!jobject.has("playerID")) { throw new MalformedCookieException(); }// ww w .j a v a 2 s. c o m JsonObject resultingCookie = new JsonObject(); resultingCookie.add("name", jobject.get("name")); resultingCookie.add("password", jobject.get("password")); resultingCookie.add("playerID", jobject.get("playerID")); if (setNew) { try { String realCookie = resultingCookie.toString(); realCookie = java.net.URLEncoder.encode(realCookie, "UTF-8"); this.userInformationString = realCookie; } catch (UnsupportedEncodingException ex) { Logger.getLogger(Cookie.class.getName()).log(Level.SEVERE, null, ex); } } return jobject; }