Java Code Examples for org.restlet.data.Form

The following are top voted examples for showing how to use org.restlet.data.Form. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: springboot-shiro-cas-mybatis   File: TicketResource.java   Source Code and 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 2
Project: springboot-shiro-cas-mybatis   File: TicketResource.java   Source Code and License 6 votes vote down vote up
/**
 * Log the form request.
 *
 * @param form the form
 */
private void logFormRequest(final Form form) {
    if (LOGGER.isDebugEnabled()) {
        final Set<String> pairs = new HashSet<>();
        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 3
Project: cas4.0.x-server-wechat   File: TicketResource.java   Source Code and License 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 4
Project: open-rmbt   File: ChoicesResource.java   Source Code and License 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 5
Project: ipst   File: ITeslaStatsResource.java   Source Code and License 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 6
Project: ipst   File: ITeslaDataResource.java   Source Code and License 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 7
Project: hub-email-extension   File: EmailTestServerResource.java   Source Code and License 6 votes vote down vote up
@Post
public void postFormData(final Representation entity) {
    ExtensionTokenManager tokenManager = getTokenManager();
    if (tokenManager.authenticationRequired()) {
        getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
    } else {
        Form form = new Form(entity);
        final String emailAddress = form.getFirstValue(FORM_INPUT_EMAIL_ADDRESS);
        if (StringUtils.isNotBlank(emailAddress)) {
            TestEmailNotifier testNotifier = (TestEmailNotifier) getContext().getAttributes()
                    .get(EmailExtensionConstants.CONTEXT_ATTRIBUTE_KEY_TEST_NOTIFIER);
            testNotifier.setEmailAddress(emailAddress);
            testNotifier.run();
            testNotifier.setEmailAddress("");
        }
    }
}
 
Example 8
Project: appBack   File: Yun15Method.java   Source Code and License 6 votes vote down vote up
public   Map<String,Object>  getEasyJson(Form form){
	 Map<String,Object> returnMap= new HashMap<String, Object>();
	List<Map<String,Object>> list= new  ArrayList<Map<String,Object>>();
	 Map<String,Object> map= new HashMap<String, Object>();
	 map.put("name", 123);
	 map.put("picUrl", "www.baidu.com");
	 list.add(map);
	 list.add(map);
	 list.add(map);
	 returnMap.put("ret", 0);
	 returnMap.put("test", "ok");
	 returnMap.put("data", list);
	 for(Entry<String, Object> entry : map.entrySet()){
           String strkey = entry.getKey();
           Object strval = entry.getValue();
       }
	 return returnMap;
}
 
Example 9
Project: cas4.1.9   File: TicketResource.java   Source Code and 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 10
Project: cas4.1.9   File: TicketResource.java   Source Code and License 6 votes vote down vote up
/**
 * Log the form request.
 *
 * @param form the form
 */
private void logFormRequest(final Form form) {
    if (LOGGER.isDebugEnabled()) {
        final Set<String> pairs = new HashSet<>();
        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 11
Project: polygene-java   File: FormRequestWriter.java   Source Code and License 6 votes vote down vote up
@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException
{
   if (requestObject instanceof Form)
   {
      // Form as query parameters
      if (request.getMethod().equals(Method.GET))
         request.getResourceRef().setQuery(((Form)requestObject).getQueryString());
      else
         request.setEntity(((Form)requestObject).getWebRepresentation(CharacterSet.UTF_8));

      return true;
   }

   return false;
}
 
Example 12
Project: DeviceConnect-Android   File: FormUtils.java   Source Code and 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 13
Project: DeviceConnect-Android   File: FormReader.java   Source Code and 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 14
Project: DeviceConnect-Android   File: AccessTokenServerResource.java   Source Code and 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 15
Project: DeviceConnect-Android   File: AccessTokenServerResource.java   Source Code and License 6 votes vote down vote up
/**
 * Get request parameter "grant_type".
 * 
 * @param params
 * @return
 * @throws OAuthException
 */
protected static GrantType getGrantType(Form params) throws OAuthException {
    String typeString = params.getFirstValue(GRANT_TYPE);
    getLogger().info("Type: " + typeString);
    try {
        GrantType type = Enum.valueOf(GrantType.class, typeString);
        getLogger().fine("Found flow - " + type);
        return type;
    } catch (IllegalArgumentException iae) {
        throw new OAuthException(OAuthError.unsupported_grant_type,
                "Unsupported flow", null);
    } catch (NullPointerException npe) {
        throw new OAuthException(OAuthError.invalid_request,
                "No grant_type parameter found.", null);
    }
}
 
Example 16
Project: DeviceConnect-Android   File: OAuthServerResource.java   Source Code and 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 17
Project: cas-4.0.1   File: TicketResource.java   Source Code and License 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 18
Project: prudence   File: DelegatedResource.java   Source Code and License 6 votes vote down vote up
/**
 * Initializes the resource, and delegates to the <code>handleInit()</code>
 * entry point in the executable.
 */
@Override
protected void doInit() throws ResourceException
{
	super.doInit();
	setAnnotated( false );

	if( attributes.isSourceViewable() )
	{
		Request request = getRequest();
		Form query = request.getResourceRef().getQueryAsForm();
		if( TRUE.equals( query.getFirstValue( SOURCE ) ) )
			// Bypass doInit delegation
			return;
	}

	DelegatedResourceConversationService conversationService = new DelegatedResourceConversationService( this, null, null, attributes.getDefaultCharacterSet() );
	enter( attributes.getEntryPointNameForInit(), true, conversationService );
}
 
Example 19
Project: prudence   File: LazyInitializationPost.java   Source Code and License 6 votes vote down vote up
@Override
protected void initialize()
{
	if( request.getMethod().equals( Method.POST ) )
	{
		// Give the exposed file map a chance to consume the entity first
		exposedFile.validateInitialized();
		map.putAll( exposedFile.formFields );

		if( request.isEntityAvailable() )
		{
			Form form = new Form( request.getEntity() );
			for( Parameter parameter : form )
				map.put( parameter.getName(), parameter.getValue() );
		}
	}
}
 
Example 20
Project: jmsRestful   File: PNSOpenResource.java   Source Code and License 6 votes vote down vote up
/** 
 * @Title: open4Apple 
 * @Description:打开苹果客户端推送
 * @param @return
 * @return String
 * @throws 
 * @author Martin
 * @date 2015年4月8日 下午3:53:41
 * @version V1.0
*/ 
@Get
public String open4Apple() {
	try {
		//获取查询参数
		Form form = getRequest().getResourceRef().getQueryAsForm() ;
		String token= form.getFirstValue("token");
		if(StringUtil.isEmpty(token)){
			return JsonUtils.getError("token参数值为null", false);
		}
		List<AppleTokenEntity> appleTokenEntity = commonDao.findByProperty(AppleTokenEntity.class, "token", token);
		if(appleTokenEntity!=null&&appleTokenEntity.size()>0){
			return JsonUtils.getError("数据库已有该token记录", false);
		}else{
			AppleTokenEntity appleToken=new AppleTokenEntity();
			appleToken.setToken(token);
			//添加操作
			commonDao.save(appleToken);
		}
		return JsonUtils.getOK("", false);
	} catch (Exception e) {
		return JsonUtils.getError(e.getMessage(), false);
	}
}
 
Example 21
Project: jmsRestful   File: PNSCloseResource.java   Source Code and License 6 votes vote down vote up
/** 
 * @Title: open4Apple 
 * @Description:打开苹果客户端推送
 * @param @return
 * @return String
 * @throws 
 * @author Martin
 * @date 2015年4月8日 下午3:53:41
 * @version V1.0
*/ 
@Get
public String close4Apple() {
	try {
		//获取查询参数
		Form form = getRequest().getResourceRef().getQueryAsForm() ;
		String token= form.getFirstValue("token");
		if(StringUtil.isEmpty(token)){
			return JsonUtils.getError("token参数值为null", false);
		}
		List<AppleTokenEntity> appleTokenEntity = commonDao.findByProperty(AppleTokenEntity.class, "token", token);
		if(appleTokenEntity==null||appleTokenEntity.size()==0){
			return JsonUtils.getError("数据库不存在该token记录", false);
		}else if(appleTokenEntity.size()==1){
			commonDao.delete(appleTokenEntity.get(0));
		}else{
			return JsonUtils.getError("数据库该记录不唯一,数据库数据异常", false);
		}
		return JsonUtils.getOK("", true);
	} catch (Exception e) {
		return JsonUtils.getError(e.getMessage(), false);
	}
}
 
Example 22
Project: SecureBPMN   File: RequestUtil.java   Source Code and License 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 = df.parse(input);
    } catch(Exception e) {
      throw new ActivitiException("Failed to parse date " + input);
    }
  }
  return value;
}
 
Example 23
Project: p00   File: TicketResource.java   Source Code and License 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 24
Project: cas-server-4.0.1   File: TicketResource.java   Source Code and License 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 25
Project: FoxBPM   File: FlowGraphicPositionResource.java   Source Code and License 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 26
Project: FoxBPM   File: AbstractRestResource.java   Source Code and License 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 27
Project: FoxBPM   File: RequestUtil.java   Source Code and License 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 28
Project: FoxBPM   File: AbstractRestResource.java   Source Code and License 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 29
Project: orcid-java-client   File: OrcidOAuthClient.java   Source Code and License 6 votes vote down vote up
/**
 * Exchange and authorization code for an auth token from ORCID
 * 
 * @see <a href='http://support.orcid.org/knowledgebase/articles/120107'>GET oauth/authorize</a>
 * @see
 * <a href='http://support.orcid.org/knowledgebase/articles/179969-methods-to-generate-an-access-token-for-testing'>
 *     Methods to Generate an Access Token for Testing</a>
 *
 * @param authorizationCode
 *      The authorization code returned from a request built with
 *      {@link #getAuthzCodeRequest(String, OrcidAuthScope)}
 *
 * @return the parsed response
 * @throws IOException
 *             if result unparsable or network unreachable.
 * @throws ResourceException
 *             if there's a http problem (e.g. 404, 400)
 */
public OrcidAccessToken getAccessToken(String authorizationCode) throws IOException {
	Reference ref = new Reference(apiUriToken + TOKEN_ENDPOINT);
	if (Context.getCurrent() == null) {
		Context.setCurrent(new Context());
	}
	ClientResource client = new ClientResource(ref);
	Form f = new Form();
	f.add("client_id", clientID);
	f.add("client_secret", clientSecret);
	f.add("grant_type", "authorization_code");
	f.add("code", authorizationCode);
	f.add("redirect_uri", redirectUri);
	client.getContext().getParameters().add("followRedirects", "true");
	log.fine(f.toString());
	log.fine(client.toString());
	Representation rep = client.post(f, MediaType.APPLICATION_JSON);
	String json = rep.getText();
	return new ObjectMapper().reader(OrcidAccessToken.class).readValue(json);
}
 
Example 30
Project: helix   File: JsonParameters.java   Source Code and License 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 31
Project: xproclet   File: UploadApplication.java   Source Code and License 6 votes vote down vote up
public Representation post(Representation entity) {
   Form form = new Form(entity);
   String submit = form.getFirstValue("submit");
   String cancel = form.getFirstValue("cancel");
   String update = form.getFirstValue("update");
   if (submit==null) {
      submit = "Upload";
   }
   if (cancel==null) {
      cancel = "Cancel";
   }
   UploadApplication app = (UploadApplication)getContext().getAttributes().get("upload.app");
   UploadProgress progress = app.newUpload("true".equals(update),submit,cancel);
   getResponse().setStatus(Status.SUCCESS_CREATED);
   getResponse().setLocationRef(new Reference(getRequest().getResourceRef().getParentRef().toString()+progress.id+"/"));
   return new StringRepresentation("<context id='"+progress.id+"'/>",MediaType.APPLICATION_XML);
}
 
Example 32
Project: xproclet   File: LoginAction.java   Source Code and License 6 votes vote down vote up
public Representation post(Representation rep) {
   Reference service = getReferenceAttribute(getRequest(),"auth-service",confService);
   if (service==null) {
      getResponse().setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
      return null;
   }
   getLogger().info("Using service "+service);
   final Form form = new Form(rep);
   String username = form.getFirstValue("username");
   String domain = form.getFirstValue("domain");
   String email = username;
   if (domain!=null && domain.length()>0 && email.indexOf('@')<0) {
      email += "@"+domain;
   }
   String password = form.getFirstValue("password");
   Identity user = idManager.get(email);
   if (user==null) {
      getLogger().info("Unknown user "+email);
      actor.unauthorized();
      return null;
   }
   login(getContext().createChildContext(),service,loginApp,loginType,username,password,email,form,actor);
   return null;
}
 
Example 33
Project: rva   File: SocialConnectorServiceImpl.java   Source Code and License 6 votes vote down vote up
public RpcResultInfo putAccessToken(String companyId,  SocialConnectorAccessInfo accessToken) throws ServiceFailedException {
	// new token - generate Id
	if ((accessToken.getId() == null) || (accessToken.getId().isEmpty()))
		accessToken.setId(UUID.randomUUID().toString());

	String url = createAccessTokenResource(companyId, accessToken.getNetworkType().toString(), accessToken.getId());
	
	Form form = new Form();

	form.add(AccessTokenAttribute.NAME, accessToken.getName());
	form.add(AccessTokenAttribute.VALUE, accessToken.getValue());
	form.add(AccessTokenAttribute.DEFAULT, ServerUtils.BooleanToStr(accessToken.isDefault()));
	
	put(url, form);

	return new RpcResultInfo(accessToken.getId());
}
 
Example 34
Project: rva   File: ScheduleServiceImpl.java   Source Code and License 6 votes vote down vote up
public RpcResultInfo checkDistribution(String companyId, ScheduleInfo schedule) throws ServiceFailedException {
	if ((schedule.getId() == null) || (schedule.getId().isEmpty()))
		schedule.setId(UUID.randomUUID().toString());
	String url = createCheckDistributionResource(companyId, schedule.getId());
	
	Form form = new Form();

	form.add(ScheduleAttribute.DISTRIBUTE_TO_ALL, ServerUtils.BooleanToStr(schedule.getDistributionToAll()));
	form.add(ScheduleAttribute.DISTRIBUTION, ServerUtils.ListToString(schedule.getDistribution(),","));
	
	Document d = post(url, form);
	RpcResultInfo result = new RpcResultInfo();
	if (d != null) {
		DistributionCheckInfo distributionCheck = docToDistributionCheck(d);
		
		if (distributionCheck != null) {
			String resultString = distributionCheck.parseDistributionCheck();
			if (!resultString.isEmpty()){
				result.setErrorMessage(resultString);
			}
		}
	}
	return result;
}
 
Example 35
Project: rva   File: ScheduleServiceImpl.java   Source Code and License 6 votes vote down vote up
public RpcResultInfo putSchedule(String companyId, ScheduleInfo schedule) throws ServiceFailedException {
		// new user- generate userId
		if ((schedule.getId() == null) || (schedule.getId().isEmpty()))
			schedule.setId(UUID.randomUUID().toString());
		String url = createScheduleResource(companyId, schedule.getId());

		Form form = new Form();

		form.add(ScheduleAttribute.ID, schedule.getId());
		form.add(ScheduleAttribute.NAME, schedule.getName());
		TimeLineUtils.addToForm(form, schedule.getTimeline());
		form.add(ScheduleAttribute.DISTRIBUTE_TO_ALL, ServerUtils.BooleanToStr(schedule.getDistributionToAll()));
		form.add(ScheduleAttribute.DISTRIBUTION, ServerUtils.ListToString(schedule.getDistribution(),","));

		form.add(ScheduleAttribute.CONTENT, schedule.getContent());
		
//		form.add(ScheduleAttribute.TRANSITION, schedule.getTransition());
//		form.add(ScheduleAttribute.SCALE, schedule.getScale());
//		form.add(ScheduleAttribute.POSITION, schedule.getPosition());

		put(url, form);
		
		//putPlayListItems(companyId, schedule.getId(), schedule.getPlayListItems());
		return new RpcResultInfo(schedule.getId());
	}
 
Example 36
Project: FiWare-Template-Handler   File: RequestUtil.java   Source Code and License 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 ActivitiException("Failed to parse date " + input);
    }
  }
  return value;
}
 
