第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何調(diào)試夸庫斯/小黑麥客戶端請求

如何調(diào)試夸庫斯/小黑麥客戶端請求

慕虎7371278 2022-09-22 20:07:26
我有一個看起來像這樣的請求:@Path("/v1")@RegisterRestClient@Produces("application/json")public interface VaultClient {    @POST    @Path("/auth/jwt/login")    @Consumes("application/json")    String getVaultToken(LoginPayload loginPayload);}登錄支付加載它只是一個簡單的POJO:public class LoginPayload {    private String jwt;    final private String role = "some-service";    public void setJwt(String _jwt) {        this.jwt = _jwt;    }}當(dāng)我嘗試通過服務(wù)調(diào)用此終結(jié)點時:public String getServiceJwt() {    String loginJwt = getLoginJwt();    LoginPayload loginPayload = new LoginPayload();    loginPayload.setJwt(loginJwt);    try {        System.out.println(loginPayload.toString());        String tokenResponse = vaultClient.getVaultToken(loginPayload);        System.out.println("##################");        System.out.println(tokenResponse);    } catch (Exception e) {        System.out.println(e);    }    return vaultJwt;}我得到一個400:javax.ws.rs.WebApplicationException: Unknown error, status code 400java.lang.RuntimeException: method call not supported但是,我不知道如何對此進(jìn)行故障排除。我可以通過PostMan /失眠執(zhí)行相同的請求,它返回的響應(yīng)很好。有沒有辦法讓我更好地內(nèi)省出的響應(yīng)是什么樣子的?也許它沒有正確地將POJO序列化為JSON?我無從得知。更新 我在此請求的另一端拋出了一個節(jié)點服務(wù)器,并注銷了正文。它是空的。因此,有些東西不是序列化POJO并將其與POST請求一起發(fā)送。不過,這不是一個很好的調(diào)試故事。有沒有辦法在不記錄此請求的另一端的情況下獲得此內(nèi)容?另外,為什么POJO不序列化?它非常密切地遵循所有文檔。
查看完整描述

1 回答

?
心有法竹

TA貢獻(xiàn)1866條經(jīng)驗 獲得超5個贊

我使用過濾器和攔截器作為異常處理程序來解決此問題:


用于打印日志的過濾器:


import lombok.extern.java.Log;

import org.glassfish.jersey.message.MessageUtils;


import javax.ws.rs.WebApplicationException;

import javax.ws.rs.client.ClientRequestContext;

import javax.ws.rs.client.ClientRequestFilter;

import javax.ws.rs.client.ClientResponseContext;

import javax.ws.rs.client.ClientResponseFilter;

import javax.ws.rs.container.ContainerRequestContext;

import javax.ws.rs.container.ContainerRequestFilter;

import javax.ws.rs.container.ContainerResponseContext;

import javax.ws.rs.container.ContainerResponseFilter;

import javax.ws.rs.core.MultivaluedMap;

import javax.ws.rs.ext.WriterInterceptor;

import javax.ws.rs.ext.WriterInterceptorContext;

import java.io.BufferedInputStream;

import java.io.ByteArrayOutputStream;

import java.io.FilterOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URI;

import java.nio.charset.Charset;

import java.util.Comparator;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.TreeSet;

import java.util.concurrent.atomic.AtomicLong;


/**

 * Based on org.glassfish.jersey.filter.LoggingFilter

 */

@Log

