com.google.gson.GsonBuilder Java Examples

The following examples show how to use com.google.gson.GsonBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiClient.java    From devicehive-java with Apache License 2.0 6 votes vote down vote up
private void createDefaultAdapter(String url) {
    DateTimeTypeAdapter typeAdapter = new DateTimeTypeAdapter(Const.TIMESTAMP_FORMAT);
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(DateTime.class,
                    typeAdapter)
            .create();
    okClient = new OkHttpClient().newBuilder()
            .readTimeout(35, TimeUnit.SECONDS)
            .connectTimeout(35, TimeUnit.SECONDS)
            .build();

    if (!url.endsWith("/")) url = url + "/";

    adapterBuilder = new Retrofit
            .Builder()
            .baseUrl(url)
            .client(okClient)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonCustomConverterFactory.create(gson));

}
 
Example #2
Source File: AuthenticationInterceptor.java    From EasyEE with MIT License 6 votes vote down vote up
/**
 * 设置当前用户的菜单
 * 
 * @param session
 * @param token
 */
public void initMenu(Session session, UsernamePasswordEncodeToken token) {
	// Set<SysMenuPermission> menus = new HashSet<SysMenuPermission>();
	// Set<SysRole> roles = sysUser.getSysRoles(); // Roles
	// // 菜单权限
	// for (SysRole role : roles) {
	// Set<SysMenuPermission> menuPermissions =
	// role.getSysMenuPermissions();
	// for (SysMenuPermission menuPermission : menuPermissions) {
	// menus.add(menuPermission);
	// }
	// }

	List<SysMenuPermission> menus = sysMenuPermissionService.listByUserId(token.getUserId());

	// 将菜单权限集合转为EasyUI菜单Tree
	List<EasyUITreeEntity> list = EasyUIUtil.getEasyUITreeFromUserMenuPermission(menus);
	Gson gson = new GsonBuilder().create();
	String menuTreeJson = gson.toJson(list);
	// session.setAttribute("menus", menus); //菜单权限集合 info
	session.setAttribute("menuTreeJson", menuTreeJson); // 菜单权限集合 info
}
 
Example #3
Source File: TwillRuntimeSpecificationAdapter.java    From twill with Apache License 2.0 6 votes vote down vote up
private TwillRuntimeSpecificationAdapter() {
  gson = new GsonBuilder()
            .serializeNulls()
            .registerTypeAdapter(TwillRuntimeSpecification.class, new TwillRuntimeSpecificationCodec())
            .registerTypeAdapter(TwillSpecification.class, new TwillSpecificationCodec())
            .registerTypeAdapter(TwillSpecification.Order.class, new TwillSpecificationOrderCoder())
            .registerTypeAdapter(TwillSpecification.PlacementPolicy.class,
                                 new TwillSpecificationPlacementPolicyCoder())
            .registerTypeAdapter(EventHandlerSpecification.class, new EventHandlerSpecificationCoder())
            .registerTypeAdapter(RuntimeSpecification.class, new RuntimeSpecificationCodec())
            .registerTypeAdapter(TwillRunnableSpecification.class, new TwillRunnableSpecificationCodec())
            .registerTypeAdapter(ResourceSpecification.class, new ResourceSpecificationCodec())
            .registerTypeAdapter(LocalFile.class, new LocalFileCodec())
            .registerTypeAdapterFactory(new TwillSpecificationTypeAdapterFactory())
            .create();
}
 
