org.restlet.data.Form Java Examples

The following examples show how to use org.restlet.data.Form. 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: JsonParameters.java    From helix with Apache License 2.0 6 votes vote down vote up
public JsonParameters(Form form) throws Exception {
  // get parameters in String format
  String jsonPayload = form.getFirstValue(JSON_PARAMETERS, true);
  if (jsonPayload == null || jsonPayload.isEmpty()) {
    _parameterMap = Collections.emptyMap();
  } else {
    _parameterMap = ClusterRepresentationUtil.JsonToMap(jsonPayload);
  }

  // get extra parameters in ZNRecord format
  ObjectMapper mapper = new ObjectMapper();
  String newIdealStateString = form.getFirstValue(NEW_IDEAL_STATE, true);

  if (newIdealStateString != null) {
    ZNRecord newIdealState =
        mapper.readValue(new StringReader(newIdealStateString), ZNRecord.class);
    _extraParameterMap.put(NEW_IDEAL_STATE, newIdealState);
  }

  String newStateModelString = form.getFirstValue(NEW_STATE_MODEL_DEF, true);
  if (newStateModelString != null) {
    ZNRecord newStateModel =
        mapper.readValue(new StringReader(newStateModelString), ZNRecord.class);
    _extraParameterMap.put(NEW_STATE_MODEL_DEF, newStateModel);
  }
}
 
Example #2
Source File: FormReader.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Reads all the parameters.
 * 
 * @return The form read.
 * @throws IOException
 *             If the parameters could not be read.
 */
public Form read() throws IOException {
    Form result = new Form();

    if (this.stream != null) {
        Parameter param = readNextParameter();

        while (param != null) {
            result.add(param);
            param = readNextParameter();
        }

        this.stream.close();
    }

    return result;
}
 
Example #3
Source File: FormUtils.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Parses a post into a given form.
 * 
 * @param form
 *            The target form.
 * @param post
 *            The posted form.
 * @param decode
 *            Indicates if the parameters should be decoded.
 */
public static void parse(Form form, Representation post, boolean decode) {
    if (post != null) {
        if (post.isAvailable()) {
            FormReader fr = null;

            try {
                fr = new FormReader(post, decode);
            } catch (IOException ioe) {
                Context.getCurrentLogger().log(Level.WARNING,
                        "Unable to create a form reader. Parsing aborted.",
                        ioe);
            }

            if (fr != null) {
                fr.addParameters(form);
            }
        } else {
            Context.getCurrentLogger()
                    .log(Level.FINE,
                            "The form wasn't changed as the given representation isn't available.");
        }
    }
}
 
Example #4
Source File: AbstractRestResource.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化分页处理
 */
protected void initPage() {
	Form queryForm = getQuery();
	Set<String> queryNames = queryForm.getNames();
	if (queryNames.contains(RestConstants.PAGE_START)) {
		if (queryNames.contains(RestConstants.PAGE_LENGTH)) {
			pageSize = StringUtil.getInt(getQueryParameter(RestConstants.PAGE_LENGTH, queryForm));
		}
		pageIndex = StringUtil.getInt(getQueryParameter(RestConstants.PAGE_START, queryForm)) / pageSize + 1;
	}
	
	if (queryNames.contains(RestConstants.PAGE_INDEX)) {
		pageIndex = StringUtil.getInt(getQueryParameter(RestConstants.PAGE_INDEX, queryForm));
	}
	if (queryNames.contains(RestConstants.PAGE_SIZE)) {
		pageSize = StringUtil.getInt(getQueryParameter(RestConstants.PAGE_SIZE, queryForm));
	}
}
 
Example #5
Source File: TicketResource.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Obtain credentials from the request.
 *
 * @return the credential
 */
protected Credential obtainCredentials() {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();
    final WebRequestDataBinder binder = new WebRequestDataBinder(c);
    final RestletWebRequest webRequest = new RestletWebRequest(getRequest());

    final Form form = new Form(getRequest().getEntity());
    logFormRequest(form);

    if (!form.isEmpty()) {
        binder.bind(webRequest);
        return c;
    }
    LOGGER.trace("Failed to bind the request to credentials. Resulting form is empty");
    return null;
}
 
