Search in sources :

Example 6 with Post

use of org.restlet.resource.Post in project open-kilda by telstra.

the class EnableBfdResource method enableBfd.

/**
 * Setting up BFD session.
 *
 * @param json the json from request.
 * @return json response.
 * @throws JsonProcessingException if response can't be wrote to string.
 */
@Post("json")
@Put("json")
public String enableBfd(String json) {
    ISwitchManager switchManager = (ISwitchManager) getContext().getAttributes().get(ISwitchManager.class.getCanonicalName());
    NoviBfdSession request;
    try {
        request = MAPPER.readValue(json, NoviBfdSession.class);
        if (request.getIntervalMs() < CONSTRAINT_INTERVAL_MIN) {
            throw new IllegalArgumentException(String.format("Invalid bfd session interval value: %d < %d", request.getIntervalMs(), CONSTRAINT_INTERVAL_MIN));
        }
        DatapathId datapathIdtarget = DatapathId.of(request.getTarget().getDatapath().toLong());
        IOFSwitch iofSwitch = switchManager.lookupSwitch(datapathIdtarget);
        OFPacketOut outPacket = makeSessionConfigMessage(request, iofSwitch, switchManager);
        if (!iofSwitch.write(outPacket)) {
            throw new IllegalStateException("Failed to set up BFD session");
        }
    } catch (IOException e) {
        logger.error("Message received is not valid BFD Request: {}", json);
        MessageError responseMessage = new MessageError(DEFAULT_CORRELATION_ID, now(), ErrorType.DATA_INVALID.toString(), "Message received is not valid BFD Request", e.getMessage());
        return generateJson(responseMessage);
    } catch (SwitchNotFoundException e) {
        MessageError responseMessage = new MessageError(DEFAULT_CORRELATION_ID, now(), ErrorType.DATA_INVALID.toString(), "Switch not found", e.getMessage());
        return generateJson(responseMessage);
    }
    return generateJson("ok");
}
Also used : IOFSwitch(net.floodlightcontroller.core.IOFSwitch) ISwitchManager(org.openkilda.floodlight.switchmanager.ISwitchManager) MessageError(org.openkilda.messaging.error.MessageError) DatapathId(org.projectfloodlight.openflow.types.DatapathId) IOException(java.io.IOException) SwitchNotFoundException(org.openkilda.floodlight.error.SwitchNotFoundException) NoviBfdSession(org.openkilda.messaging.model.NoviBfdSession) OFPacketOut(org.projectfloodlight.openflow.protocol.OFPacketOut) Post(org.restlet.resource.Post) Put(org.restlet.resource.Put)

Example 7 with Post

use of org.restlet.resource.Post in project open-kilda by telstra.

the class FlowResource method installFlow.

/**
 * Installing flow.
 *
 * @param json the json from request.
 * @return json response.
 * @throws JsonProcessingException if response can't be wrote to string.
 */
@Post("json")
@Put("json")
public String installFlow(String json) throws JsonProcessingException {
    ISwitchManager switchManager = (ISwitchManager) getContext().getAttributes().get(ISwitchManager.class.getCanonicalName());
    Message message;
    try {
        message = MAPPER.readValue(json, Message.class);
    } catch (IOException exception) {
        String messageString = "Received JSON is not valid for TPN";
        logger.error("{}: {}", messageString, json, exception);
        MessageError responseMessage = new MessageError(CorrelationContext.getId(), now(), ErrorType.DATA_INVALID.toString(), messageString, exception.getMessage());
        return MAPPER.writeValueAsString(responseMessage);
    }
    if (!(message instanceof CommandMessage)) {
        String messageString = "Json payload message is not an instance of CommandMessage";
        logger.error("{}: class={}, data={}", messageString, message.getClass().getCanonicalName(), json);
        MessageError responseMessage = new MessageError(CorrelationContext.getId(), now(), ErrorType.DATA_INVALID.toString(), messageString, message.getClass().getCanonicalName());
        return MAPPER.writeValueAsString(responseMessage);
    }
    CommandMessage cmdMessage = (CommandMessage) message;
    CommandData data = cmdMessage.getData();
    if (!(data instanceof BaseInstallFlow)) {
        String messageString = "Json payload data is not an instance of CommandData";
        logger.error("{}: class={}, data={}", messageString, data.getClass().getCanonicalName(), json);
        MessageError responseMessage = new MessageError(CorrelationContext.getId(), now(), ErrorType.DATA_INVALID.toString(), messageString, data.getClass().getCanonicalName());
        return MAPPER.writeValueAsString(responseMessage);
    }
    return MAPPER.writeValueAsString("ok");
}
Also used : ISwitchManager(org.openkilda.floodlight.switchmanager.ISwitchManager) Message(org.openkilda.messaging.Message) CommandMessage(org.openkilda.messaging.command.CommandMessage) MessageError(org.openkilda.messaging.error.MessageError) IOException(java.io.IOException) BaseInstallFlow(org.openkilda.messaging.command.flow.BaseInstallFlow) CommandData(org.openkilda.messaging.command.CommandData) CommandMessage(org.openkilda.messaging.command.CommandMessage) Post(org.restlet.resource.Post) Put(org.restlet.resource.Put)