Example #4
Source File: Config.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
private static Gson createGsonParser(FileSystem fileSystem) {
  Path cwd = normalizedAbsolutePath(fileSystem, "");
  return new GsonBuilder()
      .registerTypeAdapter(Config.class, new ConfigMarshaller(fileSystem))
      .registerTypeAdapter(Path.class, new PathDeserializer(fileSystem))
      .registerTypeAdapter(PathSpec.class, new PathSpecDeserializer(cwd))
      .registerTypeAdapter(Pattern.class, new PatternDeserializer())
      .registerTypeAdapter(
          new TypeToken<Optional<Path>>() {}.getType(), new OptionalDeserializer<>(Path.class))
      .registerTypeAdapter(
          new TypeToken<Optional<String>>() {}.getType(),
          new OptionalDeserializer<>(String.class))
      .registerTypeAdapter(
          new TypeToken<ImmutableSet<MarkdownPage>>() {}.getType(),
          new ImmutableSetDeserializer<>(MarkdownPage.class))
      .registerTypeAdapter(
          new TypeToken<ImmutableSet<Path>>() {}.getType(),
          new ImmutableSetDeserializer<>(Path.class))
      .registerTypeAdapter(
          new TypeToken<ImmutableSet<Pattern>>() {}.getType(),
          new ImmutableSetDeserializer<>(Pattern.class))
      .create();
}
 
Example #5
Source File: IntegrationMockClient.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
public boolean terminateInstance(String instanceId) {
    try {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Terminate instance: [instance-id] %s", instanceId));
        }
        URI uri = new URIBuilder(endpoint + INSTANCES_CONTEXT + instanceId).build();
        org.apache.stratos.mock.iaas.client.rest.HttpResponse response = doDelete(uri);
        if (response != null) {
            if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) {
                return true;
            } else {
                GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.create();
                org.apache.stratos.mock.iaas.domain.ErrorResponse errorResponse = gson.fromJson(response.getContent(), org.apache.stratos.mock.iaas.domain.ErrorResponse.class);
                if (errorResponse != null) {
                    throw new RuntimeException(errorResponse.getErrorMessage());
                }
            }
        }
        throw new RuntimeException("An unknown error occurred");
    } catch (Exception e) {
        String message = "Could not start mock instance";
        throw new RuntimeException(message, e);
    }
}
 
Example #6
Source File: AgentManagementServiceImpl.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * Stores userid/pwd/token and aws credentials in vault engine as per agent.
 * 
 * @param dataMap {eg: {"data":{"passwd":"password","userid":"userid"}}}
 * @param agentId
 * @return vaultresponse
 * @throws InsightsCustomException
 */
private ClientResponse storeToVault(HashMap<String, Map<String, String>> dataMap, String agentId)
		throws InsightsCustomException {
	ClientResponse vaultresponse = null;
	try {
		GsonBuilder gb = new GsonBuilder();
		Gson gsonObject = gb.create();
		String jsonobj = gsonObject.toJson(dataMap);
		log.debug("Request body for vault {} -- ", jsonobj);
		String url = ApplicationConfigProvider.getInstance().getVault().getVaultEndPoint()
				+ ApplicationConfigProvider.getInstance().getVault().getSecretEngine() + "/data/" + agentId;
		log.debug("url {}--", url);
		WebResource resource = Client.create().resource(url);
		vaultresponse = resource.type("application/json")
				.header("X-Vault-Token", ApplicationConfigProvider.getInstance().getVault().getVaultToken())
				.post(ClientResponse.class, jsonobj);
	} catch (Exception e) {
		log.error("Error while Storing to vault agent {} ", e);
		throw new InsightsCustomException(e.getMessage());
	}
	return vaultresponse;
}
 
Example #7
Source File: BaseServiceCleanArch.java    From CleanArchitecturePlugin with Apache License 2.0 6 votes vote down vote up
public Retrofit getAdapter() {
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .addInterceptor(new LoggingInterceptor())
            .build();

    Gson gson = new GsonBuilder()
            .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
            .serializeNulls()
            .create();

    return new Retrofit.Builder()
            .baseUrl(Constants.ENDPOINT)
            .client(client)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
}
 
Example #8
Source File: TMDbClient.java    From Amphitheatre with Apache License 2.0 6 votes vote down vote up
private static TMDbService getService() {
    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

    if (service == null) {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setConverter(new GsonConverter(gson))
                .setEndpoint(ApiConstants.TMDB_SERVER_URL)
                .setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade request) {
                        request.addQueryParam("api_key", ApiConstants.TMDB_SERVER_API_KEY);
                    }
                })
                .build();
        service = restAdapter.create(TMDbService.class);
    }
    return service;
}
 
