Example usage for com.google.common.net MediaType PLAIN_TEXT_UTF_8

List of usage examples for com.google.common.net MediaType PLAIN_TEXT_UTF_8

Introduction

In this page you can find the example usage for com.google.common.net MediaType PLAIN_TEXT_UTF_8.

Prototype

MediaType PLAIN_TEXT_UTF_8

To view the source code for com.google.common.net MediaType PLAIN_TEXT_UTF_8.

Click Source Link

Usage

From source file:com.mastfrog.acteur.ActeurFactory.java

public Acteur parametersMayNotBeCombined(final String... names) {
    @Description("Requires that parameters not appear together in the URL")
    class RequireParametersNotBeCombined extends Acteur {

        @Override// www  . j  a  v  a  2s. c  o  m
        public com.mastfrog.acteur.State getState() {
            HttpEvent event = deps.getInstance(HttpEvent.class);
            String first = null;
            for (String nm : names) {
                String val = event.getParameter(nm);
                if (val != null) {
                    if (first == null) {
                        first = nm;
                    } else {
                        add(Headers.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.withCharset(charset));
                        return new Acteur.RespondWith(Err.badRequest(
                                "Parameters may not contain both '" + first + "' and '" + nm + "'\n"));
                    }
                }
            }
            return new Acteur.ConsumedState();
        }

        @Override
        public String toString() {
            return "Parameters may not be combined: " + Strings.toString(Arrays.asList(names));
        }

        @Override
        public void describeYourself(Map<String, Object> into) {
            into.put("requiredParameters", names);
        }
    }
    return new RequireParametersNotBeCombined();
}

From source file:com.linecorp.armeria.server.thrift.THttpService.java

@Override
protected void doPost(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) {

    final SerializationFormat serializationFormat = validateRequestAndDetermineSerializationFormat(req, res);

    if (serializationFormat == null) {
        return;/*  w  w  w. ja  v a  2 s .  c o m*/
    }

    ctx.requestLogBuilder().serializationFormat(serializationFormat);
    req.aggregate().handle(voidFunction((aReq, cause) -> {
        if (cause != null) {
            res.respond(HttpStatus.INTERNAL_SERVER_ERROR, MediaType.PLAIN_TEXT_UTF_8,
                    Throwables.getStackTraceAsString(cause));
            return;
        }

        decodeAndInvoke(ctx, aReq, serializationFormat, res);
    })).exceptionally(CompletionActions::log);
}

From source file:com.linecorp.armeria.server.thrift.THttpService.java

private SerializationFormat validateRequestAndDetermineSerializationFormat(HttpRequest req,
        HttpResponseWriter res) {/*ww  w.j  a v a  2 s  .  co m*/

    final HttpHeaders headers = req.headers();
    final SerializationFormat serializationFormat;
    final CharSequence contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
    if (contentType != null) {
        serializationFormat = SerializationFormat.fromMediaType(contentType.toString())
                .orElse(defaultSerializationFormat);
        if (!allowedSerializationFormats.contains(serializationFormat)) {
            res.respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                    THRIFT_PROTOCOL_NOT_SUPPORTED);
            return null;
        }
    } else {
        serializationFormat = defaultSerializationFormat;
    }

    final CharSequence accept = headers.get(HttpHeaderNames.ACCEPT);
    if (accept != null) {
        // If accept header is present, make sure it is sane. Currently, we do not support accept
        // headers with a different format than the content type header.
        SerializationFormat outputSerializationFormat = SerializationFormat.fromMediaType(accept.toString())
                .orElse(serializationFormat);
        if (outputSerializationFormat != serializationFormat) {
            res.respond(HttpStatus.NOT_ACCEPTABLE, MediaType.PLAIN_TEXT_UTF_8,
                    ACCEPT_THRIFT_PROTOCOL_MUST_MATCH_CONTENT_TYPE);
            return null;
        }
    }

    return serializationFormat;
}

From source file:com.linecorp.armeria.server.thrift.THttpService.java

