org.restlet.ext.json.JsonRepresentation Java Examples

The following examples show how to use org.restlet.ext.json.JsonRepresentation. 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: EventsEid.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #2
Source File: AccessTokenServerResource.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
     * Response JSON document with valid token. The format of the JSON document
     * is according to 5.1. Successful Response.
     * 
     * @param token
     *            The token generated by the client.
     * @param requestedScope
     *            The scope originally requested by the client.
     * @return The token representation as described in RFC6749 5.1. <br>
     * 			※Local OAuth ではResultRepresentation型のポインタを返し、result=trueならアクセストークンを設定して返す。<br>
     * 			  アクセストークンは、getText()で返す。
     * @throws ResourceException
     */
    protected static Representation responseTokenRepresentation(Token token,
            String[] requestedScope) throws JSONException {
        JSONObject response = new JSONObject();

        response.put(TOKEN_TYPE, token.getTokenType());
        response.put(ACCESS_TOKEN, token.getAccessToken());
//        response.put(EXPIRES_IN, token.getExpirePeriod());
        String refreshToken = token.getRefreshToken();
        if (refreshToken != null && !refreshToken.isEmpty()) {
            response.put(REFRESH_TOKEN, refreshToken);
        }
        Scope[] scope = token.getScope();
        if (!Scopes.isIdentical(Scope.toScopeStringArray(scope), requestedScope)) {
            /*
             * OPTIONAL, if identical to the scope requested by the client,
             * otherwise REQUIRED. (5.1. Successful Response)
             */
            response.put(SCOPE, Scopes.toString(scope));
        }

        return new JsonRepresentation(response);
    }
 
Example #3
Source File: EventsEid.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Used by an Agent/Adapter that is capable of generating events to de-activate an event channel. This will 
 * prohibit any other new objects to subscribe to that channel, and the objects that are already subscribed are 
 * notified and removed from subscription list.
 * 
 * @return statusMessage {@link StatusMessage StatusMessage} with the result of the operation.
 */
@Delete
public Representation remove(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_NOT_FOUND, 
				"Invalid identifier.");
	}
	
	String body = getRequestBody(entity, logger);
	
	CommunicationManager communicationManager 
					= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	StatusMessage statusMessage = communicationManager.deactivateEventChannel(callerOid, attrEid, queryParams, body);
	
	return new JsonRepresentation(statusMessage.buildMessage().toString());
}
 
Example #4
Source File: ObjectsOidEventsEid.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves status of a remote event channel.
 * 
 * @return Latest property value.
 */
@Get
public Representation represent(Representation entity) {
	String attrOid = getAttribute(ATTR_OID);
	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 (attrOid == null || attrEid == null){
		logger.info("OID: " + attrOid + " 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);
	
	
	return new JsonRepresentation(communicationManager.getEventChannelStatus(callerOid, attrOid, attrEid, 
			queryParams, body).buildMessage().toString()); 
	
}
 
Example #5
Source File: ObjectsOidEventsEid.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Subscribes to the channel.
 * 
 * @param entity Representation of the incoming JSON.
 * @param object Model (from request).
 * @return A task to perform the action was submitted.
 */
@Post("json")
public Representation accept(Representation entity) {
	String attrOid = getAttribute(ATTR_OID);
	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 (attrOid == null || attrEid == null){
		logger.info("OID: " + attrOid + " 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);


	return new JsonRepresentation(communicationManager.subscribeToEventChannel(callerOid, attrOid, attrEid, 
			queryParams, body).buildMessage().toString());
}
 
Example #6
Source File: ObjectsOidEventsEid.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Cancel subscription to the channel.
 * 
 * @return statusMessage {@link StatusMessage StatusMessage} with the result of the operation.
 */
@Delete
public Representation remove(Representation entity) {
	String attrOid = getAttribute(ATTR_OID);
	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 + " Given identifier does not exist.");
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid identifier.");
	}
	
	String body = getRequestBody(entity, logger);
	
	CommunicationManager communicationManager 
					= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	return new JsonRepresentation(communicationManager.unsubscribeFromEventChannel(callerOid, attrOid, attrEid, 
			queryParams, body).buildMessage().toString());
}
 
Example #7
Source File: DTOReflector.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
public static Collection<String> getStrings(final Representation repr) throws Exception {
	final Collection<String> result = new ArrayList<String>();
	if (JSON_BASED.includes(repr.getMediaType())) {
		final JSONArray array = new JsonRepresentation(repr).getJsonArray();
		for (int i = 0; i < array.length(); i++) {
			result.add(array.getString(i));
		}
	} else if (XML_BASED.includes(repr.getMediaType())) {
		final Document doc = new DomRepresentation(repr).getDocument();
		final Node rootNode = doc.getFirstChild();
		final NodeList nodes = rootNode.getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			result.add(nodes.item(i).getTextContent());
		}
	} else {
		throw new UnsupportedOperationException(repr.getMediaType().toString());
	}

	return result;
}
 
Example #8
Source File: ObjectsOidActionsAid.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Stores new action.
 * 
 * @param sourceOid Caller OID.
 * @param destinationOid Called OID.
 * @param actionId Action ID.
 * @param body New representation of the Action.
 * @return Response text.
 */
private Representation startAction(String sourceOid, String destinationOid, String actionId, String body, 
		Map<String, String> queryParams){

	CommunicationManager communicationManager 
			= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);

	return new JsonRepresentation(communicationManager.startAction(sourceOid, destinationOid, actionId, body, 
			queryParams).buildMessage().toString());

}
 
