org.restlet.resource.Post Java Examples

The following examples show how to use org.restlet.resource.Post. 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: AgentsAgidObjects.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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
Source File: StorageNotifyResource.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: StaticFlowEntryDeleteResource.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: MembersResource.java    From floodlight_with_topoguard with 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 #5
Source File: PoolsResource.java    From floodlight_with_topoguard with 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 #6
Source File: VipsResource.java    From floodlight_with_topoguard with 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 #7
Source File: MonitorsResource.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@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 File: FirewallRulesResource.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: FirewallResource.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: AdminRestletResource.java    From uReplicator with 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 #11
Source File: DeploymentCollectionResource.java    From FoxBPM with 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 #12
Source File: ObjectsOidActionsAid.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #13
Source File: CalendarTypeCollectionResource.java    From FoxBPM with 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 #14
Source File: AgentsAgidObjectsDelete.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #15
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 #16
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 #17
Source File: IndexResource.java    From ontopia with 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 #18
Source File: TopicMapReloadResource.java    From ontopia with 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 #19
Source File: IndexResource.java    From ontopia with 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 #20
Source File: CalendarPartCollectionResource.java    From FoxBPM with 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 #21
Source File: ControllerRoleResource.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: NoOp.java    From floodlight_with_topoguard with 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
Source File: StaticFlowEntryPusherResource.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
/**
 * 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
Source File: SearchSparql.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #25
Source File: TicketResource.java    From springboot-shiro-cas-mybatis with 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 #26
Source File: IteslaDataListResource.java    From ipst with 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 #27
Source File: ITeslaRules.java    From ipst with 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 #28
Source File: IteslaRefCIMResource.java    From ipst with 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 #29
Source File: WorkspaceServerResource.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
@Post("text/plain")
public void dispatch(final String filePath) throws ResourceNotFoundException, LockedResourceException {
    checkArgument(!isNullOrEmpty(filePath), "filePath is null or empty");
    final IRepositoryFileStore fileStore = toFileStore(filePath);
    repositoryNotifier.dispatch(WorkspaceAPIEvent.valueOf(action), fileStore);
}
 
Example #30
Source File: GetDisambiguation.java    From AGDISTIS with GNU Affero General Public License v3.0 4 votes vote down vote up
@Post
public String postText(Representation entity) throws IOException, Exception {
	NEDAlgo_HITS agdistis = null;
	try {
		agdistis = new NEDAlgo_HITS();
	} catch (IOException e) {
		log.error(
				"Can not load index due to either wrong properties in agdistis.properties or missing index at location",
				e);
		System.exit(0);
	}
	log.info("Start working on Request for AGDISTIS");
	String result = "";
	String text = "";
	String type = "";
	InputStream input = entity.getStream();
	// here the inputStream is duplicated due to it can be read only once.
	// Therefore, we do it for checking if the input is from gerbil or not.
	byte[] byteArray = IOUtils.toByteArray(input);
	InputStream input1 = new ByteArrayInputStream(byteArray);
	InputStream input2 = new ByteArrayInputStream(byteArray);

	String string = IOUtils.toString(input1);
	// Parse the given representation and retrieve data
	Form form = new Form(string);
	text = form.getFirstValue("text");
	type = form.getFirstValue("type");
	log.info("text: " + text);
	log.info("type: " + type);

	if (text == null) {
		result = NIFGerbil(input2, agdistis); // This part is created to
		// work
		// along with GERBIL, because
		// GERBIL only sends the NIF
		// files without taking care of
		// more than one parameter. So,
		// GERBIL is not capable to send
		// the nif in the text parameter
		// making
		// AGDISTIS?type=nif&text= not
		// work.
		return result;
	}
	if (type == null) {
		type = "agdistis";
	}

	if (type.equals("agdistis")) {
		return standardAG(text, agdistis); // This type is the standard
											// and in case the user
											// doesn't send the type
											// parameter, it is
											// considered as the main
											// one(e.g
											// AGDISTIS?type=agdistis&text=<entity>Barack
											// Obama</entity>).

	} else if (type.equals("nif")) {
		return NIFType(text, agdistis); // This type is for AGDISTIS
										// works beyond the GERBIL, this
										// part is in case of user wants
										// to check just a certain NIF
										// file(e.g
										// AGDISTIS?type=nif&text=@prefix....)

	} else if (type.equals("candidates")) {
		return candidateType(text, agdistis); // Here is to let us know
												// about all candidates
												// for each mention and
												// its respective
												// HITS/PageRank score.
	} else {
		return "ERROR";
	}
}