Example #6
Source File: AbstractRestResource.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化分页处理
 */
protected void initPage() {
	Form queryForm = getQuery();
	Set<String> queryNames = queryForm.getNames();
	if (queryNames.contains(RestConstants.PAGE_START)) {
		if (queryNames.contains(RestConstants.PAGE_LENGTH)) {
			pageSize = StringUtil.getInt(getQueryParameter(RestConstants.PAGE_LENGTH, queryForm));
		}
		pageIndex = StringUtil.getInt(getQueryParameter(RestConstants.PAGE_START, queryForm)) / pageSize + 1;
	}
	
	if (queryNames.contains(RestConstants.PAGE_INDEX)) {
		pageIndex = StringUtil.getInt(getQueryParameter(RestConstants.PAGE_INDEX, queryForm));
	}
	if (queryNames.contains(RestConstants.PAGE_SIZE)) {
		pageSize = StringUtil.getInt(getQueryParameter(RestConstants.PAGE_SIZE, queryForm));
	}
}
 
Example #7
Source File: ITeslaDataResource.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected ColumnDescriptor[] subsetColumns(ColumnDescriptor[] columns, Form queryForm) {
    ColumnDescriptor[] cols = super.subsetColumns(columns, queryForm);

    for (int i=0;i<cols.length;i++) {
        ColumnDescriptor cd = cols[i];
        if (cd.getName().endsWith("_PP") && !(cd instanceof FunctionalColumn)) {
            cols[i] = new StrictlyPositive(cd.getName().substring(0, cd.getName().length()-1));
        } else if (cd.getName().endsWith("_PN") && !(cd instanceof FunctionalColumn)) {
            cols[i] = new StrictlyNegative(cd.getName().substring(0, cd.getName().length()-1));
        } else if (cd.getName().endsWith("_IP") && !(cd instanceof FunctionalColumn)) {
            cols[i] = new CurrentPowerRatio(cd.getName().substring(0, cd.getName().length()-3));
        }
    }

    return cols;
}
 
Example #8
Source File: AccessTokenServerResource.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
     * Handles the {@link Post} request. The client MUST use the HTTP "POST"
     * method when making access token requests. (3.2. Token Endpoint)
     * 
     * @param input
     *            HTML form formated token request per oauth-v2 spec.
     * @return JSON response with token or error.<br>
     * 			※Local OAuth ではResultRepresentation型のポインタを返す。<br>
     * 			getResult()=trueならアクセストークンが含まれている。アクセストークンはgetText()で取得する。<br>
     * 			getResult()=falseならエラー。アクセストークンは取得できない。<br>
     */
    public static Representation requestToken(Representation input)
            throws OAuthException, JSONException {
        getLogger().fine("Grant request");
        final Form params = new Form(input);

        final GrantType grantType = getGrantType(params);
        switch (grantType) {
        case authorization_code:
            getLogger().info("Authorization Code Grant");
            return doAuthCodeFlow(params);
//        case password:
//        	getLogger().info("Resource Owner Password Credentials Grant");
//            return doPasswordFlow(params);
//        case client_credentials:
//        	getLogger().info("Client Credentials Grantt");
//            return doClientFlow(params);
//        case refresh_token:
//        	getLogger().info("Refreshing an Access Token");
//            return doRefreshFlow(params);
        default:
            getLogger().warning("Unsupported flow: " + grantType);
            throw new OAuthException(OAuthError.unsupported_grant_type,
                    "Flow not supported", null);
        }
    }
 
Example #9
Source File: ITeslaStatsResource.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
@Get("csv")
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();
    char delimiter = queryForm.getFirstValue("delimiter", ",").charAt(0);

    return new CsvRepresentation(getStats(), true, delimiter);
}
 
Example #10
Source File: RequestUtil.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
public static Date getDate(Form form, String name) {
	Date value = null;
	if (form.getValues(name) != null) {

		String input = form.getValues(name);

		// this is zero time so we need to add that TZ indicator for
		if (input.endsWith("Z")) {
			input = input.substring(0, input.length() - 1) + "GMT-00:00";
		} else {
			int inset = 6;

			String s0 = input.substring(0, input.length() - inset);
			String s1 = input.substring(input.length() - inset, input.length());

			input = s0 + "GMT" + s1;
		}

		try {
			value = longDateFormat.parse(input);
		} catch (Exception e) {
			throw new FoxbpmPluginException("Failed to parse date " + input,"Rest服务");
		}
	}
	return value;
}
 
