Java Code Examples for com.google.common.net.MediaType#JSON_UTF_8

The following examples show how to use com.google.common.net.MediaType#JSON_UTF_8 . 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: DefaultErrorHandler.java    From purplejs with Apache License 2.0 6 votes vote down vote up
private MediaType findRenderType( final List<MediaType> accept )
{
    for ( final MediaType type : accept )
    {
        if ( isHtmlType( type ) )
        {
            return MediaType.HTML_UTF_8;
        }

        if ( isJsonType( type ) )
        {
            return MediaType.JSON_UTF_8;
        }
    }

    return MediaType.JSON_UTF_8;
}
 
Example 2
Source File: HttpSessionManager.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private CommonResponse createSession(String username, Set<String> roles, boolean ldap)
        throws Exception {
    String sessionId = new BigInteger(130, secureRandom).toString(32);
    ImmutableSession session = ImmutableSession.builder()
            .caseAmbiguousUsername(username)
            .ldap(ldap)
            .roles(roles)
            .lastRequest(clock.currentTimeMillis())
            .build();
    sessionMap.put(sessionId, session);

    String layoutJson = layoutService
            .getLayoutJson(session.createAuthentication(central, configRepository));
    CommonResponse response = new CommonResponse(OK, MediaType.JSON_UTF_8, layoutJson);
    Cookie cookie =
            new DefaultCookie(configRepository.getWebConfig().sessionCookieName(), sessionId);
    cookie.setHttpOnly(true);
    cookie.setPath("/");
    response.setHeader(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
    purgeExpiredSessions();

    auditSuccessfulLogin(username);
    return response;
}
 
Example 3
Source File: TraceDetailHttpService.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public CommonResponse handleRequest(CommonRequest request, Authentication authentication)
        throws Exception {
    String path = request.getPath();
    String traceComponent = path.substring(path.lastIndexOf('/') + 1);
    List<String> agentIds = request.getParameters("agent-id");
    checkState(!agentIds.isEmpty(), "Missing agent id in query string: %s", request.getUri());
    String agentId = agentIds.get(0);
    List<String> traceIds = request.getParameters("trace-id");
    checkState(!traceIds.isEmpty(), "Missing trace id in query string: %s", request.getUri());
    String traceId = traceIds.get(0);
    // check-live-traces is an optimization so the central collector only has to check with
    // remote agents when necessary
    List<String> checkLiveTracesParams = request.getParameters("check-live-traces");
    boolean checkLiveTraces = !checkLiveTracesParams.isEmpty()
            && Boolean.parseBoolean(checkLiveTracesParams.get(0));
    logger.debug("handleRequest(): traceComponent={}, agentId={}, traceId={},"
            + " checkLiveTraces={}", traceComponent, agentId, traceId, checkLiveTraces);

    ChunkSource detail =
            getDetailChunkSource(traceComponent, agentId, traceId, checkLiveTraces);
    if (detail == null) {
        return new CommonResponse(NOT_FOUND);
    }
    return new CommonResponse(OK, MediaType.JSON_UTF_8, detail);
}
 
Example 4
Source File: JAXBWriter.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
public Entry<String, String> serializeForType(HttpServletRequest request, Response resp) {
    String format = getStringParameter(request, "f", "xml");
    String jsonpCallback = request.getParameter("callback");
    boolean json = "json".equals(format);
    boolean jsonp = "jsonp".equals(format) && jsonpCallback != null;
    Marshaller marshaller;
    MediaType type;

    if (json) {
        marshaller = createJsonMarshaller();
        type = MediaType.JSON_UTF_8;
    } else if (jsonp) {
        marshaller = createJsonMarshaller();
        type = MediaType.JAVASCRIPT_UTF_8;
    } else {
        marshaller = createXmlMarshaller();
        type = MediaType.XML_UTF_8;
    }

    StringWriter writer = new StringWriter();
    try {
        if (jsonp) {
            writer.append(jsonpCallback).append('(');
        }
        marshaller.marshal(new ObjectFactory().createSubsonicResponse(resp), writer);
        if (jsonp) {
            writer.append(");");
        }
    } catch (JAXBException x) {
        LOG.error("Failed to marshal JAXB", x);
        throw new RuntimeException(x);
    }

    return Pair.of(type.toString(), writer.toString());
}
 
Example 5
Source File: AdminJsonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@RequiresNonNull("httpServer")
private CommonResponse onSuccessfulEmbeddedWebUpdate(EmbeddedWebConfig config)
        throws Exception {
    boolean closeCurrentChannelAfterPortChange = false;
    boolean portChangeFailed = false;
    if (config.port() != checkNotNull(httpServer.getPort())) {
        try {
            httpServer.changePort(config.port());
            closeCurrentChannelAfterPortChange = true;
        } catch (PortChangeFailedException e) {
            logger.error(e.getMessage(), e);
            portChangeFailed = true;
        }
    }
    if (config.https() != httpServer.getHttps() && !portChangeFailed) {
        // only change protocol if port change did not fail, otherwise confusing to display
        // message that port change failed while at the same time redirecting user to HTTP/S
        httpServer.changeProtocol(config.https());
        closeCurrentChannelAfterPortChange = true;
    }
    String responseText = getEmbeddedWebConfig(portChangeFailed);
    CommonResponse response = new CommonResponse(OK, MediaType.JSON_UTF_8, responseText);
    if (closeCurrentChannelAfterPortChange) {
        response.setCloseConnectionAfterPortChange();
    }
    return response;
}
 
Example 6
Source File: CommonHandler.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private CommonResponse handleNotAuthorized(CommonRequest request,
        Authentication authentication) throws Exception {
    if (authentication.anonymous()) {
        if (httpSessionManager.getSessionId(request) != null) {
            return new CommonResponse(UNAUTHORIZED, MediaType.JSON_UTF_8,
                    "{\"timedOut\":true}");
        } else {
            return new CommonResponse(UNAUTHORIZED);
        }
    } else {
        return new CommonResponse(FORBIDDEN);
    }
}
 
Example 7
Source File: CommonHandler.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static CommonResponse buildJsonResponse(@Nullable Object responseObject) {
    if (responseObject == null) {
        return new CommonResponse(OK, MediaType.JSON_UTF_8, "");
    } else if (responseObject instanceof CommonResponse) {
        return (CommonResponse) responseObject;
    } else if (responseObject instanceof String) {
        return new CommonResponse(OK, MediaType.JSON_UTF_8, (String) responseObject);
    } else {
        logger.warn("unexpected type of json service response: {}",
                responseObject.getClass().getName());
        return new CommonResponse(INTERNAL_SERVER_ERROR);
    }
}
 
Example 8
Source File: CommonHandler.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static CommonResponse newHttpResponseWithMessage(HttpResponseStatus status,
        @Nullable String message) throws IOException {
    // this is an "expected" exception, no need to send back stack trace
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeStringField("message", message);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return new CommonResponse(status, MediaType.JSON_UTF_8, sb.toString());
}
 
Example 9
Source File: CommonHandler.java    From glowroot with Apache License 2.0 4 votes vote down vote up
static CommonResponse newHttpResponseWithStackTrace(Exception e,
        HttpResponseStatus status, @Nullable String simplifiedMessage) throws IOException {
    return new CommonResponse(status, MediaType.JSON_UTF_8,
            getHttpResponseWithStackTrace(e, simplifiedMessage));
}
 
Example 10
Source File: HttpSessionManager.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private static CommonResponse buildIncorrectLoginResponse() {
    return new CommonResponse(OK, MediaType.JSON_UTF_8, "{\"incorrectLogin\":true}");
}