下面列出了org.osgi.framework.dto.ServiceReferenceDTO#org.restlet.representation.Representation 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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));
}
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;
}
@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;
}
/**
* 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;
*/
}
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;
}
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 );
}
}
};
}
/**
* 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);
}
/**
* 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();
}
}
/**
* 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());
}
/**
* 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);
}
@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.");
}
}
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());
}
}
@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;
}
/**
* 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);
}
@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());
}
}
@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;
}
@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();
}
@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);
}
}
/**
* Update the thing descriptions of objects registered under the Agent. This will delete the old records and
* replace them with new ones.
*
* @param json Representation of the incoming JSON. List of IoT thing descriptions that are to be updated
* (from request).
* @return The list of approved devices to be registered in agent configuration. Approved devices means only
* devices, that passed the validation in semantic repository and their instances were created.
*/
public Representation heavyweightUpdate(Representation json) {
if (json == null) {
logger.warning("Error when updating objects under local agent. JSON with TDs is null.");
return null;
}
return nmConnector.heavyweightUpdate(json);
}
/**
* Update the thing descriptions of objects registered under the Agent. This will only change the required fields.
*
* @param json Representation of the incoming JSON. List of IoT thing descriptions that are to be updated
* (from request).
* @return The list of approved devices to be registered in agent configuration. Approved devices means only
* devices, that passed the validation in semantic repository and their instances were created.
*/
public Representation lightweightUpdate(Representation json){
if (json == null) {
logger.warning("Error when updating objects under local agent. JSON with TDs is null.");
return null;
}
return nmConnector.lightweightUpdate(json);
}
/**
* Deletes - unregisters the IoT object(s).
*
* @param json Representation of the incoming JSON. List of IoT thing descriptions that are to be removed
* (taken from request).
* @return Notification of success or failure.
*/
public Representation deleteObjects(Representation json){
if (json == null) {
logger.warning("Error when deleting objects under local agent. JSON with TDs is null.");
return null;
}
return nmConnector.deleteObjects(json);
}
@Delete
public Representation delete() {
final String opt = (String) getRequest().getAttributes().get("opt");
JSONObject responseJson = new JSONObject();
if ("worker_number_override".equalsIgnoreCase(opt)) {
Form queryParams = getRequest().getResourceRef().getQueryAsForm();
String routeString = queryParams.getFirstValue("route", true);
if (StringUtils.isEmpty(routeString)) {
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
responseJson.put("status", Status.CLIENT_ERROR_BAD_REQUEST.getCode());
responseJson.put("message", String.format("missing parameter route"));
} else {
if (_helixMirrorMakerManager.getRouteWorkerOverride().containsKey(routeString)) {
_helixMirrorMakerManager.updateRouteWorkerOverride(routeString, -1);
responseJson.put("worker_number_override", _helixMirrorMakerManager.getRouteWorkerOverride());
responseJson.put("status", Status.SUCCESS_OK.getCode());
} else {
responseJson.put("message", String.format("route override not exists"));
responseJson.put("status", Status.SUCCESS_OK.getCode());
}
}
} else {
LOGGER.info("No valid input!");
responseJson.put("opt", "No valid input!");
}
return new StringRepresentation(responseJson.toJSONString());
}
@Override
public Representation post(Representation entity) {
String zkPath = getZKPath();
try {
JsonParameters jsonParameters = new JsonParameters(entity);
String command = jsonParameters.getCommand();
ZkClient zkClient =
(ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
if (command.equalsIgnoreCase(JsonParameters.ZK_DELETE_CHILDREN)) {
List<String> childNames = zkClient.getChildren(zkPath);
if (childNames != null) {
for (String childName : childNames) {
String childPath = zkPath.equals("/") ? "/" + childName : zkPath + "/" + childName;
zkClient.deleteRecursively(childPath);
}
}
} else {
throw new HelixException("Unsupported command: " + command + ". Should be one of ["
+ JsonParameters.ZK_DELETE_CHILDREN + "]");
}
getResponse().setStatus(Status.SUCCESS_OK);
} catch (Exception e) {
getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e),
MediaType.APPLICATION_JSON);
getResponse().setStatus(Status.SUCCESS_OK);
LOG.error("Error in post zkPath: " + zkPath, e);
}
return null;
}
public JsonArray parseThingDescriptionsFromRepresentation(Representation tds) {
JsonObject json = null;
try {
json = readJsonObject(tds.getText());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (json == null) {
logger.warning("Can't parse representation.");
return null;
}
JsonArray thingDescriptions = null;
JsonObject message = json.getJsonObject("message");
if (message == null) {
thingDescriptions = json.getJsonArray("thingDescriptions");
} else {
thingDescriptions = message.getJsonArray("thingDescriptions");
}
if (thingDescriptions == null) {
logger.warning("Can't parse representation.");
return null;
}
return thingDescriptions;
}
@Delete
public Representation deleteAnalysisTask() {
Platform platform = Platform.getInstance();
AnalysisTaskService service = platform.getAnalysisRepositoryManager().getTaskService();
String analysisTaskId = getQueryValue("analysisTaskId");
AnalysisTask task = service.deleteAnalysisTask(analysisTaskId);
StringRepresentation rep = new StringRepresentation(task.getDbObject().toString());
rep.setMediaType(MediaType.APPLICATION_JSON);
getResponse().setStatus(Status.SUCCESS_OK);
return rep;
}
/**
* Gets topic partition in blacklist
*
* @return topic partition in blacklist
*/
@Override
@Get
public Representation get() {
Set<TopicPartition> blacklist = _helixMirrorMakerManager.getTopicPartitionBlacklist();
JSONObject result = new JSONObject();
result.put("blacklist", blacklist);
return new StringRepresentation(result.toJSONString());
}
private Representation entityHeaders( Representation representation, EntityState entityState )
{
representation.setModificationDate( java.util.Date.from( entityState.lastModified() ) );
representation.setTag( new Tag( "" + entityState.version() ) );
representation.setCharacterSet( CharacterSet.UTF_8 );
representation.setLanguages( Collections.singletonList( Language.ENGLISH ) );
return representation;
}
/**
* Creates a new ManagedResource in the RestManager.
*/
@SuppressWarnings("unchecked")
@Override
public synchronized void doPut(BaseSolrResource endpoint, Representation entity, Object json) {
if (json instanceof Map) {
String resourceId = ManagedEndpoint.resolveResourceId(endpoint.getRequest());
Map<String,String> info = (Map<String,String>)json;
info.put("resourceId", resourceId);
storeManagedData(applyUpdatesToManagedData(json));
} else {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Expected Map to create a new ManagedResource but received a "+json.getClass().getName());
}
// PUT just returns success status code with an empty body
}
private ZNRecord get(Client client, String url, ObjectMapper mapper) throws Exception {
Request request = new Request(Method.GET, new Reference(url));
Response response = client.handle(request);
Representation result = response.getEntity();
StringWriter sw = new StringWriter();
result.write(sw);
String responseStr = sw.toString();
Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);
ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class);
return record;
}
protected T fromRepresentation(final Representation r, final MediaType mediaType)
throws Exception {
if (xmlMediaType.includes(mediaType) ||
MediaType.APPLICATION_XML.includes(mediaType) ||
MediaType.TEXT_XML.includes(mediaType)) {
return reflector.beanFromXml(toObject(r, Document.class));
} else if (jsonMediaType.includes(mediaType)
|| MediaType.APPLICATION_JSON.includes(mediaType) || MediaType.TEXT_PLAIN.includes(mediaType)) {
return reflector.beanFromJSONObject(toObject(r, JSONObject.class));
}
throw new UnsupportedOperationException(mediaType
.toString());
}