org.restlet.representation.Representation Java Examples
The following examples show how to use
org.restlet.representation.Representation.
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: AdminTestHelper.java From helix with Apache License 2.0 | 7 votes |
public static ZNRecord post(Client client, String url, String body) throws IOException { Reference resourceRef = new Reference(url); Request request = new Request(Method.POST, resourceRef); request.setEntity(body, MediaType.APPLICATION_ALL); Response response = client.handle(request); Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK); Representation result = response.getEntity(); StringWriter sw = new StringWriter(); if (result != null) { result.write(sw); } String responseStr = sw.toString(); Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1); Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1); ObjectMapper mapper = new ObjectMapper(); ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class); return record; }
Example #2
Source File: CalendarTypeCollectionResource.java From FoxBPM with Apache License 2.0 | 6 votes |
@SuppressWarnings("deprecation") @Post public void addCalendarType(Representation entity) { // 获取参数 // String id = getAttribute("id"); Map<String, String> paramsMap = getRequestParams(entity); String id = URLDecoder.decode(paramsMap.get("id")); String name = URLDecoder.decode(paramsMap.get("name")); if (StringUtil.isNotEmpty(id)) { CalendarTypeEntity calendarTypeEntity = new CalendarTypeEntity(id); if (StringUtil.isNotEmpty(name)) { calendarTypeEntity.setName(name); } // 获取服务 WorkCalendarService workCalendarService = ProcessEngineManagement.getDefaultProcessEngine().getService(WorkCalendarService.class); // 构造用户信息 workCalendarService.addCalendarType(calendarTypeEntity); } }
Example #3
Source File: RateLimiterResource.java From uReplicator with Apache License 2.0 | 6 votes |
@Override @Put public Representation put(Representation entity) { Form params = getRequest().getResourceRef().getQueryAsForm(); String rate = params.getFirstValue("messagerate"); if (StringUtils.isEmpty(rate)) { getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return new StringRepresentation( String.format("Failed to add new rate limit due to missing parameter messagerate%n")); } try { workerInstance.setMessageRatePerSecond(Double.parseDouble(rate)); LOGGER.info("Set messageRate to {} finished", rate); } catch (Exception e) { getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); LOGGER.error("Set messageRate to {} failed", rate, e); return new StringRepresentation( String.format("Failed to add new topic, with exception: %s%n", e)); } return new StringRepresentation( String.format("Successfully set rate: %s%n", rate)); }
Example #4
Source File: NeighbourhoodManagerConnector.java From vicinity-gateway-api with GNU General Public License v3.0 | 6 votes |
/** * Retrieves the thing descriptions of list IoT objects from the Neighborhood Manager. * * @param Representation of the incoming JSON. List of OIDs * @return Thing descriptions of objects specified in payload. */ public synchronized Representation getThingDescriptions(Representation json){ String endpointUrl = SERVER_PROTOCOL + neighbourhoodManagerServer + ":" + port + API_PATH + TD_SERVICE; ClientResource clientResource = createRequest(endpointUrl); Representation responseRepresentation = clientResource.post(json, MediaType.APPLICATION_JSON); return responseRepresentation; /* String ret; try { ret = representation.getText(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); ret = null; } return ret; */ }
Example #5
Source File: ResourceGroupResource.java From helix with Apache License 2.0 | 6 votes |
@Override public Representation delete() { try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); String resourceName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.RESOURCE_NAME); ZkClient zkclient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkclient); setupTool.dropResourceFromCluster(clusterName, resourceName); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); LOG.error("", e); } return null; }
Example #6
Source File: EntityResource.java From attic-polygene-java with Apache License 2.0 | 6 votes |
private Representation representRdfXml( final EntityState entity ) throws ResourceException { Representation representation = new WriterRepresentation( MediaType.APPLICATION_RDF_XML ) { @Override public void write( Writer writer ) throws IOException { try { Iterable<Statement> statements = entitySerializer.serialize( entity ); new RdfXmlSerializer().serialize( statements, writer ); } catch( RDFHandlerException e ) { throw new IOException( e ); } } }; representation.setCharacterSet( CharacterSet.UTF_8 ); return representation; }
Example #7
Source File: LinksResponseWriter.java From attic-polygene-java with Apache License 2.0 | 6 votes |
private Representation createTextHtmlRepresentation( final Object result, final Response response ) { return new WriterRepresentation( MediaType.TEXT_HTML ) { @Override public void write( Writer writer ) throws IOException { Map<String, Object> context = new HashMap<>(); context.put( "request", response.getRequest() ); context.put( "response", response ); context.put( "result", result ); try { cfg.getTemplate( "links.htm" ).process( context, writer ); } catch( TemplateException e ) { throw new IOException( e ); } } }; }
Example #8
Source File: ReferenceList.java From DeviceConnect-Android with MIT License | 6 votes |
/** * Returns a representation of the list in "text/html" format. * * @return A representation of the list in "text/html" format. */ public Representation getWebRepresentation() { // Create a simple HTML list final StringBuilder sb = new StringBuilder(); sb.append("<html><body style=\"font-family: sans-serif;\">\n"); if (getIdentifier() != null) { sb.append("<h2>Listing of \"" + getIdentifier().getPath() + "\"</h2>\n"); final Reference parentRef = getIdentifier().getParentRef(); if (!parentRef.equals(getIdentifier())) { sb.append("<a href=\"" + parentRef + "\">..</a><br>\n"); } } else { sb.append("<h2>List of references</h2>\n"); } for (final Reference ref : this) { sb.append("<a href=\"" + ref.toString() + "\">" + ref.getRelativeRef(getIdentifier()) + "</a><br>\n"); } sb.append("</body></html>\n"); return new StringRepresentation(sb.toString(), MediaType.TEXT_HTML); }
Example #9
Source File: Objects.java From vicinity-gateway-api with GNU General Public License v3.0 | 6 votes |
/** * Returns all available (both exposed and discovered and all adapters) IoT objects that can be seen by that * particular object - this does not count objects that are offline. * * * @return All VICINITY Identifiers of IoT objects fulfil the type and maximum constraint and own parameter OR * Object description if the OID is specified. * */ @Get public Representation represent() { Map<String, String> queryParams = getQuery().getValuesMap(); boolean attrObjectsWithTDs = false; if (queryParams.get(ATTR_TDS) != null) { attrObjectsWithTDs = Boolean.parseBoolean(queryParams.get(ATTR_TDS)); } int attrPage = 0; if (queryParams.get(ATTR_PAGE) != null) { attrPage = Integer.parseInt(queryParams.get(ATTR_PAGE)); } if (attrObjectsWithTDs) { return getObjectsTDs(attrPage); } else { return getObjects(); } }
Example #10
Source File: EventsEid.java From vicinity-gateway-api with GNU General Public License v3.0 | 6 votes |
/** * Used by an Agent/Adapter, that is capable of generating events and is willing to send these events to subscribed * objects. A call to this end point activates the channel – from that moment, other objects in the network are able * to subscribe for receiving those messages. * * @param entity Optional JSON with parameters. * @return statusMessage {@link StatusMessage StatusMessage} with the result of the operation. */ @Post("json") public Representation accept(Representation entity) { String attrEid = getAttribute(ATTR_EID); String callerOid = getRequest().getChallengeResponse().getIdentifier(); Map<String, String> queryParams = getQuery().getValuesMap(); Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER); if (attrEid == null){ logger.info("EID: " + attrEid + " Invalid identifier."); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid identifier."); } String body = getRequestBody(entity, logger); CommunicationManager communicationManager = (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER); StatusMessage statusMessage = communicationManager.activateEventChannel(callerOid, attrEid, queryParams, body); return new JsonRepresentation(statusMessage.buildMessage().toString()); }
Example #11
Source File: ObjectsOidActionsAidTasksTid.java From vicinity-gateway-api with GNU General Public License v3.0 | 6 votes |
/** * Gets a specific task status to perform an action of an available IoT object. * * @return Task status. */ @Get public Representation represent(Representation entity) { String attrOid = getAttribute(ATTR_OID); String attrAid = getAttribute(ATTR_AID); String attrTid = getAttribute(ATTR_TID); String callerOid = getRequest().getChallengeResponse().getIdentifier(); Map<String, String> queryParams = getQuery().getValuesMap(); Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER); if (attrOid == null || attrAid == null || attrTid == null){ logger.info("OID: " + attrOid + " AID: " + attrAid + " TID: " + attrTid + " Given identifier does not exist."); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Given identifier does not exist."); } String body = getRequestBody(entity, logger); return getActionTaskStatus(callerOid, attrOid, attrAid, attrTid, queryParams, body); }
Example #12
Source File: CreateFormFromContractOperation.java From bonita-studio with GNU General Public License v2.0 | 6 votes |
@Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(Messages.creatingNewForm, IProgressMonitor.UNKNOWN); try { setArtifactName(getNewName()); URL url = pageDesignerURLBuilder.newPageFromContract(formScope, artifactName); Pool parentPool = new ModelSearch(Collections::emptyList).getDirectParentOfType(contract, Pool.class); BusinessDataStore businessDataStore = new BusinessDataStore(parentPool, getRepositoryAccessor()); ContractToBusinessDataResolver contractToBusinessDataResolver = new ContractToBusinessDataResolver( businessDataStore); Contract tmpContract = EcoreUtil.copy(contract); // will contains unwanted contractInput for readOnly attributes openReadOnlyAttributeDialog(tmpContract, businessDataStore); TreeResult treeResult = contractToBusinessDataResolver.resolve(tmpContract, buildReadOnlyAttributes); Representation body = new JacksonRepresentation<>(new ToWebContract(treeResult).apply(tmpContract)); responseObject = createArtifact(url, body); } catch (MalformedURLException e) { throw new InvocationTargetException(e, "Failed to create new form url."); } }
Example #13
Source File: RawProjectResource.java From scava with Eclipse Public License 2.0 | 6 votes |
public Representation doRepresent() { String projectName = (String) getRequest().getAttributes().get("projectid"); ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository(); Project p = projectRepo.getProjects().findOneByShortName(projectName); if (p == null) { getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return Util.generateErrorMessageRepresentation(generateRequestJson(mapper, projectName), "No project was found with the requested name."); } try { // TODO: return Util.createJsonRepresentation(mapper.writeValueAsString(p.getDbObject()));//mapper.writeValueAsString(p);// } catch (Exception e) { e.printStackTrace(); return Util.generateErrorMessageRepresentation(generateRequestJson(mapper, projectName), "An error occurred when converting the project to JSON: " + e.getMessage()); } }
Example #14
Source File: RequestWriterDelegator.java From attic-polygene-java with Apache License 2.0 | 6 votes |
@Override public boolean writeRequest(Object requestObject, Request request) throws ResourceException { if (requestObject == null) { if (!Method.GET.equals(request.getMethod())) request.setEntity(new EmptyRepresentation()); return true; } if (requestObject instanceof Representation) { request.setEntity((Representation) requestObject); return true; } for (RequestWriter requestWriter : requestWriters) { if (requestWriter.writeRequest(requestObject, request)) return true; } return false; }
Example #15
Source File: ObjectsOidActionsAid.java From vicinity-gateway-api with GNU General Public License v3.0 | 6 votes |
/** * Performs an action on an available IoT object. * * @param entity Representation of the incoming JSON. * @return A task to perform an action was submitted. */ @Post("json") public Representation accept(Representation entity) { String attrOid = getAttribute(ATTR_OID); String attrAid = getAttribute(ATTR_AID); String callerOid = getRequest().getChallengeResponse().getIdentifier(); Map<String, String> queryParams = getQuery().getValuesMap(); Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER); if (attrOid == null || attrAid == null){ logger.info("OID: " + attrOid + " AID: " + attrAid + " Given identifier does not exist."); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Given identifier does not exist."); } String body = getRequestBody(entity, logger); return startAction(callerOid, attrOid, attrAid, body, queryParams); }
Example #16
Source File: ValidationRestletResource.java From uReplicator with Apache License 2.0 | 6 votes |
@Override @Get public Representation get() { final String option = (String) getRequest().getAttributes().get("option"); if ("srcKafka".equals(option)) { if (_srcKafkaValidationManager == null) { LOGGER.warn("SourceKafkaClusterValidationManager is null!"); return new StringRepresentation("SrcKafkaValidationManager is not been initialized!"); } LOGGER.info("Trying to call validation on source kafka cluster!"); return new StringRepresentation(_srcKafkaValidationManager.validateSourceKafkaCluster()); } else { LOGGER.info("Trying to call validation on current cluster!"); return new StringRepresentation(_validationManager.validateExternalView()); } }
Example #17
Source File: PlatformDeletePropertiesResource.java From scava with Eclipse Public License 2.0 | 6 votes |
@Delete public Representation deletePlatformProperties() { Platform platform = Platform.getInstance(); String key = (String) getRequest().getAttributes().get("key"); System.out.println("Delete platform properties ..."); ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository(); Properties properties = projectRepo.getProperties().findOneByKey(key); if (properties != null) { projectRepo.getProperties().remove(properties); platform.getProjectRepositoryManager().getProjectRepository().getProperties().sync(); } StringRepresentation rep = new StringRepresentation(properties.getDbObject().toString()); rep.setMediaType(MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); return rep; }
Example #18
Source File: EntityResource.java From attic-polygene-java with Apache License 2.0 | 6 votes |
@Override protected Representation delete( Variant variant ) throws ResourceException { Usecase usecase = UsecaseBuilder.newUsecase( "Remove entity" ); EntityStoreUnitOfWork uow = entityStore.newUnitOfWork( module, usecase, SystemTime.now() ); try { EntityReference reference = EntityReference.create( identity ); uow.entityStateOf( module, reference ).remove(); uow.applyChanges().commit(); getResponse().setStatus( Status.SUCCESS_NO_CONTENT ); } catch( EntityNotFoundException e ) { uow.discard(); getResponse().setStatus( Status.CLIENT_ERROR_NOT_FOUND ); } return new EmptyRepresentation(); }
Example #19
Source File: ControllerResource.java From helix with Apache License 2.0 | 5 votes |
/** * Enable/disable Helix controller * <p> * Usage: * <code>curl -d 'jsonParameters={"command":"enableCluster","enabled":"{true/false}"}' * -H "Content-Type: application/json" http://{host:port}/clusters/{cluster}/Controller */ @Override public Representation post(Representation entity) { try { String clusterName = ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME); ZkClient zkClient = ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT); ClusterSetup setupTool = new ClusterSetup(zkClient); JsonParameters jsonParameters = new JsonParameters(entity); String command = jsonParameters.getCommand(); if (command == null) { throw new HelixException("Could NOT find 'command' in parameterMap: " + jsonParameters._parameterMap); } else if (command.equalsIgnoreCase(ClusterSetup.enableCluster)) { boolean enabled = Boolean.parseBoolean(jsonParameters.getParameter(JsonParameters.ENABLED)); setupTool.getClusterManagementTool().enableCluster(clusterName, enabled); } else { throw new HelixException("Unsupported command: " + command + ". Should be one of [" + ClusterSetup.enableCluster + "]"); } getResponse().setEntity(getControllerRepresentation(clusterName)); getResponse().setStatus(Status.SUCCESS_OK); } catch (Exception e) { getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e), MediaType.APPLICATION_JSON); getResponse().setStatus(Status.SUCCESS_OK); } return null; }
Example #20
Source File: AbstractConverter.java From ontopia with Apache License 2.0 | 5 votes |
@Override public <T> float score(Representation source, Class<T> target, Resource resource) { for (Variant v : variants) { if (v.getMediaType().isCompatible(source.getMediaType())) { return .5F; } } return -1F; }
Example #21
Source File: WebPageFileStore.java From bonita-studio with GNU General Public License v2.0 | 5 votes |
public Collection<String> getPageResources() { try { ClientResource clientResource = new ClientResource( PageDesignerURLFactory.INSTANCE.resources(getId()).toURI()); clientResource.getLogger().setLevel(Level.OFF); final Representation representation = clientResource.get(); return representation != null ? parseExtensionResources( representation.getText() ) : Collections.emptyList(); } catch (URISyntaxException | IOException e) { BonitaStudioLog.error(e); return null; } }
Example #22
Source File: RawProjectListResource.java From scava with Eclipse Public License 2.0 | 5 votes |
public Representation doRepresent() { // TODO boolean paging = getRequest().getAttributes().containsKey("page"); //Platform platform = Platform.getInstance(); ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository(); Iterator<Project> it = projectRepo.getProjects().iterator(); ObjectMapper mapper = new ObjectMapper(); ArrayNode projects = mapper.createArrayNode(); while (it.hasNext()) { try { Project project = it.next(); ObjectNode p = mapper.createObjectNode(); p.put("name", project.getName()); p.put("description", project.getDescription()); projects.add(p); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); ObjectNode m = mapper.createObjectNode(); m.put("apicall", "list-all-projects"); return Util.generateErrorMessageRepresentation(m, e.getMessage()); } } return Util.createJsonRepresentation(projects); }
Example #23
Source File: RestClientImpl.java From concierge with Eclipse Public License 1.0 | 5 votes |
/** * @see org.osgi.rest.client.RestClient#getServiceRepresentations(java.lang.String * ) */ public Collection<ServiceReferenceDTO> getServiceReferences( final String filter) throws Exception { final ClientResource res = new ClientResource(Method.GET, baseUri.resolve("framework/services/representations")); if (filter != null) { res.getQuery().add("filter", filter); } final Representation repr = res.get(SERVICES_REPRESENTATIONS); return DTOReflector.getDTOs(ServiceReferenceDTO.class, repr); }
Example #24
Source File: RestClientImpl.java From concierge with Eclipse Public License 1.0 | 5 votes |
/** * @see org.osgi.rest.client.RestClient#getBundleStartLevel(java.lang.String) */ public BundleStartLevelDTO getBundleStartLevel(final String bundlePath) throws Exception { final Representation repr = new ClientResource(Method.GET, baseUri.resolve(bundlePath + "/startlevel")) .get(BUNDLE_STARTLEVEL); return DTOReflector.getDTO(BundleStartLevelDTO.class, repr); }
Example #25
Source File: ObjectsOidProperties.java From vicinity-gateway-api with GNU General Public License v3.0 | 5 votes |
/** * Retrieves a request body. * * @param entity Entity to extract the body from. * @param logger Logger. * @return Text representation of the body. */ private String getRequestBody(Representation entity, Logger logger) { if (entity == null) { return null; } // check the body of the event to be sent if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){ logger.warning("Invalid request body - must be a valid JSON."); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid request body - must be a valid JSON."); } // get the json String eventJsonString = null; try { eventJsonString = entity.getText(); } catch (IOException e) { logger.info(e.getMessage()); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid request body"); } return eventJsonString; }
Example #26
Source File: AnalysisStackTracesResource.java From scava with Eclipse Public License 2.0 | 5 votes |
public Representation doRepresent() { /** * Fetch the analysis stacktraces */ ArrayNode results = mapper.createArrayNode(); ProjectRepository projectRepository = platform.getProjectRepositoryManager().getProjectRepository(); for (ProjectError projectError : projectRepository.getErrors()) { ObjectNode error = mapper.createObjectNode(); error.put("projectId", projectError.getDbObject().get("projectId").toString()); error.put("projectName", projectError.getDbObject().get("projectName").toString()); error.put("clazz", projectError.getDbObject().get("clazz").toString()); error.put("stackTrace", projectError.getDbObject().get("stackTrace").toString().replaceAll("\n", "").replaceAll("\t", "")); error.put("workerIdentifier", projectError.getDbObject().get("workerIdentifier").toString()); try { SimpleDateFormat formater = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat parser1 = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy",Locale.UK); String executionDateError = projectError.getDbObject().get("date").toString(); error.put("executionErrorDate", formater.format(parser1.parse(executionDateError))); SimpleDateFormat parser2 = new SimpleDateFormat("yyyyMMdd"); String analysisDateError = projectError.getDbObject().get("dateForError").toString(); error.put("analysisRangeErrorDate", formater.format(parser2.parse(analysisDateError))); } catch (ParseException e) { e.printStackTrace(); } results.add(error); } return Util.createJsonRepresentation(results); }
Example #27
Source File: AbstractConverter.java From ontopia with Apache License 2.0 | 5 votes |
@Override public <T> T toObject(Representation source, Class<T> target, Resource resource) throws IOException { LocatorIF base_address = null; // todo from header/params try { TopicMapReaderIF reader = getFragmentReader(source.getStream(), base_address); TopicMapIF fragment = reader.read(); return objectFromFragment(fragment, target, resource); } catch (OntopiaRuntimeException ore) { throw OntopiaRestErrors.COULD_NOT_READ_FRAGMENT.build(ore); } }
Example #28
Source File: ObjectsOidEvents.java From vicinity-gateway-api with GNU General Public License v3.0 | 5 votes |
/** * Retrieves a request body. * * @param entity Entity to extract the body from. * @param logger Logger. * @return Text representation of the body. */ private String getRequestBody(Representation entity, Logger logger) { if (entity == null) { return null; } // check the body of the event to be sent if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){ logger.warning("Invalid request body - must be a valid JSON."); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid request body - must be a valid JSON."); } // get the json String eventJsonString = null; try { eventJsonString = entity.getText(); } catch (IOException e) { logger.info(e.getMessage()); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid request body"); } return eventJsonString; }
Example #29
Source File: GeoWaveOperationServiceWrapper.java From geowave with Apache License 2.0 | 5 votes |
private Representation handleRequestWithPayload( final HttpMethod requiredMethod, final Representation request) { // First check that the request is the requiredMethod, return 405 if // not. if (requiredMethod.equals(operation.getMethod())) { RequestParameters requestParameters; // Then check which MediaType is the request, which determines the // constructor used for RequestParameters. if (checkMediaType(MediaType.APPLICATION_JSON, request)) { try { requestParameters = new RequestParametersJson(request); } catch (final IOException e) { setStatus(Status.SERVER_ERROR_INTERNAL); return null; } } else if (checkMediaType(MediaType.APPLICATION_WWW_FORM, request)) { requestParameters = new RequestParametersForm(new Form(request)); } else { // If MediaType is not set, then the parameters are likely to be // found in the URL. requestParameters = new RequestParametersForm(getQuery()); } // Finally, handle the request with the parameters, whose type // should no longer matter. return handleRequest(requestParameters); } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); return null; } }
Example #30
Source File: ObjectsOidActions.java From vicinity-gateway-api with GNU General Public License v3.0 | 5 votes |
/** * Retrieves a request body. * * @param entity Entity to extract the body from. * @param logger Logger. * @return Text representation of the body. */ private String getRequestBody(Representation entity, Logger logger) { if (entity == null) { return null; } // check the body of the event to be sent if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){ logger.warning("Invalid request body - must be a valid JSON."); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid request body - must be a valid JSON."); } // get the json String eventJsonString = null; try { eventJsonString = entity.getText(); } catch (IOException e) { logger.info(e.getMessage()); throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid request body"); } return eventJsonString; }