Java Code Examples for org.restlet.resource.Post

The following examples show how to use org.restlet.resource.Post. These examples are extracted from open source projects. 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
/**
 * Register the IoT object(s) of the underlying eco-system e.g. devices, VA service.
 * 
 * @param entity Representation of the incoming JSON. List of IoT thing descriptions that are to be registered 
 * (from request).
 * @return All VICINITY identifiers of objects registered under VICINITY Gateway by this call.
 * 
 */
@Post("json")
public Representation accept(Representation entity) {
	
	String attrAgid = getAttribute(ATTR_AGID);
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	XMLConfiguration config = (XMLConfiguration) getContext().getAttributes().get(Api.CONTEXT_CONFIG);
	
	
	if (attrAgid == null){
		logger.info("AGID: " + attrAgid + " Invalid Agent ID.");
		throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, 
				"Invalid Agent ID.");
	}
	
	if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
		logger.info("AGID: " + attrAgid + " Invalid object descriptions.");
		
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid object descriptions");
	}
	
	return storeObjects(entity, logger, config);
}
 
Example 2
/**
 * 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 3
/**
 * 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 4
/**
 * Deletes - unregisters the IoT object(s).
 * 
 * @param entity Representation of the incoming JSON. List of IoT thing descriptions that are to be removed 
 * (taken from request).
 * @return Notification of success or failure.
 * 
 */
@Post("json")
public Representation accept(Representation entity) {
	
	String attrAgid = getAttribute(ATTR_AGID);
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	XMLConfiguration config = (XMLConfiguration) getContext().getAttributes().get(Api.CONTEXT_CONFIG);
	
	if (attrAgid == null){
		logger.info("AGID: " + attrAgid + " Invalid Agent ID.");
		throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, 
				"Invalid Agent ID.");
	}
	
	if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
		logger.info("AGID: " + attrAgid + " Invalid object descriptions.");
		
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid object descriptions");
	}
	
	return deleteObjects(entity, logger, config);
}
 