Example #9
Source File: Utils.java    From Tutorials with Apache License 2.0 6 votes vote down vote up
public static List<Feed> loadFeeds(Context context){
    try{
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        JSONArray array = new JSONArray(loadJSONFromAsset(context, "news.json"));
        List<Feed> feedList = new ArrayList<>();
        for(int i=0;i<array.length();i++){
            Feed feed = gson.fromJson(array.getString(i), Feed.class);
            feedList.add(feed);
        }
        return feedList;
    }catch (Exception e){
        Log.d(TAG,"seedGames parseException " + e);
        e.printStackTrace();
        return null;
    }
}
 
Example #10
Source File: RoleController.java    From hauth-java with MIT License 6 votes vote down vote up
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(HttpServletResponse response, HttpServletRequest request) {
    String json = request.getParameter("JSON");
    List<RoleEntity> list = new GsonBuilder().create().fromJson(json, new TypeToken<List<RoleEntity>>() {
    }.getType());

    for (RoleEntity m : list) {
        AuthDTO authDTO = authService.domainAuth(request, m.getDomain_id(), "w");
        if (!authDTO.getStatus()) {
            return Hret.error(403, "您没有权限删除域【" + m.getDomain_id() + "】中的角色信息", null);
        }
    }

    RetMsg retMsg = roleService.delete(list);
    if (!retMsg.checkCode()) {
        response.setStatus(retMsg.getCode());
        return Hret.error(retMsg);
    }
    return Hret.success(retMsg);
}
 
Example #11
Source File: Feature.java    From mapbox-java with MIT License 6 votes vote down vote up
/**
 * This takes the currently defined values found inside this instance and converts it to a GeoJson
 * string.
 *
 * @return a JSON string which represents this Feature
 * @since 1.0.0
 */
@Override
public String toJson() {

  Gson gson = new GsonBuilder()
          .registerTypeAdapterFactory(GeoJsonAdapterFactory.create())
          .registerTypeAdapterFactory(GeometryAdapterFactory.create())
          .create();


  // Empty properties -> should not appear in json string
  Feature feature = this;
  if (properties().size() == 0) {
    feature = new Feature(TYPE, bbox(), id(), geometry(), null);
  }

  return gson.toJson(feature);
}
 
Example #12
Source File: AfterRegistShareDialogActivity.java    From Social with Apache License 2.0 6 votes vote down vote up
private void handleGetShareInfo(Message msg){
    String result = msg.obj.toString();
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    ShareInfoRoot root = gson.fromJson(result, ShareInfoRoot.class);

    if (root == null){
        //new Dialog(this,"错误","链接服务器失败").show();
        Toast.makeText(this, "服务器繁忙,请重试", Toast.LENGTH_LONG).show();
        return;
    }

    switch (share_type){
        case 1:
            shareQqone(root.content, root.url, root.img_url);
            break;
        case 2:
            shareWechatMoment(root.content, root.url, root.img_url);
            break;
        case 3:
            shareSina(root.content, root.url, root.img_url);
            break;
    }

}
 
Example #13
Source File: TraderUMainConfiguration.java    From java-trader with Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new StringHttpMessageConverter());
    converters.add(new FormHttpMessageConverter());
    GsonHttpMessageConverter c = new GsonHttpMessageConverter();
    c.setGson(new GsonBuilder().disableHtmlEscaping().create());
    converters.add(c);
    converters.add(new ResourceHttpMessageConverter());
}
 