Example #11
Source File: TicketResource.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
private void logFormRequest(final Form form) {
    if (LOGGER.isDebugEnabled()) {
        final Set<String> pairs = new HashSet<String>();
        for (final String name : form.getNames()) {
            final StringBuilder builder = new StringBuilder();
            builder.append(name);
            builder.append(": ");
            if (!"password".equalsIgnoreCase(name)) {
                builder.append(form.getValues(name));
            } else {
                builder.append("*****");
            }
            pairs.add(builder.toString());
        }
        LOGGER.debug(StringUtils.join(pairs, ", "));
    }
}
 
Example #12
Source File: FlowGraphicPositionResource.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
@Get
public DataResult getPositionInfor() {
	Form query = getQuery();
	String processDefinitionId = getQueryParameter("processDefinitionId", query);
	if (StringUtil.isEmpty(processDefinitionId)) {
		throw new FoxbpmPluginException("流程定义唯一编号为空", "Rest服务");
	}
	ProcessEngine processEngine = FoxBpmUtil.getProcessEngine();
	ModelService modelService = processEngine.getModelService();
	Map<String, Map<String, Object>> positionInfor = modelService.getFlowGraphicsElementPositionById(processDefinitionId);
	Map<String, Object> resultData = new HashMap<String, Object>();
	resultData.put("positionInfor", positionInfor);
	DataResult result = new DataResult();
	result.setData(resultData);
	return result;
	
}
 
Example #13
Source File: OAuthServerResource.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Get request parameter "client_id".
 * 
 * @param params
 * @return
 * @throws OAuthException
 */
protected static Client getClient(Form params) throws OAuthException {
    // check clientId:
    String clientId = params.getFirstValue(CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        getLogger().warning("Could not find client ID");
        throw new OAuthException(OAuthError.invalid_request,
                "No client_id parameter found.", null);
    }
    Client client = clients.findById(clientId);
    getLogger().fine("Client = " + client);
    if (client == null) {
    	getLogger().warning("Need to register the client : " + clientId);
        throw new OAuthException(OAuthError.invalid_request,
                "Need to register the client : " + clientId, null);
    }

    return client;
}
 
Example #14
Source File: ChoicesResource.java    From open-rmbt with Apache License 2.0 6 votes vote down vote up
@Get("json")
public String request(final String entity) throws JSONException
{
    QueryParser qp = new QueryParser();
    Form parameters = getRequest().getResourceRef().getQueryAsForm();
    qp.parseQuery(parameters);
    
    List<String> fields = Arrays.asList(new String[]{"country_geoip"});
 
    final JSONObject answer = new JSONObject();
    final JSONArray countries = new JSONArray(queryDB("upper(msim.country)", "t.mobile_network_id", "mccmnc2name msim ON msim.uid", qp));
    final JSONArray provider = new JSONArray(queryDB("mprov.name", "t.mobile_provider_id", "provider mprov ON mprov.uid", qp));
    final JSONArray providerN = new JSONArray(queryDB("prov.name", "t.provider_id", "provider prov ON prov.uid", qp));
    
    
    
    answer.put("country_mobile", countries);
    answer.put("provider_mobile", provider);
    answer.put("provider", providerN);
    
    return answer.toString();
}
 
