Example usage for com.google.gson GsonBuilder create

List of usage examples for com.google.gson GsonBuilder create

Introduction

In this page you can find the example usage for com.google.gson GsonBuilder create.

Prototype

public Gson create() 

Source Link

Document

Creates a Gson instance based on the current configuration.

Usage

From source file:com.ecwid.mailchimp.internal.gson.MailChimpGsonFactory.java

License:Apache License

/**
 * Creates a new {@link Gson} object.//from w  w  w  . j a  v a2s. c  o m
 */
public static Gson createGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.setExclusionStrategies(exclusionStrategy);
    builder.registerTypeAdapter(Date.class, new DateTypeAdapter());
    builder.registerTypeAdapterFactory(MailChimpObjectTypeAdapter.FACTORY);
    return builder.create();
}

From source file:com.edduarte.argus.job.JobManager.java

License:Apache License

final boolean responseOk(final String documentUrl, final String clientUrl,
        final Set<DifferenceMatcher.Result> diffs) {
    Map<String, Object> jsonResponseMap = new LinkedHashMap<>();
    jsonResponseMap.put("status", "ok");
    jsonResponseMap.put("url", documentUrl);
    jsonResponseMap.put("diffs", diffs);
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Keyword.class, new KeywordSerializer());
    String input = gsonBuilder.create().toJson(jsonResponseMap);
    return sendResponse(clientUrl, input);
}

From source file:com.edduarte.argus.job.JobManager.java

License:Apache License

final boolean sendTimeoutResponse(final String documentUrl, final String clientUrl) {
    Map<String, Object> jsonResponseMap = new LinkedHashMap<>();
    jsonResponseMap.put("status", "timeout");
    jsonResponseMap.put("url", documentUrl);
    Set<DifferenceMatcher.Result> diffs = Collections.emptySet();
    jsonResponseMap.put("diffs", diffs);
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Keyword.class, new KeywordSerializer());
    String input = gsonBuilder.create().toJson(jsonResponseMap);
    return sendResponse(clientUrl, input);
}

From source file:com.edgenius.wiki.ext.calendar.service.CalendarServiceImpl.java

License:Open Source License

public String invokePluginService(String operation, String[] params) throws PluginServiceProviderException {
    if ("getEvent".equalsIgnoreCase(operation)) {
        if (params == null || params.length != 1 || NumberUtils.toInt(params[0], -1) == -1) {
            throw new PluginServiceProviderException("Unable to get correct event ID in parameter");
        }//  w  ww .  j a  v a  2  s .  c om

        Integer eventID = NumberUtils.toInt(params[0]);
        CalendarEvent event = calendarEventDAO.get(eventID);
        if (event == null) {
            throw new PluginServiceProviderException("Unable to get event.");
        }

        GsonBuilder gsonBuild = new GsonBuilder();
        return gsonBuild.create().toJson(CalendarEventJson.from(event));
    } else if ("saveEvent".equalsIgnoreCase(operation)) {
        //         pageUuid.getValue(),
        //         calendarName.getValue(),
        //         eventID.getValue(),
        //         color.getText(),
        //         subject.getText(), 
        //         String.valueOf(st.getTime()), 
        //         String.valueOf(ed.getTime()), 
        //         location.getText(),
        //         description.getText(),
        //         String.valueOf(isAllDayEvent.getValue()),
        //         repeatRule.getText()
        if (params == null || params.length != 11) {
            throw new PluginServiceProviderException("Unexpected parameters for saveEvent");
        }
        int idx = 0;

        String pageUuid = params[idx++];
        String calendarName = params[idx++];
        int eventID = NumberUtils.toInt(params[idx++]);
        int colorType = NumberUtils.toInt(params[idx++]);
        String subject = params[idx++];

        long time = NumberUtils.toLong(params[idx++]);
        if (time == 0)
            throw new PluginServiceProviderException("Unexpected start time for saveEvent " + time);
        Date st = new Date(time);

        time = NumberUtils.toLong(params[idx++]);
        if (time == 0)
            throw new PluginServiceProviderException("Unexpected end time for saveEvent " + time);

        Date ed = new Date(time);
        String location = params[idx++];
        String desc = params[idx++];
        boolean isAllDay = BooleanUtils.toBoolean(params[idx++]);
        String repeatRule = params[idx++];

        CalendarEvent event;
        if (eventID == 0) {
            log.info("new event saved for ");
            event = new CalendarEvent();
            Calendar cal = this.getCalendar(pageUuid, calendarName);
            if (cal == null)
                throw new PluginServiceProviderException(
                        "Failed get calendar from page " + pageUuid + " by name " + calendarName);

            event.setCalendar(cal);
        } else {
            event = calendarEventDAO.get(eventID);
            if (event == null) {
                throw new PluginServiceProviderException("Failed get event by id" + eventID);
            }
        }

        event.setCategory(colorType);
        event.setSubject(subject);
        event.setStart(st);
        event.setEnd(ed);
        event.setLocation(location);
        event.setContent(desc);
        event.setAllDayEvent(isAllDay);
        event.setRepeatRule(repeatRule);
        WikiUtil.setTouchedInfo(userReadingService, event);
        calendarEventDAO.saveOrUpdate(event);
        return "";
    } else {
        throw new PluginServiceProviderException("Invalid operation request " + operation);
    }
}