public class LoggingFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter,

                                      ClientResponseFilter, WriterInterceptor {


    private static final String NOTIFICATION_PREFIX = "* ";


    private static final String REQUEST_PREFIX = "> ";


    private static final String RESPONSE_PREFIX = "< ";


    private static final String ENTITY_LOGGER_PROPERTY = LoggingFilter.class.getName() + ".entityLogger";


    private static final String LOGGING_ID_PROPERTY = LoggingFilter.class.getName() + ".id";


    private static final Comparator<Map.Entry<String, List<String>>> COMPARATOR = (o1, o2) -> o1.getKey().compareToIgnoreCase(o2.getKey());


    private static final int DEFAULT_MAX_ENTITY_SIZE = 8 * 1024;


    private final AtomicLong _id = new AtomicLong(0);


    private final int maxEntitySize;


    public LoggingFilter() {


        this.maxEntitySize = LoggingFilter.DEFAULT_MAX_ENTITY_SIZE;

    }



    private void log(final StringBuilder b) {


        LoggingFilter.log.info(b.toString());

    }


    private StringBuilder prefixId(final StringBuilder b, final long id) {


        b.append(id).append(" ");

        return b;

    }


    private void printRequestLine(final StringBuilder b, final String note, final long id, final String method, final URI uri) {


        this.prefixId(b, id).append(LoggingFilter.NOTIFICATION_PREFIX)

                .append(note)

                .append(" on thread ").append(Thread.currentThread().getName())

                .append("\n");

        this.prefixId(b, id).append(LoggingFilter.REQUEST_PREFIX).append(method).append(" ")

                .append(uri.toASCIIString()).append("\n");

    }


    private void printResponseLine(final StringBuilder b, final String note, final long id, final int status) {


        this.prefixId(b, id).append(LoggingFilter.NOTIFICATION_PREFIX)

                .append(note)

                .append(" on thread ").append(Thread.currentThread().getName()).append("\n");

        this.prefixId(b, id).append(LoggingFilter.RESPONSE_PREFIX)

                .append(status)

                .append("\n");

    }


    private void printPrefixedHeaders(final StringBuilder b,

                                      final long id,

                                      final String prefix,

                                      final MultivaluedMap<String, String> headers) {


        for (final Map.Entry<String, List<String>> headerEntry : this.getSortedHeaders(headers.entrySet())) {

            final List<?> val = headerEntry.getValue();

            final String header = headerEntry.getKey();


            if(val.size() == 1) {

                this.prefixId(b, id).append(prefix).append(header).append(": ").append(val.get(0)).append("\n");

            }

            else {

                final StringBuilder sb = new StringBuilder();

                boolean add = false;

                for (final Object s : val) {

                    if(add) {

                        sb.append(',');

                    }

                    add = true;

                    sb.append(s);

                }

                this.prefixId(b, id).append(prefix).append(header).append(": ").append(sb.toString()).append("\n");

            }

        }

    }


    private Set<Map.Entry<String, List<String>>> getSortedHeaders(final Set<Map.Entry<String, List<String>>> headers) {


        final TreeSet<Map.Entry<String, List<String>>> sortedHeaders = new TreeSet<>(LoggingFilter.COMPARATOR);

        sortedHeaders.addAll(headers);

        return sortedHeaders;

    }


    private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset) throws IOException {


        if(!stream.markSupported()) {

            stream = new BufferedInputStream(stream);

        }

        stream.mark(this.maxEntitySize + 1);

        final byte[] entity = new byte[this.maxEntitySize + 1];

        final int entitySize = stream.read(entity);

        b.append(new String(entity, 0, Math.min(entitySize, this.maxEntitySize), charset));

        if(entitySize > this.maxEntitySize) {

            b.append("...more...");

        }

        b.append('\n');

        stream.reset();

        return stream;

    }


    @Override

    public void filter(final ClientRequestContext context) throws IOException {


        final long id = this._id.incrementAndGet();

        context.setProperty(LoggingFilter.LOGGING_ID_PROPERTY, id);


        final StringBuilder b = new StringBuilder();


        this.printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri());

        this.printPrefixedHeaders(b, id, LoggingFilter.REQUEST_PREFIX, context.getStringHeaders());


        if(context.hasEntity()) {

            final OutputStream stream = new LoggingFilter.LoggingStream(b, context.getEntityStream());

            context.setEntityStream(stream);

            context.setProperty(LoggingFilter.ENTITY_LOGGER_PROPERTY, stream);

            // not calling log(b) here - it will be called by the interceptor

        }

        else {

            this.log(b);

        }

    }


    @Override

    public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext)

    throws IOException {


        final Object requestId = requestContext.getProperty(LoggingFilter.LOGGING_ID_PROPERTY);

        final long id = requestId != null ? (Long) requestId : this._id.incrementAndGet();


        final StringBuilder b = new StringBuilder();


        this.printResponseLine(b, "Client response received", id, responseContext.getStatus());

        this.printPrefixedHeaders(b, id, LoggingFilter.RESPONSE_PREFIX, responseContext.getHeaders());


        if(responseContext.hasEntity()) {

            responseContext.setEntityStream(this.logInboundEntity(b, responseContext.getEntityStream(),

                    MessageUtils.getCharset(responseContext.getMediaType())));

        }


        this.log(b);

    }


    @Override

    public void filter(final ContainerRequestContext context) throws IOException {


        final long id = this._id.incrementAndGet();

        context.setProperty(LoggingFilter.LOGGING_ID_PROPERTY, id);


        final StringBuilder b = new StringBuilder();


        this.printRequestLine(b, "Server has received a request", id, context.getMethod(), context.getUriInfo().getRequestUri());

        this.printPrefixedHeaders(b, id, LoggingFilter.REQUEST_PREFIX, context.getHeaders());


        if(context.hasEntity()) {

            context.setEntityStream(

                    this.logInboundEntity(b, context.getEntityStream(), MessageUtils.getCharset(context.getMediaType())));

        }


        this.log(b);

    }


    @Override

    public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)

    throws IOException {


        final Object requestId = requestContext.getProperty(LoggingFilter.LOGGING_ID_PROPERTY);

        final long id = requestId != null ? (Long) requestId : this._id.incrementAndGet();


        final StringBuilder b = new StringBuilder();


        this.printResponseLine(b, "Server responded with a response", id, responseContext.getStatus());

        this.printPrefixedHeaders(b, id, LoggingFilter.RESPONSE_PREFIX, responseContext.getStringHeaders());


        if(responseContext.hasEntity()) {

            final OutputStream stream = new LoggingFilter.LoggingStream(b, responseContext.getEntityStream());

            responseContext.setEntityStream(stream);

            requestContext.setProperty(LoggingFilter.ENTITY_LOGGER_PROPERTY, stream);

            // not calling log(b) here - it will be called by the interceptor

        }

        else {

            this.log(b);

        }

    }


    @Override

    public void aroundWriteTo(final WriterInterceptorContext writerInterceptorContext)

    throws IOException, WebApplicationException {


        final LoggingFilter.LoggingStream stream = (LoggingFilter.LoggingStream) writerInterceptorContext.getProperty(LoggingFilter.ENTITY_LOGGER_PROPERTY);

        writerInterceptorContext.proceed();

        if(stream != null) {

            this.log(stream.getStringBuilder(MessageUtils.getCharset(writerInterceptorContext.getMediaType())));

        }

    }


    private class LoggingStream extends FilterOutputStream {


        private final StringBuilder b;


        private final ByteArrayOutputStream baos = new ByteArrayOutputStream();


        LoggingStream(final StringBuilder b, final OutputStream inner) {


            super(inner);


            this.b = b;

        }


        StringBuilder getStringBuilder(final Charset charset) {

            // write entity to the builder

            final byte[] entity = this.baos.toByteArray();


            this.b.append(new String(entity, 0, Math.min(entity.length, LoggingFilter.this.maxEntitySize), charset));

            if(entity.length > LoggingFilter.this.maxEntitySize) {

                this.b.append("...more...");

            }

            this.b.append('\n');


            return this.b;

        }


        @Override

        public void write(final int i) throws IOException {


            if(this.baos.size() <= LoggingFilter.this.maxEntitySize) {

                this.baos.write(i);

            }

            this.out.write(i);

        }


    }


}