Example 5
/**
 * 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 6
Source Project: uReplicator   Source File: AdminRestletResource.java    License: Apache License 2.0 6 votes vote down vote up
@Post
public Representation post() {
  final String opt = (String) getRequest().getAttributes().get("opt");
  JSONObject responseJson = new JSONObject();
  if ("disable_autobalancing".equalsIgnoreCase(opt)) {
    _helixMirrorMakerManager.disableAutoBalancing();
    LOGGER.info("Disabled autobalancing!");
    responseJson.put("opt", "disable_autobalancing");
    responseJson.put("auto_balancing", _helixMirrorMakerManager.isAutoBalancingEnabled());
  } else if ("enable_autobalancing".equalsIgnoreCase(opt)) {
    _helixMirrorMakerManager.enableAutoBalancing();
    LOGGER.info("Enabled autobalancing!");
    responseJson.put("opt", "enable_autobalancing");
    responseJson.put("auto_balancing", _helixMirrorMakerManager.isAutoBalancingEnabled());
  } else {
    LOGGER.info("No valid input!");
    responseJson.put("opt", "No valid input!");
  }
  return new StringRepresentation(responseJson.toJSONString());
}
 
Example 7
@Put
@Post
public LBMonitor createMonitor(String postData) {

    LBMonitor monitor=null;
    try {
        monitor=jsonToMonitor(postData);
    } catch (IOException e) {
        log.error("Could not parse JSON {}", e.getMessage());
    }
    
    ILoadBalancerService lbs =
            (ILoadBalancerService)getContext().getAttributes().
                get(ILoadBalancerService.class.getCanonicalName());
    
    String monitorId = (String) getRequestAttributes().get("monitor");
    if (monitorId != null)
        return lbs.updateMonitor(monitor);
    else
        return lbs.createMonitor(monitor);
}
 
Example 8
Source Project: floodlight_with_topoguard   Source File: VipsResource.java    License: Apache License 2.0 6 votes vote down vote up
@Put
@Post
public LBVip createVip(String postData) {

    LBVip vip=null;
    try {
        vip=jsonToVip(postData);
    } catch (IOException e) {
        log.error("Could not parse JSON {}", e.getMessage());
    }
    
    ILoadBalancerService lbs =
            (ILoadBalancerService)getContext().getAttributes().
                get(ILoadBalancerService.class.getCanonicalName());
    
    String vipId = (String) getRequestAttributes().get("vip");
    if (vipId != null)
        return lbs.updateVip(vip);
    else
        return lbs.createVip(vip);
}
 
Example 9
Source Project: floodlight_with_topoguard   Source File: PoolsResource.java    License: Apache License 2.0 6 votes vote down vote up
@Put
@Post
public LBPool createPool(String postData) {        

    LBPool pool=null;
    try {
        pool=jsonToPool(postData);
    } catch (IOException e) {
        log.error("Could not parse JSON {}", e.getMessage());
    }
    
    ILoadBalancerService lbs =
            (ILoadBalancerService)getContext().getAttributes().
                get(ILoadBalancerService.class.getCanonicalName());
    
    String poolId = (String) getRequestAttributes().get("pool");
    if (poolId != null)
        return lbs.updatePool(pool);
    else        
        return lbs.createPool(pool);
}
 
Example 10
Source Project: floodlight_with_topoguard   Source File: MembersResource.java    License: Apache License 2.0 6 votes vote down vote up
@Put
@Post
public LBMember createMember(String postData) {        

    LBMember member=null;
    try {
        member=jsonToMember(postData);
    } catch (IOException e) {
        log.error("Could not parse JSON {}", e.getMessage());
    }
    
    ILoadBalancerService lbs =
            (ILoadBalancerService)getContext().getAttributes().
                get(ILoadBalancerService.class.getCanonicalName());
    
    String memberId = (String) getRequestAttributes().get("member");
    if (memberId != null)
        return lbs.updateMember(member);
    else        
        return lbs.createMember(member);
}
 
Example 11
@Post
@LogMessageDoc(level="ERROR",
    message="Error deleting flow mod request: {request}",
    explanation="An invalid delete request was sent to static flow pusher",
    recommendation="Fix the format of the static flow mod request")
public String del(String fmJson) {
    IStorageSourceService storageSource =
            (IStorageSourceService)getContext().getAttributes().
                get(IStorageSourceService.class.getCanonicalName());
    String fmName = null;
    if (fmJson == null) {
        return "{\"status\" : \"Error! No data posted.\"}";
    }
    try {
        fmName = StaticFlowEntries.getEntryNameFromJson(fmJson);
        if (fmName == null) {
            return "{\"status\" : \"Error deleting entry, no name provided\"}";
        }
    } catch (IOException e) {
        log.error("Error deleting flow mod request: " + fmJson, e);
        return "{\"status\" : \"Error deleting entry, see log for details\"}";
    }

    storageSource.deleteRowAsync(StaticFlowEntryPusher.TABLE_NAME, fmName);
    return "{\"status\" : \"Entry " + fmName + " deleted\"}";
}
 
Example 12
@Post("json")
public Map<String,Object> notify(String entity) throws Exception {
    List<StorageSourceNotification> notifications = null;
    ObjectMapper mapper = new ObjectMapper();
    notifications = 
        mapper.readValue(entity, 
                new TypeReference<List<StorageSourceNotification>>(){});
    
    IStorageSourceService storageSource = 
        (IStorageSourceService)getContext().getAttributes().
            get(IStorageSourceService.class.getCanonicalName());
    storageSource.notifyListeners(notifications);
    
    HashMap<String, Object> model = new HashMap<String,Object>();
    model.put("output", "OK");
    return model;
}
 
Example 13
/**
 * Takes a Firewall Rule string in JSON format and parses it into
 * our firewall rule data structure, then adds it to the firewall.
 * @param fmJson The Firewall rule entry in JSON format.
 * @return A string status message
 */
@Post
public String store(String fmJson) {
    IFirewallService firewall =
            (IFirewallService)getContext().getAttributes().
            get(IFirewallService.class.getCanonicalName());

    FirewallRule rule;
    try {
        rule = jsonToFirewallRule(fmJson);
    } catch (IOException e) {
        log.error("Error parsing firewall rule: " + fmJson, e);
        return "{\"status\" : \"Error! Could not parse firewall rule, see log for details.\"}";
    }
    String status = null;
    if (checkRuleExists(rule, firewall.getRules())) {
        status = "Error! A similar firewall rule already exists.";
        log.error(status);
    	return ("{\"status\" : \"" + status + "\"}");
    } else {
        // add rule to firewall
        firewall.addRule(rule);
        status = "Rule added";
    	return ("{\"status\" : \"" + status + "\", \"rule-id\" : \""+ Integer.toString(rule.ruleid) + "\"}");
    }
}
 