Example #14
Source File: GroupDataActivity.java    From Social with Apache License 2.0 5 votes vote down vote up
private void handleDeleteGroup(Message msg){
    String result = msg.obj.toString();
    Log.d("NearbyFragment", result);
    gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    root = gson.fromJson(result, Root.class);

    if(root==null){
        //new Dialog(this,"错误","链接服务器失败").show();
        Toast.makeText(this,"服务器繁忙,请重试",Toast.LENGTH_LONG).show();
        return ;
    }
    if (root.success == false){
        new Dialog(this,"错误",root.message).show();
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
         try {
             EMClient.getInstance().groupManager().destroyGroup(hx_group_id);//需异步处理
         }catch (HyphenateException e){
             e.printStackTrace();
         }
        }
    }).start();

    Dialog dialog = new Dialog(this,"Tips","删除成功");
    dialog.setOnAcceptButtonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent("com.allever.social.refresh_group_list");
            sendBroadcast(intent);
            GroupDataActivity.this.finish();
        }
    });
    dialog.show();
}
 
Example #15
Source File: BaseController.java    From EasyEE with MIT License 5 votes vote down vote up
/**
 * 设置当前用户的菜单
 */
public void initMenuAndOperationsName(SysUser sysUser) {
	HttpSession session = request.getSession();
	List<SysMenuPermission> menus = sysMenuPermissionService.listByUserId(sysUser.getUserId());

	// 将菜单权限集合转为EasyUI菜单Tree
	List<EasyUITreeEntity> list = EasyUIUtil.getEasyUITreeFromUserMenuPermission(menus);
	Gson gson = new GsonBuilder().create();
	String menuTreeJson = gson.toJson(list);
	session.setAttribute("menuTreeJson", menuTreeJson); // 菜单权限集合 info

	// 保存所有权限对应的权限名称,权限备注
	session.setAttribute("operationsName", sysOperationPermissionService.getAllOpreationNames());
}
 
Example #16
Source File: GsonUtil.java    From ECharts with MIT License 5 votes vote down vote up
/**
 * 反序列化
 *
 * @param json
 * @return
 */
public static Option fromJSON(String json) {
    Gson gson = new GsonBuilder().setPrettyPrinting().
            registerTypeAdapter(Series.class, new SeriesDeserializer()).
            registerTypeAdapter(Axis.class, new AxisDeserializer()).create();
    Option option = gson.fromJson(json, Option.class);
    return option;
}
 
Example #17
Source File: PropertiesSerializer.java    From repairnator with MIT License 5 votes vote down vote up
@Override
public void serialize() {
    Gson gson = new GsonBuilder().registerTypeAdapter(Properties.class, new PropertiesSerializerAdapter()).create();
    JsonObject element = (JsonObject)gson.toJsonTree(inspector.getJobStatus().getProperties());

    element.addProperty("runId", RepairnatorConfig.getInstance().getRunId());
    Date reproductionDateBeginning = inspector.getJobStatus().getProperties().getReproductionBuggyBuild().getReproductionDateBeginning();
    reproductionDateBeginning = reproductionDateBeginning == null ? new Date() : reproductionDateBeginning;
    this.addDate(element, "reproductionDate", reproductionDateBeginning);
    element.addProperty("buildStatus", inspector.getBuildToBeInspected().getStatus().name());
    element.addProperty("buggyBuildId", inspector.getBuggyBuild().getId());
    if (inspector.getPatchedBuild() != null) {
        element.addProperty("patchedBuildId", inspector.getPatchedBuild().getId());
    }
    element.addProperty("status",this.getPrettyPrintState(inspector));

    JsonObject elementFreeMemory = new JsonObject();
    Map<String, Long> freeMemoryByStep = inspector.getJobStatus().getFreeMemoryByStep();
    for (Map.Entry<String, Long> stepFreeMemory : freeMemoryByStep.entrySet()) {
        elementFreeMemory.addProperty(stepFreeMemory.getKey(), stepFreeMemory.getValue());
    }
    element.add("freeMemoryByStep", elementFreeMemory);

    List<SerializedData> dataList = new ArrayList<>();

    dataList.add(new SerializedData(new ArrayList<>(), element));

    for (SerializerEngine engine : this.getEngines()) {
        engine.serialize(dataList, this.getType());
    }
}
 