在其余客戶端界面中使用篩選器:


@Path("/")

@Produces(MediaType.APPLICATION_JSON)

@Consumes(MediaType.APPLICATION_JSON)

@RegisterRestClient

@RegisterProvider(LoggingFilter.class)

public interface Api {


    @GET

    @Path("/foo/bar")

    FooBar getFoorBar();

現(xiàn)在,請求和響應(yīng)負(fù)載將打印在日志中。


之后,用于處理異常的偵聽器:


限定 符:


@InterceptorBinding

@Target({TYPE, METHOD})

@Retention(RUNTIME)

public @interface ExceptionHandler {


}

攔截 器:


@Interceptor

@ExceptionHandler

public class ExceptionHandlerInterceptor  {


    @AroundInvoke

    public Object processRequest(final InvocationContext invocationContext) {


        try {

            return invocationContext.proceed();


        }

        catch (final WebApplicationException e) {


            final int status = e.getResponse().getStatus();

            final String errorJson = e.getResponse().readEntity(String.class);


            final Jsonb jsonb = JsonbBuilder.create();


            //"ErrorMessageDTO" is waited when a error occurs

            ErrorMessage errorMessage = jsonb.fromJson(errorJson, ErrorMessage.class);


            //isValid method verifies if the conversion was successful

            if(errorMessage.isValid()) {

                return Response

                        .status(status)

                        .entity(errorMessage)

                        .build();

            }


            errorMessage = ErrorMessage

                    .builder()

                    .statusCode(status)

                    .statusMessage(e.getMessage())

                    .success(false)

                    .build();


            return Response

                    .status(status)

                    .entity(errorMessage)

                    .build();

        }

        catch (final Exception e) {


            e.printStackTrace();


            return Response

                    .status(Status.INTERNAL_SERVER_ERROR)

                    .entity(ErrorMessage

                            .builder()

                            .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())

                            .statusMessage(e.getMessage())

                            .success(false)

                            .build())

                    .build();

        }

    }


}

使用攔截器:


@Path("/resource")

@Produces(MediaType.APPLICATION_JSON)

@Consumes(MediaType.APPLICATION_JSON)

@ExceptionHandler

@Traced

@Log

public class ResourceEndpoint {


    @Inject

    @RestClient

    Api api;


    @GET

    @Path("/latest")

    public Response getFooBarLatest() {


        return Response.ok(this.api.getFoorBar()).build();

    }

錯誤消息豆:


@RegisterForReflection

@Getter

@Setter

@AllArgsConstructor

@NoArgsConstructor

@Data

@Builder

public class ErrorMessage  {


    @JsonbProperty("status_message")

    private String statusMessage;


    @JsonbProperty("status_code")

    private Integer statusCode;


    @JsonbProperty("success")

    private boolean success = true;


    @JsonbTransient

    public boolean isValid() {


        return this.statusMessage != null && !this.statusMessage.isEmpty() && this.statusCode != null;

    }


}

PS:使用龍目島!


查看完整回答
反對 回復(fù) 2022-09-22
  • 1 回答
  • 0 關(guān)注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號