Example 8 with Post

use of org.restlet.resource.Post in project pinot by linkedin.

the class PinotTableRestletResource method post.

@Override
@Post("json")
public Representation post(Representation entity) {
    AbstractTableConfig config = null;
    try {
        String jsonRequest = entity.getText();
        config = AbstractTableConfig.init(jsonRequest);
        try {
            addTable(config);
        } catch (Exception e) {
            LOGGER.error("Caught exception while adding table", e);
            ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_TABLE_ADD_ERROR, 1L);
            setStatus(Status.SERVER_ERROR_INTERNAL);
            return new StringRepresentation("Failed: " + e.getMessage());
        }
        return new StringRepresentation("Success");
    } catch (Exception e) {
        LOGGER.error("error reading/serializing requestJSON", e);
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        return new StringRepresentation("Failed: " + e.getMessage());
    }
}
Also used : StringRepresentation(org.restlet.representation.StringRepresentation) AbstractTableConfig(com.linkedin.pinot.common.config.AbstractTableConfig) JsonProcessingException(org.codehaus.jackson.JsonProcessingException) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) JSONException(org.json.JSONException) IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) Post(org.restlet.resource.Post)

Example 9 with Post

use of org.restlet.resource.Post in project pinot by linkedin.

the class PinotInstanceRestletResource method post.

@Override
@Post("json")
public Representation post(Representation entity) {
    StringRepresentation presentation;
    try {
        final String instanceName = (String) getRequest().getAttributes().get(INSTANCE_NAME);
        if (instanceName == null) {
            // This is a request to create an instance
            try {
                final Instance instance = mapper.readValue(ByteStreams.toByteArray(entity.getStream()), Instance.class);
                presentation = addInstance(instance);
            } catch (final Exception e) {
                presentation = new StringRepresentation(e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
                LOGGER.error("Caught exception while processing post request", e);
                ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_INTERNAL_ERROR, 1L);
                setStatus(Status.SERVER_ERROR_INTERNAL);
            }
        } else {
            // This is a request to toggle the state of an instance
            if (_pinotHelixResourceManager.instanceExists(instanceName)) {
                final String state = getRequest().getEntityAsText().trim();
                if (isValidState(state)) {
                    presentation = toggleInstanceState(instanceName, state);
                } else {
                    LOGGER.error(INVALID_STATE_ERROR);
                    setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                    return new StringRepresentation(INVALID_STATE_ERROR);
                }
            } else {
                setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                presentation = new StringRepresentation("Error: Instance " + instanceName + " not found.");
            }
        }
    } catch (final Exception e) {
        presentation = new StringRepresentation(e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
        LOGGER.error("Caught exception while processing post request", e);
        ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_INSTANCE_POST_ERROR, 1L);
        setStatus(Status.SERVER_ERROR_INTERNAL);
    }
    return presentation;
}
Also used : StringRepresentation(org.restlet.representation.StringRepresentation) Instance(com.linkedin.pinot.controller.api.pojos.Instance) JSONException(org.json.JSONException) Post(org.restlet.resource.Post)

Example 10 with Post

use of org.restlet.resource.Post in project pinot by linkedin.

the class PinotSegmentUploadRestletResource method post.