Example #15
Source File: FlowGraphicImgResource.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
@Get
public InputStream getFlowGraphicImg() {
	Form query = getQuery();
	String processInstanceId = getQueryParameter("processInstanceId", query);
	String processDefinitionKey = getQueryParameter("processDefinitionKey", query);
	// 获取引擎
	ProcessEngine processEngine = FoxBpmUtil.getProcessEngine();
	ModelService modelService = processEngine.getModelService();
	// 获取图片
	InputStream in = null;
	// 流程定义id
	String processDefinitionId = null;
	// 流程定义Id
	if (StringUtil.isEmpty(processInstanceId)) {
		// 流程定义Key
		if (StringUtil.isEmpty(processDefinitionKey)) {
			throw new FoxbpmPluginException("流程定义 编号为空", "Rest服务");
		}
		ProcessDefinition processDefinition = modelService.getLatestProcessDefinition(processDefinitionKey);
		if (null == processDefinition) {
			throw new FoxbpmPluginException("未找到流程定义:" + processDefinitionKey, "Rest服务");
		}
		processDefinitionId = processDefinition.getId();
	} else {
		ProcessInstanceQuery processInstanceQuery = processEngine.getRuntimeService().createProcessInstanceQuery();
		ProcessInstance processInstance = processInstanceQuery.processInstanceId(processInstanceId).singleResult();
		if (null == processInstance) {
			throw new FoxbpmPluginException("未找到流程定义:" + processInstanceId, "Rest服务");
		}
		processDefinitionId = processInstance.getProcessDefinitionId();
	}
	 
	in = modelService.GetFlowGraphicsImgStreamByDefId(processDefinitionId);
	return in;
}
 
Example #16
Source File: TaskCollectionResource.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
protected boolean validateUser() {
	HttpServletRequest request = ServletUtils.getRequest(getRequest());
	String userId = (String) request.getSession().getAttribute("userId");
	Form queryForm = getQuery();
	String assignee = getQueryParameter("assignee", queryForm);
	String processInstanceId = getQueryParameter("processInstanceId", queryForm);
	String candidateUser = getQueryParameter("candidateUser", queryForm);
	if (userId == null || (assignee == null && candidateUser == null && processInstanceId == null)
	        || (assignee != null && !userId.equals(assignee))
	        || (candidateUser != null && !userId.equals(candidateUser))) {
		setStatus(Status.CLIENT_ERROR_UNAUTHORIZED, "对应的请求无权访问!");
		return false;
	}
	return true;
}
 
Example #17
Source File: SignupResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public Form signup()
{
    Form form = new Form();
    form.set( "name", "Rickard" );
    form.set( "realName", "Rickard Öberg" );
    form.set( "password", "rickard" );
    form.set( "email", "rickard@polygene" );
    return form;
}
 
Example #18
Source File: FlowGraphicSvgResource.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
@Get
public DataResult getFlowGraphicImg() {
	Form query = getQuery();
	String processInstanceId = getQueryParameter("processInstanceId", query);
	String processDefinitionKey = getQueryParameter("processDefinitionKey", query);
	// 获取引擎
	ProcessEngine processEngine = FoxBpmUtil.getProcessEngine();
	ModelService modelService = processEngine.getModelService();
	// 流程定义id
	String processDefinitionId = null;
	// 流程定义Id
	if (StringUtil.isEmpty(processInstanceId)) {
		// 流程定义Key
		if (StringUtil.isEmpty(processDefinitionKey)) {
			throw new FoxbpmPluginException("流程定义编号为空", "Rest服务");
		}
		ProcessDefinition processDefinition = modelService.getLatestProcessDefinition(processDefinitionKey);
		if (null == processDefinition) {
			throw new FoxbpmPluginException("未找到流程定义"+processDefinitionKey, "Rest服务");
		}
		processDefinitionId = processDefinition.getId();
	} else {
		ProcessInstanceQuery processInstanceQuery = processEngine.getRuntimeService().createProcessInstanceQuery();
		ProcessInstance processInstance = processInstanceQuery.processInstanceId(processInstanceId).singleResult();
		if (null == processInstance) {
			throw new FoxbpmPluginException("未找到流程定义"+processInstanceId, "Rest服务");
		}
		processDefinitionId = processInstance.getProcessDefinitionId();
	}
	String svgContent = modelService.getProcessDefinitionSVG(processDefinitionId);
	DataResult dataResult =new DataResult();
	try {
		dataResult.setData(svgContent);
	} catch (Exception e) {
	}
	return dataResult;
}
 
Example #19
Source File: IndexResourcePOSTTest.java    From ontopia with Apache License 2.0 5 votes vote down vote up
@Test
public void testValueDatatypeFORM() throws IOException {
	Form form = new Form();
	form.add("value", "v1");
	form.add("datatype", DataTypes.TYPE_STRING.getAddress());
	Collection<VariantName> variants = post(null, REF, form);

	Assert.assertNotNull(variants);
	Assert.assertEquals(2, variants.size());
	assertContainsTopics(variants, "4", "12");
}
 