Example #18
Source File: NinePatchGenerationTest.java    From androidsvgdrawable-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void fromJson() throws URISyntaxException, JsonIOException, JsonSyntaxException, IOException, TranscoderException, InstantiationException, IllegalAccessException {
    try (final Reader reader = new InputStreamReader(new FileInputStream(PATH_IN + ninePatchConfig))) {
        Type t = new TypeToken<Set<NinePatch>>() {}.getType();
        Set<NinePatch> ninePatchSet = new GsonBuilder().create().fromJson(reader, t);
        NinePatchMap ninePatchMap = NinePatch.init(ninePatchSet);
        QualifiedResource svg = qualifiedSVGResourceFactory.fromSVGFile(new File(PATH_IN + resourceName));
        NinePatch ninePatch = ninePatchMap.getBestMatch(svg);

        assertNotNull(ninePatch);

        final String name = svg.getName();
    	Reflect.on(svg).set("name", name + "_" + targetDensity.name());
        plugin.transcode(svg, targetDensity, new File(PATH_OUT), ninePatch);
     final File ninePatchFile = new File(PATH_OUT, svg.getName() + ".9." + OUTPUT_FORMAT.name().toLowerCase());
        final File nonNinePatchFile = new File(PATH_OUT, svg.getName() + "." + OUTPUT_FORMAT.name().toLowerCase());

        if (OUTPUT_FORMAT.hasNinePatchSupport()) {
        	assertTrue(FilenameUtils.getName(ninePatchFile.getAbsolutePath()) + " does not exists although the output format supports nine patch", ninePatchFile.exists());
        	assertTrue(FilenameUtils.getName(nonNinePatchFile.getAbsolutePath()) + " file does not exists although the output format supports nine patch", !nonNinePatchFile.exists());
         BufferedImage image = ImageIO.read(new FileInputStream(ninePatchFile));
      tester.test(image);
      // test corner pixels
      int w = image.getWidth();
      int h = image.getHeight();
      new PixelTester(new int[][] {}, new int[][] {
      		{0, 0},
      		{0, h - 1},
      		{w - 1, 0},
      		{w - 1, h - 1}
      }).test(image);
        } else {
        	assertTrue(FilenameUtils.getName(ninePatchFile.getAbsolutePath()) + " exists although the output format does not support nine patch", !ninePatchFile.exists());
        	assertTrue(FilenameUtils.getName(nonNinePatchFile.getAbsolutePath()) + " does not exists although the output format does not support nine patch", nonNinePatchFile.exists());
        }
    }
}
 
Example #19
Source File: Calibration.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public String toS() {
    Gson gson = new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation()
            .registerTypeAdapter(Date.class, new DateTypeAdapter())
            .serializeSpecialFloatingPointValues()
            .create();
    return gson.toJson(this);
}
 
Example #20
Source File: GroupDefineController.java    From batch-scheduler with MIT License 5 votes vote down vote up
@RequestMapping(value = "/task/update", method = RequestMethod.PUT)
@ResponseBody
public String updateTask(HttpServletResponse response, HttpServletRequest request) {
    String json = request.getParameter("JSON");
    List<GroupTaskDto> list = new GsonBuilder().create().fromJson(json,
            new TypeToken<List<GroupTaskDto>>() {
            }.getType());
    RetMsg retMsg = groupTaskService.updateTaskLocation(list);
    if (retMsg.checkCode()) {
        return Hret.error(retMsg);
    }
    return Hret.success(retMsg);
}
 
Example #21
Source File: RestClient.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
public boolean updateEntity(String filePath, String resourcePath, String entityName) {
    try {
        String content = getJsonStringFromFile(filePath);
        URI uri = new URIBuilder(this.endPoint + resourcePath).build();

        HttpResponse response = doPut(uri, content);
        if (response != null) {
            if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) {
                return true;
            } else {
                GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.create();
                ErrorResponse errorResponse = gson.fromJson(response.getContent(),
                        ErrorResponse.class);
                if (errorResponse != null) {
                    throw new RuntimeException(errorResponse.getErrorMessage());
                }
            }
        }
        String msg = "An unknown error occurred while trying to update ";
        log.error(msg + entityName);
        throw new RuntimeException(msg + entityName);
    } catch (Exception e) {
        String message = "Could not update " + entityName;
        log.error(message, e);
        throw new RuntimeException(message, e);
    }
}
 
