List of usage examples for com.google.gson GsonBuilder create
public Gson create()
From source file:com.cloud.serializer.GsonHelper.java
License:Apache License
static Gson setDefaultGsonConfig(GsonBuilder builder) { builder.setVersion(1.5);// ww w .j a v a 2 s. co m ArrayTypeAdaptor<Command> cmdAdaptor = new ArrayTypeAdaptor<Command>(); builder.registerTypeAdapter(Command[].class, cmdAdaptor); ArrayTypeAdaptor<Answer> ansAdaptor = new ArrayTypeAdaptor<Answer>(); builder.registerTypeAdapter(Answer[].class, ansAdaptor); builder.registerTypeAdapter(new TypeToken<List<PortConfig>>() { }.getType(), new PortConfigListTypeAdaptor()); builder.registerTypeAdapter(new TypeToken<Pair<Long, Long>>() { }.getType(), new NwGroupsCommandTypeAdaptor()); Gson gson = builder.create(); cmdAdaptor.initGson(gson); ansAdaptor.initGson(gson); return gson; }
From source file:com.cloudbase.CBHelperRequest.java
License:Open Source License
@SuppressWarnings("unchecked") public void run() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(this.request.getUrl()); if (this.helperObject.isDebugMode()) Log.d("CBHELPER", "Sending request to url: " + this.request.getUrl()); try {/*from w w w .j a va 2 s.co m*/ // Add your data Enumeration<String> params = this.request.getParameters().keys(); // prepare the request adding all of the parameters. CBMultipartEntity entity = new CBMultipartEntity(); while (params.hasMoreElements()) { String curKey = params.nextElement(); entity.addPart(new CBStringPart(curKey, this.request.getParameters().get(curKey))); } // if we have file attachments then add each file to the multipart request if (this.request.getFiles() != null && this.request.getFiles().size() > 0) { int fileCounter = 0; for (File curFile : this.request.getFiles()) { String name = curFile.getName(); int pos = name.lastIndexOf('.'); String ext = name.substring(pos + 1); entity.addPart(new CBFilePart("file" + fileCounter, curFile, null, (pos > -1 ? MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) : null))); fileCounter++; } } // add the multipart request to the http connection httppost.setEntity(entity); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); // if we have a responder then parse the response data into the global CBHelperResponse object if (this.responder != null) { resp = new CBHelperResponse(); resp.setFunction(this.request.getCloudbaseFunction()); resp.setHttpStatus(response.getStatusLine().getStatusCode()); // if it's a download then we need to save the file content into a temporary file in // application cache folder. Then return that file to the responder if (this.request.getCloudbaseFunction().equals("download")) { InputStream input = response.getEntity().getContent(); File outputFile = File.createTempFile(this.request.getFileId(), null, new File(this.getTemporaryFilePath())); OutputStream fos = new BufferedOutputStream(new FileOutputStream(outputFile)); try { byte[] buffer = new byte[(int) 4096]; int readBytes; while (((readBytes = input.read(buffer, 0, buffer.length)) != -1)) { fos.write(buffer, 0, readBytes); } } catch (IOException e) { e.printStackTrace(); } if (fos != null) { try { fos.close(); } catch (IOException e) { } } if (input != null) { try { input.close(); } catch (IOException e) { } } resp.setDownloadedFile(outputFile); } else { // if it's not a download parse the JSON response and set all // the variables in the CBHelperResponse object String responseString = EntityUtils.toString(response.getEntity()); resp.setResponseDataString(responseString); if (this.helperObject.isDebugMode()) Log.d("test", resp.getResponseDataString()); // Use the cloudbase.io deserializer to get the data in a Map<String, Object> // format. GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Object.class, new CBNaturalDeserializer()); Gson gson = gsonBuilder.create(); Map<String, Object> responseData = gson.fromJson(responseString, Map.class); if (responseData == null) { resp.setErrorMessage("Empty response data"); resp.setSuccess(false); } else { Map<String, Object> outputData = (Map<String, Object>) responseData .get(this.request.getCloudbaseFunction()); resp.setData(outputData.get("message")); resp.setErrorMessage((String) outputData.get("error")); resp.setSuccess(((String) outputData.get("status")).equals("OK")); } } // now that the response object is ready use the Handler we have been handed from the // CBHelper class on the main thread to call the responder object. This way the data // is available to the UI thread mHandler.post(new Runnable() { @Override public void run() { responder.handleResponse(request, resp); } }); } if ((resp == null || resp.getHttpStatus() == 200) && this.queueFileName != null) { this.helperObject.removeQueuedRequest(this.queueFileName); } } catch (Exception e) { Log.e("REQUEST", "Error " + e.getMessage(), e); if (this.responder != null) { mHandler.post(new Runnable() { @Override public void run() { responder.handleResponse(request, resp); } }); } } }
From source file:com.cloudbees.eclipse.core.util.Utils.java
License:Open Source License
public static Gson createGson() { final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.serializeSpecialFloatingPointValues(); gsonBuilder.serializeNulls();//from w w w . j a v a 2 s. com // gsonBuilder.setPrettyPrinting(); // temporary // gsonBuilder.excludeFieldsWithoutExposeAnnotation(); Gson g = gsonBuilder.create(); return g; }
From source file:com.cloudsearch.model.ClientFile.java
License:Apache License
/** * Construct a new ClientFile from its JSON representation. * * @param in Reader of JSON string to parse. *//*from w ww . j av a 2 s . c o m*/ public ClientFile(Reader in) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); ClientFile other = gson.fromJson(in, ClientFile.class); this.resource_id = other.resource_id; this.title = other.title; this.description = other.description; this.mimeType = other.mimeType; this.content = other.content; this.labels = other.labels; this.editable = other.editable; this.parents = other.parents; }
From source file:com.cloudsearch.model.State.java
License:Apache License
/** * Create a new State given its JSON representation. * * @param json Serialized representation of a State. *//* ww w . j a va 2 s .c o m*/ public State(String json) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); State other = gson.fromJson(json, State.class); this.action = other.action; this.ids = other.ids; this.parentId = other.parentId; }
From source file:com.cognifide.aet.rest.MetadataServlet.java
License:Apache License
@Override protected void process(DBKey dbKey, HttpServletRequest req, HttpServletResponse resp) throws IOException { String correlationId = req.getParameter(Helper.CORRELATION_ID_PARAM); String suiteName = req.getParameter(Helper.SUITE_PARAM); String formatted = req.getParameter(FORMATTED_PARAM); resp.setCharacterEncoding("UTF-8"); Suite suite;/*ww w. ja va 2s . c om*/ try { if (isValidCorrelationId(correlationId)) { suite = metadataDAO.getSuite(dbKey, correlationId); } else if (isValidName(suiteName)) { suite = metadataDAO.getLatestRun(dbKey, suiteName); } else { resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); resp.getWriter().write(responseAsJson("Neither valid correlationId or suite param was specified.")); return; } } catch (StorageException e) { LOGGER.error("Failed to get suite", e); resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); resp.getWriter().write(responseAsJson("Failed to get suite: %s", e.getMessage())); return; } GsonBuilder gsonBuilder = new GsonBuilder(); if (formatted != null && "true".equals(formatted)) { gsonBuilder.setPrettyPrinting(); } String result = gsonBuilder.create().toJson(suite, Suite.class); resp.setContentType("application/json"); if (result != null) { resp.getWriter().write(result); } else { resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); resp.getWriter().write(responseAsJson("Unable to get Suite Metadata for %s", dbKey.toString())); } }
From source file:com.comapi.internal.network.RestClient.java
License:Open Source License
/** * Create Gson converter for the service. * * @return Gson converter.//w w w .j a va 2 s . c om */ private Gson createGson() { GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping().setLenient(). addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(SerializedName.class) == null; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); return gsonBuilder.create(); }
From source file:com.cubeia.poker.handhistory.impl.JsonHandHistoryLogger.java
License:Open Source License
private Gson createGson() { GsonBuilder b = new GsonBuilder(); b.registerTypeAdapter(HandHistoryEvent.class, new EventSerializer()); b.setPrettyPrinting();//from ww w. j av a 2s . c om return b.create(); }
From source file:com.cubeia.poker.handhistory.provider.impl.HandHistoryProviderServiceImpl.java
License:Open Source License
private Gson createGson() { GsonBuilder b = new GsonBuilder(); b.registerTypeAdapter(HandHistoryEvent.class, new HandHistorySerializer()); //b.setPrettyPrinting(); return b.create(); }
From source file:com.cypherlabs.easycalcpro.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Code block to validate application licensing //final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE); //String deviceId = tm.getDeviceId(); String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID); // Library calls this when it's done. mLicenseCheckerCallback = new EasyCalcProLicenseCheckerCallback(); mHandler = new Handler(); mChecker = new LicenseChecker(this, new ServerManagedPolicy(this, new AESObfuscator(SALT, getPackageName(), deviceId)), getResources().getString(R.string.BASE64_PUBLIC_KEY)); doCheck();/*w w w . j av a 2s .c o m*/ // this.input = (EditText) findViewById(R.id.input); this.output = (TextView) findViewById(R.id.output); this.outputInWords = (TextView) findViewById(R.id.output_words); //restore last session values SharedPreferences easyCalcSharedPreferences = null; easyCalcSharedPreferences = getSharedPreferences(Constants.ACTIVITY_STATE_PREFS, MODE_PRIVATE); if (easyCalcSharedPreferences != null) { String savedIputBreakDowns = easyCalcSharedPreferences.getString(Constants.INPUTBREAKDOWNS, Constants.EMPTY_STRING); GsonBuilder gsonb = new GsonBuilder(); Gson gson = gsonb.create(); Type type = new TypeToken<List<StringBuilder>>() { }.getType(); this.inputBreakdowns = gson.fromJson(savedIputBreakDowns, type); if (this.inputBreakdowns == null) { inputBreakdowns = new ArrayList<>(); } //restore input and numeral output this.input.setText(easyCalcSharedPreferences.getString(Constants.INPUT, Constants.EMPTY_STRING)); this.output.setText(easyCalcSharedPreferences.getString(Constants.OUTPUT_NUMERALS, "")); //restore language setting this.words_output_lang = easyCalcSharedPreferences.getString(Constants.WORDS_OUTPUT_LANG, null); if (words_output_lang == null) { this.words_output_lang = getResources().getString(R.string.main_english); } //restore english and hindi output values this.englishOutput = easyCalcSharedPreferences.getString(Constants.OUTPUT_ENGLISH, Constants.EMPTY_STRING); this.hindiOutput = easyCalcSharedPreferences.getString(Constants.OUTPUT_HINDI, Constants.EMPTY_STRING); //set word output as per language setting if (this.words_output_lang.equals(getResources().getString(R.string.main_english))) { MainActivity.this.outputInWords.setText(MainActivity.this.englishOutput); } if (this.words_output_lang.equals(getResources().getString(R.string.main_hindi))) { MainActivity.this.outputInWords.setText(MainActivity.this.hindiOutput); } //restore word output on/off boolean this.wordOutputOn = easyCalcSharedPreferences.getBoolean(Constants.WORD_OUTPUT_ON, true); if (!this.wordOutputOn) { this.outputInWords.setVisibility(View.GONE); } } entries.add("7"); entries.add("8"); entries.add("9"); entries.add("/"); entries.add("4"); entries.add("5"); entries.add("6"); entries.add("*"); entries.add("1"); entries.add("2"); entries.add("3"); entries.add("-"); entries.add("0"); entries.add("."); entries.add("="); entries.add("+"); if (this.wordOutputOn) { entries.add("ON");//to show word ourput or not } else { entries.add("OFF");//to show word ourput or not } entries.add("AC");//Clear function entries.add("DEL");//Clear last character entries.add("CPY");//copy functionality GridView gridview = (GridView) findViewById(R.id.gridview); TextAdapter textAdapter = new TextAdapter(this, this.entries); gridview.setAdapter(textAdapter); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }