Search in sources :

Example 86 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class MetadataHttpHandler method getValidatedSearchRequest.

// TODO (CDAP-14946): Find a better way to determine allowed combinations of search parameters
private SearchRequest getValidatedSearchRequest(@Nullable String scope, @Nullable List<String> namespaces, @Nullable String searchQuery, @Nullable List<String> targets, @Nullable String sort, int offset, int limit, @Nullable Integer numCursors, boolean cursorRequested, @Nullable String cursor, boolean showHidden, @Nullable String entityScope) throws BadRequestException {
    try {
        SearchRequest.Builder builder = SearchRequest.of(searchQuery == null ? "*" : searchQuery);
        if (scope != null) {
            builder.setScope(validateScope(scope));
        }
        if (EntityScope.SYSTEM == validateEntityScope(entityScope)) {
            builder.addNamespace(entityScope.toLowerCase());
        } else if (namespaces != null) {
            for (String namespace : namespaces) {
                builder.addNamespace(namespace);
            }
        }
        if (targets != null) {
            targets.forEach(builder::addType);
        }
        if (sort != null) {
            Sorting sorting;
            try {
                sorting = Sorting.of(URLDecoder.decode(sort, StandardCharsets.UTF_8.name()));
            } catch (UnsupportedEncodingException e) {
                // this cannot happen because UTF_8 is always supported
                throw new IllegalStateException(e);
            }
            if (!MetadataConstants.ENTITY_NAME_KEY.equalsIgnoreCase(sorting.getKey()) && !MetadataConstants.CREATION_TIME_KEY.equalsIgnoreCase(sorting.getKey())) {
                throw new IllegalArgumentException("Sorting is only supported on fields: " + MetadataConstants.ENTITY_NAME_KEY + ", " + MetadataConstants.CREATION_TIME_KEY);
            }
            builder.setSorting(sorting);
        }
        builder.setOffset(offset);
        builder.setLimit(limit);
        if (cursorRequested || (numCursors != null && numCursors > 0)) {
            if (sort == null) {
                throw new IllegalArgumentException("Specify a sort order when requesting a cursor");
            }
            builder.setCursorRequested(true);
        }
        if (cursor != null) {
            if (sort == null) {
                throw new IllegalArgumentException("Specify a sort order when passing in a cursor");
            }
            builder.setCursor(cursor);
        }
        builder.setShowHidden(showHidden);
        SearchRequest request = builder.build();
        LOG.trace("Received search request {}", request);
        return request;
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage(), e);
    }
}
Also used : SearchRequest(io.cdap.cdap.spi.metadata.SearchRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BadRequestException(io.cdap.cdap.common.BadRequestException) Sorting(io.cdap.cdap.spi.metadata.Sorting)

Example 87 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class MetadataHttpHandler method readTags.

private Set<String> readTags(FullHttpRequest request) throws BadRequestException {
    ByteBuf content = request.content();
    if (!content.isReadable()) {
        throw new BadRequestException("Unable to read a list of tags from the request.");
    }
    Set<String> toReturn;
    try (Reader reader = new InputStreamReader(new ByteBufInputStream(content), StandardCharsets.UTF_8)) {
        toReturn = GSON.fromJson(reader, SET_STRING_TYPE);
    } catch (IOException e) {
        throw new BadRequestException("Unable to read a list of tags from the request.", e);
    }
    if (toReturn == null) {
        throw new BadRequestException("Null tags were read from the request.");
    }
    return toReturn;
}
Also used : InputStreamReader(java.io.InputStreamReader) BadRequestException(io.cdap.cdap.common.BadRequestException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf)

Example 88 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class TetheringServerHandler method connectControlChannel.

/**
 * Sends control commands to the client.
 */
@GET
@Path("/tethering/controlchannels/{peer}")
public void connectControlChannel(FullHttpRequest request, HttpResponder responder, @PathParam("peer") String peer, @QueryParam("messageId") String messageId) throws IOException, NotImplementedException, PeerNotFoundException, ForbiddenException, BadRequestException {
    checkTetheringServerEnabled();
    store.updatePeerTimestamp(peer);
    TetheringStatus tetheringStatus = store.getPeer(peer).getTetheringStatus();
    if (tetheringStatus == TetheringStatus.PENDING) {
        throw new PeerNotFoundException(String.format("Peer %s not found", peer));
    } else if (tetheringStatus == TetheringStatus.REJECTED) {
        responder.sendStatus(HttpResponseStatus.FORBIDDEN);
        throw new ForbiddenException(String.format("Peer %s is not authorized", peer));
    }
    List<TetheringControlResponse> controlResponses = new ArrayList<>();
    MessageFetcher fetcher = messagingContext.getMessageFetcher();
    TopicId topic = new TopicId(NamespaceId.SYSTEM.getNamespace(), topicPrefix + peer);
    String lastMessageId = messageId;
    try (CloseableIterator<Message> iterator = fetcher.fetch(topic.getNamespace(), topic.getTopic(), 1, messageId)) {
        while (iterator.hasNext()) {
            Message message = iterator.next();
            TetheringControlMessage controlMessage = GSON.fromJson(message.getPayloadAsString(StandardCharsets.UTF_8), TetheringControlMessage.class);
            lastMessageId = message.getId();
            controlResponses.add(new TetheringControlResponse(lastMessageId, controlMessage));
        }
    } catch (TopicNotFoundException e) {
        LOG.warn("Received control connection from peer {} that's not tethered", peer);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(String.format("Invalid message id %s", messageId));
    }
    if (controlResponses.isEmpty()) {
        controlResponses.add(new TetheringControlResponse(lastMessageId, new TetheringControlMessage(TetheringControlMessage.Type.KEEPALIVE)));
    }
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(controlResponses.toArray(new TetheringControlResponse[0]), TetheringControlResponse[].class));
}
Also used : ForbiddenException(io.cdap.cdap.common.ForbiddenException) MessageFetcher(io.cdap.cdap.api.messaging.MessageFetcher) Message(io.cdap.cdap.api.messaging.Message) TopicNotFoundException(io.cdap.cdap.api.messaging.TopicNotFoundException) ArrayList(java.util.ArrayList) BadRequestException(io.cdap.cdap.common.BadRequestException) TopicId(io.cdap.cdap.proto.id.TopicId) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 89 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class LoadPreferencesCommand method perform.

@SuppressWarnings("unchecked")
@Override
public void perform(Arguments arguments, PrintStream printStream) throws Exception {
    String contentType = arguments.getOptional(ArgumentName.CONTENT_TYPE.toString(), "");
    File file = new File(arguments.get(ArgumentName.LOCAL_FILE_PATH.toString()));
    if (!file.isFile()) {
        throw new IllegalArgumentException("Not a file: " + file);
    }
    Map<String, String> args = Maps.newHashMap();
    try (FileReader reader = new FileReader(file)) {
        if (contentType.equals("json")) {
            args = GSON.fromJson(reader, MAP_STRING_STRING_TYPE);
        } else {
            throw new IllegalArgumentException("Unsupported file format. Only JSON format is supported");
        }
    } catch (JsonSyntaxException e) {
        throw new BadRequestException(String.format("JSON syntax in file is invalid. Support only for string-to-string map. %s", e.getMessage()));
    }
    setPreferences(arguments, printStream, args);
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) BadRequestException(io.cdap.cdap.common.BadRequestException) FileReader(java.io.FileReader) File(java.io.File)

Example 90 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class ProgramLifecycleService method findRuntimeInfo.

private Map<RunId, ProgramRuntimeService.RuntimeInfo> findRuntimeInfo(ProgramId programId, @Nullable String runId) throws BadRequestException {
    if (runId != null) {
        RunId run;
        try {
            run = RunIds.fromString(runId);
        } catch (IllegalArgumentException e) {
            throw new BadRequestException("Error parsing run-id.", e);
        }
        ProgramRuntimeService.RuntimeInfo runtimeInfo = runtimeService.lookup(programId, run);
        return runtimeInfo == null ? Collections.emptyMap() : Collections.singletonMap(run, runtimeInfo);
    }
    return new HashMap<>(runtimeService.list(programId));
}
Also used : HashMap(java.util.HashMap) BadRequestException(io.cdap.cdap.common.BadRequestException) RuntimeInfo(io.cdap.cdap.app.runtime.ProgramRuntimeService.RuntimeInfo) RunId(org.apache.twill.api.RunId) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ProgramRuntimeService(io.cdap.cdap.app.runtime.ProgramRuntimeService)

Aggregations

BadRequestException (io.cdap.cdap.common.BadRequestException)188 Path (javax.ws.rs.Path)68 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)54 IOException (java.io.IOException)46 JsonSyntaxException (com.google.gson.JsonSyntaxException)44 NotFoundException (io.cdap.cdap.common.NotFoundException)42 ApplicationId (io.cdap.cdap.proto.id.ApplicationId)42 POST (javax.ws.rs.POST)42 HttpResponse (io.cdap.common.http.HttpResponse)36 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)34 URL (java.net.URL)34 ProgramType (io.cdap.cdap.proto.ProgramType)30 InputStreamReader (java.io.InputStreamReader)28 Reader (java.io.Reader)28 ArrayList (java.util.ArrayList)28 AuditPolicy (io.cdap.cdap.common.security.AuditPolicy)26 ProgramId (io.cdap.cdap.proto.id.ProgramId)26 ServiceUnavailableException (io.cdap.cdap.common.ServiceUnavailableException)24 GET (javax.ws.rs.GET)24 ProgramRunId (io.cdap.cdap.proto.id.ProgramRunId)22