Example #22
Source File: HarFileHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private void saveHar() throws IOException, TechnicalConnectorException {
   String fileName = IdGeneratorFactory.getIdGenerator("uuid").generateId() + ".har";
   File file = new File(this.outputdir, fileName);
   LOG.info("Writing har file on location: {}", file.getPath());
   Gson gson = (new GsonBuilder()).setPrettyPrinting().create();
   gson.toJson(this.harJson, new JsonWriter(new FileWriter(file)));
}
 
Example #23
Source File: TypeAdapterPrecedenceTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testNonstreamingHierarchicalFollowedByNonstreaming() {
  Gson gson = new GsonBuilder()
      .registerTypeHierarchyAdapter(Foo.class, newSerializer("hierarchical"))
      .registerTypeHierarchyAdapter(Foo.class, newDeserializer("hierarchical"))
      .registerTypeAdapter(Foo.class, newSerializer("non hierarchical"))
      .registerTypeAdapter(Foo.class, newDeserializer("non hierarchical"))
      .create();
  assertEquals("\"foo via non hierarchical\"", gson.toJson(new Foo("foo")));
  assertEquals("foo via non hierarchical", gson.fromJson("foo", Foo.class).name);
}
 
Example #24
Source File: SuggestionServiceImpl.java    From intellij-spring-assistant with MIT License 5 votes vote down vote up
private void processContainers(Module module, List<MetadataContainerInfo> containersToProcess,
    List<MetadataContainerInfo> containersToRemove,
    Map<String, MetadataContainerInfo> seenContainerPathToContainerInfo,
    Trie<String, MetadataSuggestionNode> rootSearchIndex) {
  // Lets remove references to files that are no longer present in classpath
  containersToRemove.forEach(
      container -> removeReferences(seenContainerPathToContainerInfo, rootSearchIndex,
          container));

  for (MetadataContainerInfo metadataContainerInfo : containersToProcess) {
    // lets remove existing references from search index, as these files are modified, so that we can rebuild index
    if (seenContainerPathToContainerInfo
        .containsKey(metadataContainerInfo.getContainerArchiveOrFileRef())) {
      removeReferences(seenContainerPathToContainerInfo, rootSearchIndex, metadataContainerInfo);
    }

    String metadataFilePath = metadataContainerInfo.getFileUrl();
    try (InputStream inputStream = metadataContainerInfo.getMetadataFile().getInputStream()) {
      GsonBuilder gsonBuilder = new GsonBuilder();
      // register custom mapper adapters
      gsonBuilder.registerTypeAdapter(SpringConfigurationMetadataValueProviderType.class,
          new SpringConfigurationMetadataValueProviderTypeDeserializer());
      gsonBuilder.registerTypeAdapterFactory(new GsonPostProcessEnablingTypeFactory());
      SpringConfigurationMetadata springConfigurationMetadata = gsonBuilder.create()
          .fromJson(new BufferedReader(new InputStreamReader(inputStream)),
              SpringConfigurationMetadata.class);
      buildMetadataHierarchy(module, rootSearchIndex, metadataContainerInfo,
          springConfigurationMetadata);

      seenContainerPathToContainerInfo
          .put(metadataContainerInfo.getContainerArchiveOrFileRef(), metadataContainerInfo);
    } catch (IOException e) {
      log.error("Exception encountered while processing metadata file: " + metadataFilePath, e);
      removeReferences(seenContainerPathToContainerInfo, rootSearchIndex, metadataContainerInfo);
    }
  }
}
 
Example #25
Source File: DispatchService.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Response<Collection<Patient>> fromJson(Message msg) {
    Type type = new TypeToken<Response<List<Patient>>>() {
    }.getType();
    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat(DispatchService.this.getString(R.string.cfg_format_date_value))
            .create();
    Response<Collection<Patient>> response = gson.fromJson(msg.obj.toString(), type);
    return response;
}
 