Example #9
Source File: ObjectsOidActions.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves all actions of specific object
 * 
 * @param sourceOid Caller OID.
 * @param attrOid Called OID.
 * @param logger Logger taken previously from Context.
 * @return Response text.
 */ 
private Representation getObjectActions(String sourceOid, String destinationOid, String body, 
		Map<String, String> queryParams){
	
	CommunicationManager communicationManager 
		= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	return new JsonRepresentation(communicationManager.getActionsOfRemoteObject(sourceOid, destinationOid, body, queryParams).buildMessage().toString());
}
 
Example #10
Source File: ObjectsOidActionsAid.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves the Action defined as AID.
 * 
 * @param sourceOid Caller OID.
 * @param status Next status.
 * @param actionId Action ID.
 * @param returnValue New return value.
 * @param queryParams Query parameters to be send along.
 * @return Response text.
 */
private Representation updateActionStatus(String sourceOid, String actionId, String status, String returnValue, 
		Map<String, String> queryParams){
	
	CommunicationManager communicationManager 
			= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);

	return new JsonRepresentation(communicationManager.updateTaskStatus(sourceOid, actionId, status, returnValue, 
			queryParams).buildMessage().toString());
	
}
 
Example #11
Source File: ObjectsLogin.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Answers the GET call, after it is authenticated.
 * 
 * @return A {@link StatusMessage StatusMessage} indicating that login is successful.
 */
@Get
public Representation represent() {
	
	// if the login is unsuccessful, the execution will never reach this place
	// the status message has to be created a new - there is no easy way how to propagate it from the REST
	// authentication verifier.
	StatusMessage statusMessage = new StatusMessage(false, CodesAndReasons.CODE_200_OK, 
			CodesAndReasons.REASON_200_OK + "Login successfull.", StatusMessage.CONTENTTYPE_APPLICATIONJSON);
	
	return new JsonRepresentation(statusMessage.buildMessage().toString());
}
 
Example #12
Source File: ObjectsLogout.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Logs the object that is calling this method out from the network.
 * 
 * @return {@link StatusMessage StatusMessage} with a success message.
 */
@Get
public Representation represent() {
	
	logoutObject();
	
	// the status message has to be created a new - there is no easy way how to propagate it from the REST
	// authentication verifier.
	StatusMessage statusMessage = new StatusMessage(false, CodesAndReasons.CODE_200_OK, 
			CodesAndReasons.REASON_200_OK + "Logout successfull.", StatusMessage.CONTENTTYPE_APPLICATIONJSON);
	
	return new JsonRepresentation(statusMessage.buildMessage().toString());
}
 