Example 14
/**
 * Allows setting of subnet mask
 * @param fmJson The Subnet Mask in JSON format.
 * @return A string status message
 */
@Post
public String handlePost(String fmJson) {
    IFirewallService firewall =
            (IFirewallService)getContext().getAttributes().
            get(IFirewallService.class.getCanonicalName());

    String newMask;
    try {
        newMask = jsonExtractSubnetMask(fmJson);
    } catch (IOException e) {
        log.error("Error parsing new subnet mask: " + fmJson, e);
        return "{\"status\" : \"Error! Could not parse new subnet mask, see log for details.\"}";
    }
    firewall.setSubnetMask(newMask);
    return ("{\"status\" : \"subnet mask set\"}");
}
 
Example 15
Source Project: FoxBPM   Source File: DeploymentCollectionResource.java    License: Apache License 2.0 6 votes vote down vote up
@Post
public String deploy(Representation entity){
	InputStream input = null;
	String processDefinitionKey = null;
	try {
		input = entity.getStream();
		if(input == null){
			throw new FoxbpmPluginException("请求中必须包含文件流", "Rest服务");
		}
		ModelService modelService = FoxBpmUtil.getProcessEngine().getModelService();
		ZipInputStream zip = new ZipInputStream(input);
		DeploymentBuilder deploymentBuilder = modelService.createDeployment();
		deploymentBuilder.addZipInputStream(zip);
		Deployment deployment = deploymentBuilder.deploy();
		setStatus(Status.SUCCESS_CREATED);
		ProcessDefinitionQuery processDefinitionQuery = modelService.createProcessDefinitionQuery();
		processDefinitionKey = processDefinitionQuery.deploymentId(deployment.getId()).singleResult().getId();
	} catch (Exception e) {
		if (e instanceof FoxBPMException) {
			throw (FoxBPMException) e;
		}
		throw new FoxBPMException(e.getMessage(), e);
	}		
	return processDefinitionKey;
}
 
Example 16
Source Project: FoxBPM   Source File: CalendarTypeCollectionResource.java    License: Apache License 2.0 6 votes vote down vote up
@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 17
/**
 * Queries the network as if it were the VICINITY triple store of all objects’ data.
 * 
 * @param query The SPARQL query as JSON.
 */
@Post("json")
public Representation accept(Representation entity) {
	String callerOid = getRequest().getChallengeResponse().getIdentifier();
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	
	// get the query in body
	String sparqlQuery = getRequestBody(entity, logger);
	
	// and perhaps parameters
	Map<String, String> queryParams = getQuery().getValuesMap();
	
	return performSearch(callerOid, sparqlQuery, queryParams);
}
 
Example 18
Source Project: springboot-shiro-cas-mybatis   Source File: TicketResource.java    License: MIT License 5 votes vote down vote up
/**
 * Accept credentials and attempt to create the TGT.
 *
 * @param entity the entity
 */
@Post
public final void acceptRepresentation(final Representation entity)  {
    LOGGER.debug("Obtaining credentials...");
    final Credential c = obtainCredentials();

    if (c == null) {
        LOGGER.trace("No credentials could be obtained from the REST entity representation");
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid or missing credentials");
        return;
    }

    try (final Formatter fmt = new Formatter()) {
        final TicketGrantingTicket ticketGrantingTicketId = this.centralAuthenticationService.createTicketGrantingTicket(c);
        getResponse().setStatus(determineStatus());
        final Reference ticketReference = getRequest().getResourceRef().addSegment(ticketGrantingTicketId.getId());
        getResponse().setLocationRef(ticketReference);

        fmt.format("<!DOCTYPE HTML PUBLIC \\\"-//IETF//DTD HTML 2.0//EN\\\"><html><head><title>");
        fmt.format("%s %s", getResponse().getStatus().getCode(), getResponse().getStatus().getDescription())
           .format("</title></head><body><h1>TGT Created</h1><form action=\"%s", ticketReference)
           .format("\" method=\"POST\">Service:<input type=\"text\" name=\"service\" value=\"\">")
           .format("<br><input type=\"submit\" value=\"Submit\"></form></body></html>");

        getResponse().setEntity(fmt.toString(), MediaType.TEXT_HTML);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    }
}
 