Example #20
Source File: RequestParametersFormTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Test
public void getStringReturnsFormString() throws Exception {
  final Map<String, String> testKVP = new HashMap<>();

  final Form form = mockedForm(testKVP);
  testKVP.put(testKey, testString);

  classUnderTest = new RequestParametersForm(form);

  assertEquals(testString, classUnderTest.getString(testKey));
}
 
Example #21
Source File: UserCollectionResouce.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
@Get
public DataResult getAllUsers() {
	Form query = getQuery();
	Set<String> names = query.getNames();
	String userName = null;
	String userId = null;
	if (names.contains("userName")) {
		String tmpUserName = getQueryParameter("userName", query);
		if(StringUtil.isNotEmpty(tmpUserName))
			userName = "%"+tmpUserName+"%";
	}
	if (names.contains("userId")) {
		String tmpUserId = getQueryParameter("userId", query);
		if(StringUtil.isNotEmpty(tmpUserId))
			userId = "%"+tmpUserId+"%";
	}
	List<UserEntity> users = FoxBpmUtil.getProcessEngine().getIdentityService().getUsers(userId, userName);
	// 数据转换
	List<Map<String, Object>> resultDatas = new ArrayList<Map<String, Object>>();
	for (UserEntity user : users) {
		resultDatas.add(user.getPersistentState());
	}
	// 数据响应体构造
	DataResult result = new DataResult();
	result.setData(resultDatas);
	result.setTotal(users.size());
	return result;
}
 
Example #22
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 #23
Source File: ProcessDefinitionCollectionResouce.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
@Get
public DataResult getDefinitions() {
	ProcessEngine engine = ProcessEngineManagement.getDefaultProcessEngine();
	ProcessDefinitionQuery processDefinitionQuery = engine.getModelService().createProcessDefinitionQuery();
	Form query = getQuery();
	Set<String> names = query.getNames();
	if (names.contains(RestConstants.CATEGORY)) {
		processDefinitionQuery.processDefinitionCategory(getQueryParameter(RestConstants.CATEGORY, query));
	}
	if (names.contains(RestConstants.PROCESS_KEY)) {
		processDefinitionQuery.processDefinitionKey(getQueryParameter(RestConstants.PROCESS_KEY, query));
	}
	if (names.contains(RestConstants.NAME)) {
		processDefinitionQuery.processDefinitionName(getQueryParameter(RestConstants.NAME, query));
	}
	if (names.contains(RestConstants.NAME_LIKE)) {
		processDefinitionQuery.processDefinitionNameLike(parseLikeValue(getQueryParameter(RestConstants.NAME_LIKE, query)));
	}

	List<ProcessDefinition> processDefinitions = processDefinitionQuery.list();
	List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
	for (ProcessDefinition process : processDefinitions) {
		Map<String,Object> processAttrMap = process.getPersistentState();
		processAttrMap.put("description", process.getDescription());
		results.add(processAttrMap);
	}
	DataResult result = new DataResult();
	result.setData(results);
	result.setTotal(processDefinitions.size());
	return result;
}
 
Example #24
Source File: AbstractPaginateList.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public DataResult paginateList(Form form, Query query, String defaultSort, Map<String, QueryProperty> properties) {

	// Collect parameters
	int start = RequestUtil.getInteger(form, "start", 0);
	int size = RequestUtil.getInteger(form, "size", 10);
	String sort = form.getValues("sort");
	if (sort == null) {
		sort = defaultSort;
	}
	String order = form.getValues("order");
	if (order == null) {
		order = "asc";
	}

	// Sort order
	if (sort != null && properties.size() > 0) {
		QueryProperty qp = properties.get(sort);
		if (qp == null) {
			throw new FoxbpmPluginException("Value for param 'sort' is not valid, '" + sort + "' is not a valid property","rest服务");
		}
		((AbstractQuery) query).orderBy(qp);
		if (order.equals("asc")) {
			query.asc();
		} else if (order.equals("desc")) {
			query.desc();
		} else {
			throw new FoxbpmPluginException("Value for param 'order' is not valid : '" + order + "', must be 'asc' or 'desc'","rest服务");
		}
	}

	List list = processList(query.listPage(start, size));
	DataResult response = new DataResult();
	response.setSort(sort);
	response.setOrder(order);
	response.setData(list);
	return response;
}
 