Example 37
Project: geowave   File: GeoWaveOperationServiceWrapper.java   Source Code and License 6 votes vote down vote up
private String[] getFieldValues(
		final Form form,
		final String name ) {
	String[] val = null;
	if (form != null) {
		val = form.getValuesArray(name);
	}
	if ((val == null) || (val.length == 0)) {
		val = getQuery().getValuesArray(
				name);
	}
	String str = getFieldValue(
			form,
			name);
	if (str == null) {
		return val;
	}
	else {

		return str.split(",");
	}
}
 
Example 38
Project: spring-restlet   File: UpdateGadgetUserPrefsHandlerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void updateUserPrefs(DashboardId dashboardId, GadgetRequestContext gadgetRequestContext, GadgetId gadgetId,
		Form queryParams, Response response) {
	IDashboard dashboard = repository.get(dashboardId, gadgetRequestContext);

	try {
		dashboard.updateGadgetUserPrefs(gadgetId, adaptParameterMapToUserPrefValues(queryParams));
		repository.save(dashboard);
	} catch (IllegalArgumentException iae) {
		// thrown if a required pref was set to an illegal value
		response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, i18n.getText("invalid.value.for.required.pref"));
	} catch (InconsistentDashboardStateException idse) {
		log.error("UpdateGadgetUserPrefsHandlerImpl: Unexpected error occurred: ", idse);
		response.setStatus(Status.CLIENT_ERROR_CONFLICT, i18n.getText("error.please.reload"));
	}
}
 