Example 19
Source Project: ipst   Source File: IteslaDataListResource.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Post("form:html")
public Object postCimDirectory(Form queryForm) throws IOException {

    if (queryForm == null)
        queryForm = getRequest().getOriginalRef().getQueryAsForm();

    if (dataId == null || storeId == null) {
        throw new IllegalArgumentException("Missing datasource or store id");
    } else {

        ITeslaDatastore store = (ITeslaDatastore) getApplication().getDataService().getDataStore(storeId);
        if (store == null) {
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            return "Datastore does not exist: " + storeId;
        }

        ITeslaDatasource ds = store.getDataSource(dataId);
        if (ds == null) {
            ds = store.createDataSource(dataId);
        }
        boolean parallel = queryForm.getFirstValue("parallel") != null
                ? Boolean.valueOf(queryForm.getFirstValue("parallel")) : true;
        CimHistoImporter importer = new CimHistoImporter(ds);
        importer.addCim(new File(queryForm.getFirstValue("dir")), parallel);

        ds.persistState();
    }

    return null;
}
 
Example 20
Source Project: ipst   Source File: ITeslaRules.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Post("json")
public void putRule(JSONObject rule) throws Exception {

    String workflowId = rule.getString("workflowId");

    if (datasource == null) {
        //create datasource if needed
        datasource = getApplication().getDataService().getDataStore(storeId).createDataSource(dataId);
    }

    if (algoType == null || contingencyId == null || workflowId == null || indexType == null) {
        throw new IllegalArgumentException("Cannot create/update rule ; incomplete identifier (algo="+algoType+" ; cont="+contingencyId+" ; workflow="+workflowId+" ; indexType="+indexType+" )");
    }

    Map<String, Object> query = new HashMap();
    query.put("algoType", algoType);
    query.put("contingencyId", contingencyId);
    query.put("indexType", indexType);

    String[] headers = new String[] {"algoType", "contingencyId", "indexType", "workflowId", "quality", "treeSize", "criticality", "tree"};
    Object[] values = new Object [] {
            algoType,
            contingencyId,
            indexType,
            workflowId,
            rule.getDouble("quality"),
            rule.getInt("treeSize"),
            rule.getDouble("criticality"),
            rule.getJSONObject("tree").toString()
    };

    datasource.updateData(query, headers, values);

    datasource.persistState();

}
 
Example 21
Source Project: ipst   Source File: IteslaRefCIMResource.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Put
@Post
public void setReferenceCIM(String referenceCimPath) throws IOException {
    if (datasource == null) {
        //create datasource if needed
        datasource = getApplication().getDataService().getDataStore(storeId).createDataSource(dataId);
    }

    ((ITeslaDatasource)datasource).setLatestCim(referenceCimPath);
    ((ITeslaDatasource)datasource).setLatestNetwork(CimHistoImporter.readCim(new File(referenceCimPath)));
}
 
Example 22
Source Project: floodlight_with_topoguard   Source File: NoOp.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Does nothing and returns 200 OK with a status message
 * 
 * @return status: ok
 */
@Get
@Put
@Post
@Delete
public String noOp(String postdata) {
    setStatus(Status.SUCCESS_OK);
    return "{\"status\":\"ok\"}";
}
 
Example 23
/**
 * Takes a Static Flow Pusher string in JSON format and parses it into
 * our database schema then pushes it to the database.
 * @param fmJson The Static Flow Pusher entry in JSON format.
 * @return A string status message
 */
@Post
@LogMessageDoc(level="ERROR",
    message="Error parsing push flow mod request: {request}",
    explanation="An invalid request was sent to static flow pusher",
    recommendation="Fix the format of the static flow mod request")
public String store(String fmJson) {
    IStorageSourceService storageSource =
            (IStorageSourceService)getContext().getAttributes().
                get(IStorageSourceService.class.getCanonicalName());

    Map<String, Object> rowValues;
    try {
        rowValues = StaticFlowEntries.jsonToStorageEntry(fmJson);
        String status = null;
        if (!checkMatchIp(rowValues)) {
            status = "Warning! Pushing a static flow entry that matches IP " +
                    "fields without matching for IP payload (ether-type 2048) will cause " +
                    "the switch to wildcard higher level fields.";
            log.error(status);
        } else {
            status = "Entry pushed";
        }
        storageSource.insertRowAsync(StaticFlowEntryPusher.TABLE_NAME, rowValues);
        return ("{\"status\" : \"" + status + "\"}");
    } catch (IOException e) {
        log.error("Error parsing push flow mod request: " + fmJson, e);
        return "{\"status\" : \"Error! Could not parse flod mod, see log for details.\"}";
    }
}
 