Example #25
Source File: JSONResponseReader.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public Object readResponse( Response response, Class<?> resultType )
{
    if( response.getEntity().getMediaType().equals( MediaType.APPLICATION_JSON ) )
    {
        if( ValueComposite.class.isAssignableFrom( resultType ) )
        {
            String jsonValue = response.getEntityAsText();
            ValueCompositeType valueType = module.valueDescriptor( resultType.getName() ).valueType();
            return jsonDeserializer.deserialize( module, valueType, jsonValue );
        }
        else if( resultType.equals( Form.class ) )
        {
            try( JsonReader reader = jsonFactories.readerFactory()
                                                  .createReader( response.getEntity().getReader() ) )
            {
                JsonObject jsonObject = reader.readObject();
                Form form = new Form();
                jsonObject.forEach(
                    ( key, value ) ->
                    {
                        String valueString = value.getValueType() == JsonValue.ValueType.STRING
                                             ? ( (JsonString) value ).getString()
                                             : value.toString();
                        form.set( key, valueString );
                    } );
                return form;
            }
            catch( IOException | JsonException e )
            {
                throw new ResourceException( e );
            }
        }
    }
    return null;
}
 
Example #26
Source File: SPARQLResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private Value parseValueParam( Repository repository, Form form, String parameterName )
    throws ResourceException
{
    String paramValue = form.getFirstValue( parameterName );
    try
    {
        return Protocol.decodeValue( paramValue, repository.getValueFactory() );
    }
    catch( IllegalArgumentException e )
    {
        throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid value for parameter '" + parameterName + "': "
                                                                      + paramValue );
    }
}
 
Example #27
Source File: DefaultRequestReader.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private String getValue( String name, Form queryAsForm, Form entityAsForm )
{
    String value = queryAsForm.getFirstValue( name );
    if( value == null )
    {
        value = entityAsForm.getFirstValue( name );
    }
    return value;
}
 
Example #28
Source File: ContextResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private String getValue( String name, Form queryAsForm, Form entityAsForm )
{
    String value = queryAsForm.getFirstValue( name );
    if( value == null )
    {
        value = entityAsForm.getFirstValue( name );
    }
    return value;
}
 
Example #29
Source File: RequestUtil.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
public static boolean getBoolean(Form form, String name, boolean defaultValue) {
	boolean value = defaultValue;
	if (form.getValues(name) != null) {
		value = Boolean.valueOf(form.getValues(name));
	}
	return value;
}
 
Example #30
Source File: SwitchClustersResource.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Get("json")
public Map<String, List<String>> retrieve() {
    IFloodlightProviderService floodlightProvider =
            (IFloodlightProviderService)getContext().getAttributes().
                get(IFloodlightProviderService.class.getCanonicalName());
    ITopologyService topology =
            (ITopologyService)getContext().getAttributes().
                get(ITopologyService.class.getCanonicalName());

    Form form = getQuery();
    String queryType = form.getFirstValue("type", true);
    boolean openflowDomain = true;
    if (queryType != null && "l2".equals(queryType)) {
        openflowDomain = false;
    }

    Map<String, List<String>> switchClusterMap = new HashMap<String, List<String>>();
    for (Long dpid: floodlightProvider.getAllSwitchDpids()) {
        Long clusterDpid =
                (openflowDomain
                 ? topology.getOpenflowDomainId(dpid)
                 :topology.getL2DomainId(dpid));
        List<String> switchesInCluster = switchClusterMap.get(HexString.toHexString(clusterDpid));
        if (switchesInCluster != null) {
            switchesInCluster.add(HexString.toHexString(dpid));
        } else {
            List<String> l = new ArrayList<String>();
            l.add(HexString.toHexString(dpid));
            switchClusterMap.put(HexString.toHexString(clusterDpid), l);
        }
    }
    return switchClusterMap;
}