@Override
@Post
public Representation post(Representation entity) {
    Representation rep = null;
    File tmpSegmentDir = null;
    File dataFile = null;
    try {
        // 0/ Get upload type, if it's uri, then download it, otherwise, get the tar from the request.
        Series headers = (Series) getRequestAttributes().get(RESTLET_HTTP_HEADERS);
        String uploadTypeStr = headers.getFirstValue(FileUploadUtils.UPLOAD_TYPE);
        FileUploadType uploadType = null;
        try {
            uploadType = (uploadTypeStr == null) ? FileUploadType.getDefaultUploadType() : FileUploadType.valueOf(uploadTypeStr);
        } catch (Exception e) {
            uploadType = FileUploadType.getDefaultUploadType();
        }
        String downloadURI = null;
        boolean found = false;
        switch(uploadType) {
            case URI:
            case JSON:
                // Download segment from the given Uri
                try {
                    downloadURI = getDownloadUri(uploadType, headers, entity);
                } catch (Exception e) {
                    String errorMsg = String.format("Failed to get download Uri for upload file type: %s, with error %s", uploadType, e.getMessage());
                    LOGGER.warn(errorMsg);
                    JSONObject errorMsgInJson = getErrorMsgInJson(errorMsg);
                    ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L);
                    setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                    return new StringRepresentation(errorMsgInJson.toJSONString(), MediaType.APPLICATION_JSON);
                }
                SegmentFetcher segmentFetcher = null;
                // Get segmentFetcher based on uri parsed from download uri
                try {
                    segmentFetcher = SegmentFetcherFactory.getSegmentFetcherBasedOnURI(downloadURI);
                } catch (Exception e) {
                    String errorMsg = String.format("Failed to get SegmentFetcher from download Uri: %s", downloadURI);
                    LOGGER.warn(errorMsg);
                    JSONObject errorMsgInJson = getErrorMsgInJson(errorMsg);
                    ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L);
                    setStatus(Status.SERVER_ERROR_INTERNAL);
                    return new StringRepresentation(errorMsgInJson.toJSONString(), MediaType.APPLICATION_JSON);
                }
                // Download segment tar to local.
                dataFile = new File(tempDir, "tmp-" + System.nanoTime());
                try {
                    segmentFetcher.fetchSegmentToLocal(downloadURI, dataFile);
                } catch (Exception e) {
                    String errorMsg = String.format("Failed to fetch segment tar from download Uri: %s to %s", downloadURI, dataFile.toString());
                    LOGGER.warn(errorMsg);
                    JSONObject errorMsgInJson = getErrorMsgInJson(errorMsg);
                    ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L);
                    setStatus(Status.SERVER_ERROR_INTERNAL);
                    return new StringRepresentation(errorMsgInJson.toJSONString(), MediaType.APPLICATION_JSON);
                }
                if (dataFile.exists() && dataFile.length() > 0) {
                    found = true;
                }
                break;
            case TAR:
            default:
                // 1/ Create a factory for disk-based file items
                final DiskFileItemFactory factory = new DiskFileItemFactory();
                // 2/ Create a new file upload handler based on the Restlet
                // FileUpload extension that will parse Restlet requests and
                // generates FileItems.
                final RestletFileUpload upload = new RestletFileUpload(factory);
                final List<FileItem> items;
                // 3/ Request is parsed by the handler which generates a
                // list of FileItems
                items = upload.parseRequest(getRequest());
                for (FileItem fileItem : items) {
                    if (!found) {
                        if (fileItem.getFieldName() != null) {
                            found = true;
                            dataFile = new File(tempDir, fileItem.getFieldName());
                            fileItem.write(dataFile);
                        }
                    } else {
                        LOGGER.warn("Got extra file item while pushing segments: " + fileItem.getFieldName());
                    }
                    // TODO: remove the try-catch after verifying it will not throw any exception
                    try {
                        // Remove the temp file
                        // When the file is copied to instead of renamed to the new file, the temp file might be left in the dir
                        fileItem.delete();
                    } catch (Exception e) {
                        LOGGER.error("Caught exception while deleting the temp file, should not reach here", e);
                    }
                }
        }
        // back to the client.
        if (found) {
            // Create a new representation based on disk file.
            // The content is arbitrarily sent as plain text.
            rep = new StringRepresentation(dataFile + " sucessfully uploaded", MediaType.TEXT_PLAIN);
            tmpSegmentDir = new File(tempUntarredPath, dataFile.getName() + "-" + _controllerConf.getControllerHost() + "_" + _controllerConf.getControllerPort() + "-" + System.currentTimeMillis());
            LOGGER.info("Untar segment to temp dir: " + tmpSegmentDir);
            if (tmpSegmentDir.exists()) {
                FileUtils.deleteDirectory(tmpSegmentDir);
            }
            if (!tmpSegmentDir.exists()) {
                tmpSegmentDir.mkdirs();
            }
            // While there is TarGzCompressionUtils.unTarOneFile, we use unTar here to unpack all files
            // in the segment in order to ensure the segment is not corrupted
            TarGzCompressionUtils.unTar(dataFile, tmpSegmentDir);
            File segmentFile = tmpSegmentDir.listFiles()[0];
            String clientIpAddress = getClientInfo().getAddress();
            String clientAddress = InetAddress.getByName(clientIpAddress).getHostName();
            LOGGER.info("Processing upload request for segment '{}' from client '{}'", segmentFile.getName(), clientAddress);
            return uploadSegment(segmentFile, dataFile, downloadURI);
        } else {
            // Some problem occurs, sent back a simple line of text.
            String errorMsg = "No file was uploaded";
            LOGGER.warn(errorMsg);
            JSONObject errorMsgInJson = getErrorMsgInJson(errorMsg);
            rep = new StringRepresentation(errorMsgInJson.toJSONString(), MediaType.APPLICATION_JSON);
            ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L);
            setStatus(Status.SERVER_ERROR_INTERNAL);
        }
    } catch (final Exception e) {
        rep = exceptionToStringRepresentation(e);
        LOGGER.error("Caught exception in file upload", e);
        ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L);
        setStatus(Status.SERVER_ERROR_INTERNAL);
    } finally {
        if ((tmpSegmentDir != null) && tmpSegmentDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpSegmentDir);
            } catch (final IOException e) {
                LOGGER.error("Caught exception in file upload", e);
                ControllerRestApplication.getControllerMetrics().addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L);
                setStatus(Status.SERVER_ERROR_INTERNAL);
            }
        }
        if ((dataFile != null) && dataFile.exists()) {
            FileUtils.deleteQuietly(dataFile);
        }
    }
    return rep;
}
Also used : RestletFileUpload(org.restlet.ext.fileupload.RestletFileUpload) SegmentFetcher(com.linkedin.pinot.common.segment.fetcher.SegmentFetcher) StringRepresentation(org.restlet.representation.StringRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) Representation(org.restlet.representation.Representation) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Series(org.restlet.util.Series) FileItem(org.apache.commons.fileupload.FileItem) FileUploadType(com.linkedin.pinot.common.utils.FileUploadUtils.FileUploadType) JSONObject(com.alibaba.fastjson.JSONObject) StringRepresentation(org.restlet.representation.StringRepresentation) File(java.io.File) Post(org.restlet.resource.Post)

Aggregations

Post (org.restlet.resource.Post)20 StringRepresentation (org.restlet.representation.StringRepresentation)9 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)7 IOException (java.io.IOException)5 JsonRepresentation (org.restlet.ext.json.JsonRepresentation)5 HashMap (java.util.HashMap)4 JsonValue (org.forgerock.json.JsonValue)4 OAuth2Exception (org.forgerock.oauth2.core.exceptions.OAuth2Exception)4 JSONException (org.json.JSONException)4 JSONObject (org.json.JSONObject)4 Representation (org.restlet.representation.Representation)4 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)3 Request (org.restlet.Request)3 DeviceCode (org.forgerock.oauth2.core.DeviceCode)2 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)2 RedirectUriMismatchException (org.forgerock.oauth2.core.exceptions.RedirectUriMismatchException)2 ResourceOwnerAuthenticationRequired (org.forgerock.oauth2.core.exceptions.ResourceOwnerAuthenticationRequired)2 ResourceSetDescription (org.forgerock.oauth2.resources.ResourceSetDescription)2 ISwitchManager (org.openkilda.floodlight.switchmanager.ISwitchManager)2 MessageError (org.openkilda.messaging.error.MessageError)2