Example 24
@Post("json")
@LogMessageDoc(level="WARN",
               message="Invalid role value specified in REST API to " +
                  "set controller role",
               explanation="An HA role change request was malformed.",
               recommendation=LogMessageDoc.CHECK_CONTROLLER)
public void setRole(RoleInfo roleInfo) {
    //Role role = Role.lookupRole(roleInfo.getRole());
    Role role = null;
    try {
        role = Role.valueOf(roleInfo.getRole().toUpperCase());
    }
    catch (IllegalArgumentException e) {
        // The role value in the REST call didn't match a valid
        // role name, so just leave the role as null and handle
        // the error below.
    }
    if (role == null) {
        log.warn ("Invalid role value specified in REST API to " +
        		  "set controller role");
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid role value");
        return;
    }
    String roleChangeDescription = roleInfo.getRoleChangeDescription();
    if (roleChangeDescription == null)
        roleChangeDescription = "<none>";

    IFloodlightProviderService floodlightProvider =
            (IFloodlightProviderService)getContext().getAttributes().
                get(IFloodlightProviderService.class.getCanonicalName());

    floodlightProvider.setRole(role, roleChangeDescription);
}
 
Example 25
Source Project: ontopia   Source File: TopicMapReloadResource.java    License: Apache License 2.0 5 votes vote down vote up
@Post
public void reload() {
	TopicMapReferenceIF reference = getTopicMapReference();
	
	if (reference.isOpen()) {
		reference.close();
		reference.open();
	}
}
 
Example 26
Source Project: ontopia   Source File: IndexResource.java    License: Apache License 2.0 5 votes vote down vote up
@Post("json:json")
public Collection<?> getOccurrences(Map<String, String> data) {
	if (data == null) {
		throw OntopiaRestErrors.EMPTY_ENTITY.build();
	}
	return getOccurrences(data.get("value"), data.get("datatype"));
}
 
Example 27
Source Project: ontopia   Source File: IndexResource.java    License: Apache License 2.0 5 votes vote down vote up
@Post("form:json")
public Collection<?> getOccurrences(Form data) {
	if (data == null) {
		throw OntopiaRestErrors.EMPTY_ENTITY.build();
	}
	return getOccurrences(data.getFirstValue("value"), data.getFirstValue("datatype"));
}
 
Example 28
Source Project: FoxBPM   Source File: CalendarPartCollectionResource.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
	@Post
	public void addCalendarPart(Representation entity) {
		// 获取参数
//		String id = getAttribute("id");
		Map<String, String> paramsMap = getRequestParams(entity);
		String id = URLDecoder.decode(paramsMap.get("id"));
		String amorpm = URLDecoder.decode(paramsMap.get("amorpm"));
		String starttime = URLDecoder.decode(paramsMap.get("starttime"));
		String endtime = URLDecoder.decode(paramsMap.get("endtime"));
		String ruleid = URLDecoder.decode(paramsMap.get("ruleid"));
		if (StringUtil.isNotEmpty(id)) {
			CalendarPartEntity calendarPartEntity = new CalendarPartEntity(id);
			if (StringUtil.isNotEmpty(amorpm)) {
				calendarPartEntity.setAmorpm(Integer.valueOf(amorpm));
			}
			if (StringUtil.isNotEmpty(starttime)) {
				calendarPartEntity.setStarttime(starttime);
			}
			if (StringUtil.isNotEmpty(endtime)) {
				calendarPartEntity.setEndtime(endtime);
			}
			if (StringUtil.isNotEmpty(ruleid)) {
				calendarPartEntity.setRuleid(ruleid);
			}
			// 获取服务
			WorkCalendarService workCalendarService = ProcessEngineManagement.getDefaultProcessEngine().getService(WorkCalendarService.class);
			// 构造用户信息
			workCalendarService.addCalendarPart(calendarPartEntity);
		}
	}
 
Example 29
/**
 * Used by the Agent / Adapter to post a semantic seaqrch query.
 * 
 * @param entity The query packaged as JSON entity.
 * @return Response after the search.
 */