From source file:com.edgenius.wiki.ext.calendar.web.CalendarAction.java

License:Open Source License

/**
 * Browser all events in calendar.//from   w w  w  . j ava 2 s .co  m
 */
public String execute() {
    CalendarJson json;
    try {
        Date[] scope = CalendarUtil.getCalendarScope(CalendarConstants.VIEW.valueOf(viewType.toUpperCase()),
                new Date(), weekStartDay);
        List<CalendarEvent> calEvents = calendarService.getEvents(calendarName, pageUuid, scope[0], scope[1]);
        json = CalendarJson.toJson(calEvents, scope[0], scope[1]);
    } catch (Exception e) {
        CalendarErrorJson error = new CalendarErrorJson("001", "Get calendar data failed");
        json = new CalendarJson();
        json.setError(error);
        log.error("Get calendar failed", e);
    }

    try {
        GsonBuilder gsonBuild = new GsonBuilder();
        gsonBuild.registerTypeAdapter(Date.class, new DateSerializer());
        String jsonstr = gsonBuild.create().toJson(json);

        //hack - remove "@1111@" to new Date(1111) format. 
        String[] list = StringUtil.splitWithoutEscaped(jsonstr, "\"@");
        jsonstr = StringUtil.join("new Date(", list);
        jsonstr = jsonstr.replaceAll("@\"", ")");

        getResponse().getOutputStream().write(jsonstr.getBytes(Constants.UTF8));
    } catch (IOException e) {
        log.error("Calendar view get data failed", e);
    }
    return null;
}

From source file:com.elitise.appv2.Peripheral.java

License:Open Source License

@Override
protected void onStop() {

    super.onStop();
    disconnectFromDevices();//from   www  . j  a  va2 s.  c om
    GsonBuilder gsonb = new GsonBuilder();
    Gson gson = gsonb.create();
    String ownbatteries = gson.toJson(mUser.getBatteriesList());
    SharedPreferences prefs = this.getSharedPreferences("userdata", Context.MODE_PRIVATE);
    SharedPreferences.Editor e = prefs.edit();
    e.putString("batteris", ownbatteries);
    e.apply();
    if (mGattServer != null) {
        mGattServer.close();
    }
    if (mBluetoothAdapter.isEnabled() && mAdvertiser != null) {
        // If stopAdvertising() gets called before close() a null
        // pointer exception is raised.

        mAdvertiser.stopAdvertising(mAdvCallback);
    }
}

From source file:com.empresa.rest.services.IngresosRest.java

@PUT
@Path("inhabilit/{id}")
@Consumes(MediaType.APPLICATION_JSON)//w w w.  j  a  va2 s  .c  o  m
public Response inhabilit(@PathParam("id") Integer id) {
    Ingresos ingreso = ejbIngresosFacade.find(id);

    if (ingreso.getEstado()) {
        ingreso.setEstado(Boolean.FALSE);
    } else {
        ingreso.setEstado(Boolean.TRUE);

    }
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    try {
        ejbIngresosFacade.edit(ingreso);
        return Response.ok().entity(gson.toJson("El estado se ha cambiado")).build();
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.BAD_REQUEST).entity(gson.toJson("Error de persistencia"))
                .build();
    }
}

From source file:com.ericsson.eiffel.remrem.generate.config.GsonHttpMessageConverterConfig.java

License:Apache License

private Gson gson() {
    final GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter());
    return builder.create();
}

From source file:com.ericsson.jira.oslc.managers.JiraManager.java

License:Open Source License

/**
 * Add External link // w w  w . j  a  va  2  s  .  c o m
 * @param issueId the ID of issue where the links will be added to
 * @param linksList the list of the links which will be added to the issue
 * @return true - if the links will be added to the issue successfully, otherwise false
 * @throws IOException
 * @throws ServletException
 * @throws PermissionException
 */