private void decodeAndInvoke(ServiceRequestContext ctx, AggregatedHttpMessage req,
        SerializationFormat serializationFormat, HttpResponseWriter res) {

    final TProtocol inProto = FORMAT_TO_THREAD_LOCAL_INPUT_PROTOCOL.get(serializationFormat).get();
    inProto.reset();/*from www. j a  v  a  2s  .  co  m*/
    final TMemoryInputTransport inTransport = (TMemoryInputTransport) inProto.getTransport();
    final HttpData content = req.content();
    inTransport.reset(content.array(), content.offset(), content.length());

    final TMessage header;
    final int seqId;
    final ThriftFunction f;
    final TBase<TBase<?, ?>, TFieldIdEnum> args;
    try {
        try {
            header = inProto.readMessageBegin();
        } catch (Exception e) {
            logger.debug("{} Failed to decode Thrift header:", ctx, e);
            res.respond(HttpStatus.BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8,
                    "Failed to decode Thrift header: " + Throwables.getStackTraceAsString(e));
            return;
        }

        seqId = header.seqid;

        final byte typeValue = header.type;
        final int colonIdx = header.name.indexOf(':');
        final String serviceName;
        final String methodName;
        if (colonIdx < 0) {
            serviceName = "";
            methodName = header.name;
        } else {
            serviceName = header.name.substring(0, colonIdx);
            methodName = header.name.substring(colonIdx + 1);
        }

        // Basic sanity check. We usually should never fail here.
        if (typeValue != TMessageType.CALL && typeValue != TMessageType.ONEWAY) {
            final TApplicationException cause = new TApplicationException(
                    TApplicationException.INVALID_MESSAGE_TYPE,
                    "unexpected TMessageType: " + typeString(typeValue));

            respond(serializationFormat, seqId, header.name, cause, res);
            return;
        }

        // Ensure that such a method exists.
        final ThriftServiceEntry entry = entries().get(serviceName);
        f = entry != null ? entry.metadata.function(methodName) : null;
        if (f == null) {
            final TApplicationException cause = new TApplicationException(TApplicationException.UNKNOWN_METHOD,
                    "unknown method: " + header.name);

            respond(serializationFormat, seqId, methodName, cause, res);
            return;
        }

        // Decode the invocation parameters.
        try {
            if (f.isAsync()) {
                AsyncProcessFunction<Object, TBase<TBase<?, ?>, TFieldIdEnum>, Object> asyncFunc = f
                        .asyncFunc();

                args = asyncFunc.getEmptyArgsInstance();
                args.read(inProto);
                inProto.readMessageEnd();
            } else {
                ProcessFunction<Object, TBase<TBase<?, ?>, TFieldIdEnum>> syncFunc = f.syncFunc();

                args = syncFunc.getEmptyArgsInstance();
                args.read(inProto);
                inProto.readMessageEnd();
            }
        } catch (Exception e) {
            // Failed to decode the invocation parameters.
            logger.debug("{} Failed to decode Thrift arguments:", ctx, e);

            final TApplicationException cause = new TApplicationException(TApplicationException.PROTOCOL_ERROR,
                    "failed to decode arguments: " + e);

            respond(serializationFormat, seqId, methodName, cause, res);
            return;
        }
    } finally {
        inTransport.clear();
    }

    invoke(ctx, serializationFormat, seqId, header.name, f, args, res);
}

From source file:org.haiku.haikudepotserver.job.LocalJobServiceImpl.java

@Override
public String deriveDataFilename(String jobDataGuid) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(jobDataGuid));

    String descriptor = "jobdata";
    String extension = "dat";

    Optional<JobData> jobDataOptional = tryGetData(jobDataGuid);

    if (jobDataOptional.isPresent()) {

        JobData jobData = jobDataOptional.get();
        Optional<? extends JobSnapshot> jobOptional = tryGetJobForData(jobDataGuid);

        if (jobOptional.isPresent()) {
            descriptor = jobOptional.get().getJobTypeCode();
        }//from   ww  w  .  j a  v  a  2  s  .  c o  m

        // TODO; get the extensions from a file etc...
        if (!Strings.isNullOrEmpty(jobData.getMediaTypeCode())) {
            if (jobData.getMediaTypeCode().startsWith(MediaType.CSV_UTF_8.withoutParameters().toString())) {
                extension = "csv";
            }

            if (jobData.getMediaTypeCode().equals(MediaType.ZIP.withoutParameters().toString())) {
                extension = "zip";
            }

            if (jobData.getMediaTypeCode().equals(MediaType.TAR.withoutParameters().toString())) {
                extension = "tgz";
            }

            if (jobData.getMediaTypeCode().equals(MediaType.PLAIN_TEXT_UTF_8.withoutParameters().toString())) {
                extension = "txt";
            }
        }
    }

    return String.format("hds_%s_%s_%s.%s", descriptor,
            DateTimeHelper.create14DigitDateTimeFormat().format(Instant.now()), jobDataGuid.substring(0, 4),
            extension);
}