@Post("json")
public Representation accept(Representation entity) {
	
	String callerOid = getRequest().getChallengeResponse().getIdentifier();
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	
	// get the query in body
	String semanticQuery = getRequestBody(entity, logger);
	
	// and perhaps parameters
	Map<String, String> queryParams = getQuery().getValuesMap();
	
	return performSearch(callerOid, semanticQuery, queryParams);
}
 
Example 30
@Override
@Post
public Representation post(Representation entity) {
  final String topicName = (String) getRequest().getAttributes().get("topicName");
  Form queryParams = getRequest().getResourceRef().getQueryAsForm();
  String srcCluster = queryParams.getFirstValue("src");
  String dstCluster = queryParams.getFirstValue("dst");

  LOGGER.info("Received request to whitelist topic {} from {} to {} on uReplicator ",
      topicName, srcCluster, dstCluster);

  // TODO: validate src->dst combination
  if (!isValidPipeline(srcCluster, dstCluster)) {
    LOGGER.warn(
        "Failed to whitelist topic {} on uReplicator because of not valid pipeline from {} to {}",
        topicName, srcCluster, dstCluster);
    return getResponseJsonStringRepresentation(Status.CLIENT_ERROR_NOT_FOUND,
        String.format(
            "Failed to whitelist topic %s on uReplicator because of not valid pipeline from %s to %s",
            topicName, srcCluster, dstCluster));
  }

  // Check if topic in source cluster
  TopicPartition srcTopicPartitionInfo = _clusterToObserverMap.get(srcCluster)
      .getTopicPartitionWithRefresh(topicName);
  LOGGER.info("Source topicPartitionInfo: {}", srcTopicPartitionInfo);
  if (srcTopicPartitionInfo == null) {
    LOGGER
        .warn("Failed to whitelist topic {} on uReplicator because of not exists in src cluster",
            topicName);
    return getResponseJsonStringRepresentation(Status.CLIENT_ERROR_NOT_FOUND,
        String.format(
            "Failed to whitelist new topic: %s, it's not existed in source Kafka cluster!",
            topicName));
  }

  // Check if topic in destination cluster
  TopicPartition dstTopicPartitionInfo = _clusterToObserverMap.get(dstCluster)
      .getTopicPartitionWithRefresh(topicName);
  LOGGER.info("Destination topicPartitionInfo: {}", dstTopicPartitionInfo);
  if (dstTopicPartitionInfo == null) {
    LOGGER
        .warn("Failed to whitelist topic {} on uReplicator because of not exists in dst cluster",
            topicName);
    return getResponseJsonStringRepresentation(Status.CLIENT_ERROR_NOT_FOUND,
        String.format(
            "Failed to whitelist new topic: %s, it's not existed in destination Kafka cluster!",
            topicName));
  }
  _helixMirrorMakerManager.updateCurrentStatus();
  String pipeline = ControllerUtils.getPipelineName(srcCluster, dstCluster);
  if (_helixMirrorMakerManager.isTopicPipelineExisted(topicName, pipeline)) {
    LOGGER.info("Topic {} already on uReplicator in pipeline {}", topicName, pipeline);
    return getResponseJsonStringRepresentation(Status.SUCCESS_OK,
        String.format("Failed to add new topic: %s from: %s to: %s, it is already existed!",
            topicName, srcCluster, dstCluster));
  } else {
    try {
      _helixMirrorMakerManager.addTopicToMirrorMaker(srcTopicPartitionInfo.getTopic(),
          srcTopicPartitionInfo.getPartition(), srcCluster, dstCluster, pipeline);
      LOGGER.info("Successfully whitelist the topic {} from {} to {}", topicName, srcCluster,
          dstCluster);
      return getResponseJsonStringRepresentation(Status.SUCCESS_OK,
          String.format("Successfully add new topic: %s from: %s to: %s",
              srcTopicPartitionInfo.getTopic(), srcCluster, dstCluster));
    } catch (Exception e) {
      LOGGER.info("Failed to whitelist the topic {} from {} to {} due to exception {}",
          topicName, srcCluster, dstCluster, e);
      return getResponseJsonStringRepresentation(Status.SERVER_ERROR_INTERNAL,
          String.format("Failed add new topic: %s from: %s to: %s due to exception: %s",
              srcTopicPartitionInfo.getTopic(), srcCluster, dstCluster, e.toString()));
    }
  }
}