Example #13
Source File: DTOReflector.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
public static <T extends DTO> T getDTO(final Class<T> clazz,
		final Representation repr) throws Exception {
	if (JSON_BASED.includes(repr.getMediaType())) {
		final JSONObject data = new JsonRepresentation(repr).getJsonObject();
		return getDTOfromJson(clazz, data, repr.getLocationRef().getPath());
	} else if (XML_BASED.includes(repr.getMediaType())) {
		final Document doc = new DomRepresentation(repr).getDocument();
		return getDTOfromXml(clazz, (Element) doc.getFirstChild(), repr.getLocationRef().getPath());
	} else {
		throw new UnsupportedOperationException(repr.getMediaType().toString());
	}
}
 
Example #14
Source File: DTOReflector.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
public static <T extends DTO> Collection<T> getDTOs(Class<T> clazz, Representation repr) throws Exception {
	if (JSON_BASED.includes(repr.getMediaType())) {
		return getDTOsFromJson(clazz, new JsonRepresentation(repr).getJsonArray());
	} else if (XML_BASED.includes(repr.getMediaType())) {
		System.out.println("content: " + repr.getText());
		return getDTOsFromXml(clazz, new DomRepresentation(repr).getDocument());
	} else {
		throw new UnsupportedOperationException(repr.getMediaType().toString());
	}
}
 
Example #15
Source File: DTOReflector.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
public static Map<String, String> getMap(final Representation repr) throws Exception {
	if (JSON_BASED.includes(repr.getMediaType())) {
		final JSONObject data = new JsonRepresentation(repr).getJsonObject();
		return getMapfromJsonObject(data);
	} else {
		throw new UnsupportedOperationException(repr.getMediaType().toString());
	}
}
 
Example #16
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getBundleState(java.lang.String)
 */
public int getBundleState(final String bundlePath) throws Exception {
	final Representation repr = new ClientResource(Method.GET,
			baseUri.resolve(bundlePath + "/state")).get(BUNDLE_STATE);

	// FIXME: hardcoded to JSON
	final JSONObject obj = new JsonRepresentation(repr).getJsonObject();
	return obj.getInt("state");
}
 
Example #17
Source File: OAuthServerResource.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Returns the representation of the given error. The format of the JSON
 * document is according to 5.2. Error Response.
 * 
 * @param ex
 *            Any OAuthException with error
 * @return The representation of the given error.
 */
public static Representation responseErrorRepresentation(OAuthException ex) {
    try {
        return new JsonRepresentation(ex.createErrorDocument());
    } catch (JSONException e) {
        StringRepresentation r = new StringRepresentation(
                "{\"error\":\"server_error\",\"error_description:\":\""
                        + e.getLocalizedMessage() + "\"}");
        r.setMediaType(MediaType.APPLICATION_JSON);
        return r;
    }
}
 
Example #18
Source File: CreateFormOperation.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.beginTask(Messages.creatingNewForm, IProgressMonitor.UNKNOWN);
    setArtifactName(getNewName());
    JSONObject jsonBody = createBody();
    try {
        responseObject = createArtifact(pageDesignerURLBuilder.newPage(), new JsonRepresentation(jsonBody));
    } catch (MalformedURLException e) {
        throw new InvocationTargetException(e, "Failed to create new form URL.");
    }
}
 
Example #19
Source File: CreatePageOperation.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.beginTask(Messages.creatingNewPage, IProgressMonitor.UNKNOWN);
    setArtifactName(getNewName());
    JSONObject bodyObject = createBody();
    try {
        responseObject = createArtifact(pageDesignerURLBuilder.newPage(), new JsonRepresentation(bodyObject));
    } catch (MalformedURLException e) {
        throw new InvocationTargetException(e, "Failed to create new page URL.");
    }
    openArtifact(getNewArtifactId());
}
 
Example #20
Source File: CreateLayoutOperation.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.beginTask(Messages.creatingNewLayout, IProgressMonitor.UNKNOWN);
    setArtifactName(getNewName());
    JSONObject bodyObject = createBody();
    try {
        responseObject = createArtifact(pageDesignerURLBuilder.newPage(), new JsonRepresentation(bodyObject));
    } catch (MalformedURLException e) {
        throw new InvocationTargetException(e, "Failed to create new page URL.");
    }
    openArtifact(getNewArtifactId());
}
 