Example 39
Project: SlipStreamServer   File: DeploymentFormProcesorTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = ValidationException.class)
public void deploymentWithMissingMappingAndDefaultValue()
		throws ConfigurationException, SlipStreamClientException {

	User user = UserTest.createUser("test");

	String imageName = "deploymentWithMissingMappingAndDefaultValue";
	Module image = new ImageModule(imageName);
	image.setParameter(new ModuleParameter("pi1", "some_default", "",
			ParameterCategory.Input));
	image.store();

	Form form = new Form();

	form.add("name", "node1");
	form.add("node--1--shortname", "node1");
	form.add("node--1--imagelink", "module/" + imageName);

	DeploymentFormProcessor processor = new DeploymentFormProcessor(user);

	try {
		processor.processForm(form);
	} finally {
		image.remove();
	}
}
 
Example 40
Project: spring-restlet   File: ChangeLayoutHandlerImpl.java   Source Code and License 6 votes vote down vote up
private GadgetLayout parseGadgetLayout(Layout layout, Form queryParams) throws ParseGadgetLayoutException {
	List<Iterable<GadgetId>> columns = new ArrayList<Iterable<GadgetId>>(layout.getNumberOfColumns());
	columns.addAll(Collections.<Iterable<GadgetId>> nCopies(layout.getNumberOfColumns(),
			Collections.<GadgetId> emptyList()));
	for (int i = 0; i < columns.size(); i++) {
		String[] gadgetIds = queryParams.getValuesArray(Integer.toString(i));
		if (gadgetIds == null) {
			// there are no gadgets in this column
			continue;
		}
		try {
			columns.set(i, toGadgetIds(gadgetIds));
		} catch (NumberFormatException e) {
			throw new ParseGadgetLayoutException("gadget ids must be integers");
		}
	}
	return new GadgetLayout(columns);
}