Example #26
Source File: PolicyRefresher.java    From ranger with Apache License 2.0 5 votes vote down vote up
public PolicyRefresher(RangerBasePlugin plugIn) {
	if(LOG.isDebugEnabled()) {
		LOG.debug("==> PolicyRefresher(serviceName=" + plugIn.getServiceName() + ").PolicyRefresher()");
	}

	RangerPluginConfig pluginConfig   = plugIn.getConfig();
	String             propertyPrefix = pluginConfig.getPropertyPrefix();

	this.plugIn      = plugIn;
	this.serviceType = plugIn.getServiceType();
	this.serviceName = plugIn.getServiceName();
	this.cacheDir    = pluginConfig.get(propertyPrefix + ".policy.cache.dir");

	String appId         = StringUtils.isEmpty(plugIn.getAppId()) ? serviceType : plugIn.getAppId();
	String cacheFilename = String.format("%s_%s.json", appId, serviceName);

	cacheFilename = cacheFilename.replace(File.separatorChar,  '_');
	cacheFilename = cacheFilename.replace(File.pathSeparatorChar,  '_');

	this.cacheFileName = cacheFilename;

	Gson gson = null;
	try {
		gson = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").create();
	} catch(Throwable excp) {
		LOG.fatal("PolicyRefresher(): failed to create GsonBuilder object", excp);
	}

	this.gson                          = gson;
	this.disableCacheIfServiceNotFound = pluginConfig.getBoolean(propertyPrefix + ".disable.cache.if.servicenotfound", true);
	this.rangerAdmin                   = RangerBasePlugin.createAdminClient(pluginConfig);
	this.rolesProvider                 = new RangerRolesProvider(getServiceType(), appId, getServiceName(), rangerAdmin,  cacheDir, pluginConfig);
	this.pollingIntervalMs             = pluginConfig.getLong(propertyPrefix + ".policy.pollIntervalMs", 30 * 1000);

	setName("PolicyRefresher(serviceName=" + serviceName + ")-" + getId());

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== PolicyRefresher(serviceName=" + serviceName + ").PolicyRefresher()");
	}
}
 
Example #27
Source File: ClusterStats.java    From karamel with Apache License 2.0 5 votes vote down vote up
public synchronized String toJsonAndMarkNotUpdated() {
  GsonBuilder builder = new GsonBuilder();
  builder.disableHtmlEscaping();
  Gson gson = builder.setPrettyPrinting().create();
  String json = gson.toJson(this);
  updated = false;
  return json;
}
 
Example #28
Source File: SecurityConfigurationGson.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope("prototype")
Gson gson() {
  return new GsonBuilder()
      .setPrettyPrinting()
      .registerTypeAdapter(NFVMessage.class, new NfvoGsonDeserializerNFVMessage())
      .registerTypeAdapter(BaseVimInstance.class, new NfvoGsonDeserializerVimInstance())
      .registerTypeAdapter(BaseVimInstance.class, new NfvoGsonSerializerVimInstance())
      .registerTypeAdapter(OAuth2AccessToken.class, new GsonSerializerOAuth2AccessToken())
      .create();
}
 
Example #29
Source File: InstantConverterTest.java    From gson-jodatime-serialisers with MIT License 5 votes vote down vote up
/**
 * Tests that serialising an instant with out milliseconds returns the expected ISO 8601 string
 */
@Test
public void testSerialiseWithOutMilliseconds()
{
  final Gson gson = Converters.registerInstant(new GsonBuilder()).create();
  final Instant instant = Instant.parse("2019-07-23T00:06:12Z");
  final String expectedJson = "\"2019-07-23T00:06:12.000Z\"";

  final String actualJson = gson.toJson(instant);

  assertThat(actualJson, is(expectedJson));
}
 
Example #30
Source File: CalibrationAbstract.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
protected static String dataToJsonString(CalibrationData data) {
    final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    try {
        return gson.toJson(data);
    } catch (NullPointerException e) {
        return "";
    }
}