Example #21
Source File: CreateCustomWidgetOperation.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.beginTask(Messages.creatingNewWidget, IProgressMonitor.UNKNOWN);
    JSONObject bodyObject = createBody();
    try {
        responseObject = createArtifact(pageDesignerURLBuilder.newWidget(), new JsonRepresentation(bodyObject));
    } catch (MalformedURLException e) {
        throw new InvocationTargetException(e, "Failed to create new widget URL.");
    }
    openArtifact(getNewArtifactId());
}
 
Example #22
Source File: ObjectsOid.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves thing description of specific object
 * 
 * @param sourceOid Caller OID.
 * @param attrOid Called OID.
 * @param logger Logger taken previously from Context.
 * @return Response text.
 */ 
private Representation getObjectThingDescription(String sourceOid, String destinationOid, String body, 
		Map<String, String> queryParams){
	
	CommunicationManager communicationManager 
		= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	return new JsonRepresentation(communicationManager.getThingDescriptionOfRemoteObject(sourceOid, destinationOid, body, queryParams).buildMessage().toString());
}
 
Example #23
Source File: CommunicationManager.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * getThingDescriptions - Return one page of the thing descriptions of IoT object(s).
 * 
 * @param page number (0 <-> countOfObjects/5 + 1)
 * @param sourceObjectId 
 * 
 * @return JsonObject with the list of thing descriptions 
 */
public Representation getThingDescriptions(String sourceObjectId, int pageNumber){
	
	if (sourceObjectId == null || sourceObjectId.isEmpty()) {
		logger.warning("Method parameter sourceObjectId can't be null nor empty.");
		
		return null;
	}
	
	if (pageNumber < 0) {
		logger.warning("Method parameter pageNumber can't be smaller than 0;");
		logger.warning("Set pageNumber to 0;");
		
		pageNumber = 0;
	}
	
	Set<String> rosterObjects = getRosterEntriesForObject(sourceObjectId, pageNumber);
	
	if (rosterObjects == null) {
		return null;
	}
	
	JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
	JsonArrayBuilder mainArrayBuilder = Json.createArrayBuilder();
	
	rosterObjects.forEach(item -> {
		mainArrayBuilder.add(
				Json.createObjectBuilder().add(ATTR_OID, item)
			);
	});
	
	mainObjectBuilder.add(ATTR_OBJECTS, mainArrayBuilder);
	JsonObject json = mainObjectBuilder.build();
	
	return nmConnector.getThingDescriptions(new JsonRepresentation(json.toString()));
}
 
Example #24
Source File: ObjectsOidEvents.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves all events of specific object
 * 
 * @param sourceOid Caller OID.
 * @param attrOid Called OID.
 * @param logger Logger taken previously from Context.
 * @return Response text.
 */ 
private Representation getObjectEvents(String sourceOid, String destinationOid, String body, 
		Map<String, String> queryParams){
	
	CommunicationManager communicationManager 
		= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	return new JsonRepresentation(communicationManager.getEventsOfRemoteObject(sourceOid, destinationOid, body, queryParams).buildMessage().toString());
}
 
Example #25
Source File: ObjectsOidProperties.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves all properties of specific object
 * 
 * @param sourceOid Caller OID.
 * @param attrOid Called OID.
 * @param logger Logger taken previously from Context.
 * @return Response text.
 */ 
private Representation getObjectProperties(String sourceOid, String destinationOid, String body, 
		Map<String, String> queryParams){
	
	CommunicationManager communicationManager 
		= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	return new JsonRepresentation(communicationManager.getPropertiesOfRemoteObject(sourceOid, destinationOid, body, queryParams).buildMessage().toString());
}
 
Example #26
Source File: ObjectsOidPropertiesPid.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves the property defined as PID.
 * 
 * @param sourceOid Caller OID.
 * @param attrOid Called OID.
 * @param attrPid Property ID.
 * @param logger Logger taken previously from Context.
 * @return Response text.
 */
private Representation getObjectProperty(String sourceOid, String destinationOid, String propertyId, String body, 
		Map<String, String> queryParams){
	
	CommunicationManager communicationManager 
		= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	return new JsonRepresentation(communicationManager.getPropertyOfRemoteObject(sourceOid, destinationOid, 
			propertyId, body, queryParams).buildMessage().toString());
}
 