public static Boolean addOSLCLink(final Long issueId, final ArrayList linksList)
        throws IOException, ServletException, PermissionException {
    logger.debug("JiraManager - addOSLCLink");
    DefaultIssueManager issueManager = ComponentAccessor.getComponent(DefaultIssueManager.class);
    MutableIssue issue = issueManager.getIssueObject(issueId);

    PermissionManager.checkPermission(null, issue, Permissions.EDIT_ISSUE);

    DefaultCustomFieldManager cfManager = (DefaultCustomFieldManager) ComponentAccessor.getCustomFieldManager();
    CustomField cf = cfManager.getCustomFieldObjectByName(JiraConstants.OSLC_CUSTOM_FIELD_NAME);

    if (cf == null) {
        return false;
    }

    // prepare GSON
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();

    String uri;
    String label;

    for (int iLink = 0; iLink < linksList.size(); iLink++) {
        ArrayList onelink = (ArrayList) linksList.get(iLink);
        if (onelink.size() > 1) {
            label = (String) onelink.get(0);
            uri = (String) onelink.get(1);
        } else {
            continue;
        }
        // get all application links which are already saved in custom
        // field
        String links = (String) cf.getValue(issue);
        AppLinksRepository appLinkList = new AppLinksRepository();

        if (links != "") {
            try {
                appLinkList = gson.fromJson(links, AppLinksRepository.class);
            } catch (com.google.gson.JsonSyntaxException e) {
                logger.debug("JiraManager - addOSLCLink - " + e.getMessage());
            }

            if (appLinkList == null) {
                appLinkList = new AppLinksRepository();
            }

            appLinkList.addAppLink(label, uri, true);
        }

        String updatedLinks = "";
        updatedLinks = gson.toJson(appLinkList);

        if (updatedLinks != null && updatedLinks != "") {
            cf.createValue(issue, updatedLinks);
        }

    } // for

    ApplicationUser user = PermissionManager.getLoggedUser();
    OSLCUtils.fireRestIssueEvent(issue, user, IssueEventType.ADD_EXT_LINK);

    return true;
}

From source file:com.ericsson.jira.oslc.managers.JiraManager.java

License:Open Source License

/**
 * It removes the external link from the issue
 * @param issueId the ID of issue//from  w ww.ja  v a 2  s  .c o m
 * @param URItoRemove URI of the link which will be removed from the issue
 * @return true - if the links will be removed to the issue successfully, otherwise false
 * @throws GetIssueException
 * @throws PermissionException
 */
public static Boolean removeOSLCLink(final String issueId, final String URItoRemove)
        throws GetIssueException, PermissionException {
    String currentMethod = "removeOSLCLink";
    logger.debug(CURRENT_CLASS + "." + currentMethod);

    DefaultIssueManager issueManager = ComponentAccessor.getComponent(DefaultIssueManager.class);
    Long issueIdLong = (long) -1;

    try {
        issueIdLong = Long.valueOf(issueId).longValue();
    } catch (Exception ex) {
        logger.error(CURRENT_CLASS + "." + currentMethod + "Exception: " + ex.getMessage());
        throw new GetIssueException("Issue not available");
    }

    MutableIssue issue = issueManager.getIssueObject(issueIdLong);
    ApplicationUser user = PermissionManager.getLoggedUser();
    PermissionManager.checkPermissionWithUser(user, issue, Permissions.EDIT_ISSUE);

    if (issue == null)
        throw new GetIssueException("Issue not available");

    DefaultCustomFieldManager cfManager = (DefaultCustomFieldManager) ComponentAccessor.getCustomFieldManager();
    CustomField cf = cfManager.getCustomFieldObjectByName(JiraConstants.OSLC_CUSTOM_FIELD_NAME);

    if (cf == null) {
        throw new GetIssueException(
                "Custom field (" + JiraConstants.OSLC_CUSTOM_FIELD_NAME + ") not available");
    }

    // prepare GSON
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();

    // get all application links which are already saved in custom field
    String appLinks = (String) cf.getValue(issue);
    AppLinksRepository appLinkList = new AppLinksRepository();

    if (appLinks == null) {
        return false;
    } else if (appLinks == "") {
        return true;
    }

    try {
        appLinkList = gson.fromJson(appLinks, AppLinksRepository.class);
    } catch (com.google.gson.JsonSyntaxException e) {
        logger.error(CURRENT_CLASS + "." + currentMethod + "Exception: " + e.getMessage());
    }

    if (appLinkList == null || URItoRemove == null) {
        return false;
    }

    if (appLinkList.removeAppLink(URItoRemove)) {
        String updatedAppLinks = "";
        if (appLinkList.GetAllAppLinks().size() == 0) {
            updatedAppLinks = "";
        } else {
            updatedAppLinks = gson.toJson(appLinkList);
        }

        if (updatedAppLinks != null) {
            cf.createValue(issue, updatedAppLinks);
            return true;
        }
    }

    return false;

}