Example #27
Source File: ObjectsOidPropertiesPid.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Updates the property defined as PID.
 * 
 * @param sourceOid Caller OID.
 * @param destinationOid Called OID.
 * @param propertyId Property ID.
 * @param body New representation of the property.
 * @param logger Logger taken previously from Context.
 * @return Response text.
 */
private Representation updateProperty(String sourceOid, String destinationOid, String propertyId, String body, 
		Map<String, String> queryParams){
	
	CommunicationManager communicationManager 
							= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	return new JsonRepresentation(communicationManager.setPropertyOfRemoteObject(sourceOid, destinationOid, 
			propertyId, body, queryParams).buildMessage().toString());
	
}
 
Example #28
Source File: EventsEid.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Used by an Agent/Adapter that is capable of generating events, to send an event to all subscribed objects on 
 * the network.
 * 
 * @param entity JSON with the event.
 * @return statusMessage {@link StatusMessage StatusMessage} with the result of the operation.
 */
@Put("json")
public Representation store(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);
	
	// check the mandatory attributes
	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.sendEventToSubscribedObjects(callerOid, attrEid, body, 
							queryParams);
	
	return new JsonRepresentation(statusMessage.buildMessage().toString());
}
 
Example #29
Source File: CommunicationManager.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * getThingDescriptions - Return all pages of the thing descriptions of IoT object(s).
 * 
 * @param sourceObjectId 
 * 
 * @return The list of thing descriptions 
 */
public Representation getThingDescriptions(String sourceObjectId) {
	
	if (sourceObjectId == null || sourceObjectId.isEmpty()) {
		logger.warning("Method parameter sourceObjectId can't be null nor empty.");
		
		return null;
	}
	
	JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
	JsonArrayBuilder mainArrayBuilder = Json.createArrayBuilder();
	
	Representation r = null;
	int i = 0;
	
	do {
		
		r = getThingDescriptions(sourceObjectId, i++);
		
		if (r == null) {
			break;
		}
		
		JsonArray tds = parseThingDescriptionsFromRepresentation(r);
		tds.forEach(item -> {
			mainArrayBuilder.add(item);
		});
	}
	while (true);
	
	mainObjectBuilder.add(ATTR_TDS, mainArrayBuilder);
	JsonObject json = mainObjectBuilder.build();
	
	return new JsonRepresentation(json.toString());
}
 
Example #30
Source File: ITeslaDataResource.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
@Get("csv|json")
public Object getRepresentation() {

    if (ds == null) {
        getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        return null;
    }

    if (!ds.getStatus().isInitialized()) {
        getResponse().setStatus(Status.SUCCESS_ACCEPTED);
        return "Initializing...";
    }

    Form queryForm = getRequest().getOriginalRef().getQueryAsForm();

    ITeslaDatasource teslaDs = (ITeslaDatasource)ds;

    String fieldName = (String)getRequest().getAttributes().get("field");
    if (fieldName != null) {
        if ("regions".equals(fieldName))
            return teslaDs.getMetadata().getRegions();
        else if ("count".equals(fieldName)) {
            DBCursor cursor = getData().getCursor();
            cursor.sort(null);
            return ((Number)cursor.explain().get("n")).intValue();
        }
        else if ("forecastsDiff".equals(fieldName))
            return getForecastsAndSnapshots();
        else if ("stations".equals(fieldName))
            return teslaDs.getMetadata().getToposPerSubstation().keySet();
        else if ("explain".equals(fieldName))
            return new JsonRepresentation(((MongoDataset)getData()).explain().toString());
        else if ("countries".equals(fieldName))
            return teslaDs.getMetadata().getCountries();
        else if ("topos".equals(fieldName)) {
            //warn this is potentially a large result - must implement a finer query mechanism (per substation id)
            String stationId = queryForm.getFirstValue("topoId", true);
            if (stationId == null) {
                return teslaDs.getMetadata().getToposPerSubstation();
            }
            else return teslaDs.getMetadata().getToposPerSubstation().get(stationId).keySet();
        }

        else return null;
    } else
        return super.getRepresentation();
}