use of org.restlet.representation.Representation in project camel by apache.
the class DefaultRestletBinding method populateRestletRequestFromExchange.
public void populateRestletRequestFromExchange(Request request, Exchange exchange) {
request.setReferrerRef("camel-restlet");
final Method method = request.getMethod();
MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
if (mediaType == null) {
mediaType = MediaType.APPLICATION_WWW_FORM;
}
Form form = null;
// Use forms only for PUT, POST and x-www-form-urlencoded
if ((Method.PUT == method || Method.POST == method) && MediaType.APPLICATION_WWW_FORM.equals(mediaType, true)) {
form = new Form();
if (exchange.getIn().getBody() instanceof Map) {
//Body is key value pairs
try {
Map pairs = exchange.getIn().getBody(Map.class);
for (Object key : pairs.keySet()) {
Object value = pairs.get(key);
form.add(key.toString(), value != null ? value.toString() : null);
}
} catch (Exception e) {
throw new RuntimeCamelException("body for " + MediaType.APPLICATION_WWW_FORM + " request must be Map<String,String> or string format like name=bob&password=secRet", e);
}
} else {
// use string based for forms
String body = exchange.getIn().getBody(String.class);
if (body != null) {
List<NameValuePair> pairs = URLEncodedUtils.parse(body, Charset.forName(IOHelper.getCharsetName(exchange, true)));
for (NameValuePair p : pairs) {
form.add(p.getName(), p.getValue());
}
}
}
}
// get outgoing custom http headers from the exchange if they exists
Series<Header> restletHeaders = exchange.getIn().getHeader(HeaderConstants.ATTRIBUTE_HEADERS, Series.class);
if (restletHeaders == null) {
restletHeaders = new Series<Header>(Header.class);
request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, restletHeaders);
} else {
// if the restlet headers already exists on the exchange, we need to filter them
for (String name : restletHeaders.getNames()) {
if (headerFilterStrategy.applyFilterToCamelHeaders(name, restletHeaders.getValues(name), exchange)) {
restletHeaders.removeAll(name);
}
}
request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, restletHeaders);
// since the restlet headers already exists remove them from the exchange so they don't get added again below
// we will get a new set of restlet headers on the response
exchange.getIn().removeHeader(HeaderConstants.ATTRIBUTE_HEADERS);
}
// login and password are filtered by header filter strategy
String login = exchange.getIn().getHeader(RestletConstants.RESTLET_LOGIN, String.class);
String password = exchange.getIn().getHeader(RestletConstants.RESTLET_PASSWORD, String.class);
if (login != null && password != null) {
ChallengeResponse authentication = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, login, password);
request.setChallengeResponse(authentication);
LOG.debug("Basic HTTP Authentication has been applied");
}
for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
// Use forms only for PUT, POST and x-www-form-urlencoded
if (form != null) {
if (key.startsWith("org.restlet.")) {
// put the org.restlet headers in attributes
request.getAttributes().put(key, value);
} else {
// put the user stuff in the form
if (value instanceof Collection) {
for (Object v : (Collection<?>) value) {
form.add(key, v.toString());
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
restletHeaders.set(key, value.toString());
}
}
} else {
//Add headers to headers and to body
form.add(key, value.toString());
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
restletHeaders.set(key, value.toString());
}
}
}
} else {
// For non-form post put all the headers in custom headers
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
restletHeaders.set(key, value.toString());
}
}
LOG.debug("Populate Restlet request from exchange header: {} value: {}", key, value);
}
}
if (form != null) {
request.setEntity(form.getWebRepresentation());
LOG.debug("Populate Restlet {} request from exchange body as form using media type {}", method, mediaType);
} else {
// include body if PUT or POST
if (request.getMethod() == Method.PUT || request.getMethod() == Method.POST) {
Representation body = createRepresentationFromBody(exchange, mediaType);
request.setEntity(body);
LOG.debug("Populate Restlet {} request from exchange body: {} using media type {}", method, body, mediaType);
} else {
// no body
LOG.debug("Populate Restlet {} request from exchange using media type {}", method, mediaType);
request.setEntity(new EmptyRepresentation());
}
}
// accept
String accept = exchange.getIn().getHeader("Accept", String.class);
final ClientInfo clientInfo = request.getClientInfo();
final List<Preference<MediaType>> acceptedMediaTypesList = clientInfo.getAcceptedMediaTypes();
if (accept != null) {
final MediaType[] acceptedMediaTypes = exchange.getContext().getTypeConverter().tryConvertTo(MediaType[].class, exchange, accept);
for (final MediaType acceptedMediaType : acceptedMediaTypes) {
acceptedMediaTypesList.add(new Preference<MediaType>(acceptedMediaType));
}
}
final MediaType[] acceptedMediaTypes = exchange.getIn().getHeader(Exchange.ACCEPT_CONTENT_TYPE, MediaType[].class);
if (acceptedMediaTypes != null) {
for (final MediaType acceptedMediaType : acceptedMediaTypes) {
acceptedMediaTypesList.add(new Preference<MediaType>(acceptedMediaType));
}
}
}
use of org.restlet.representation.Representation in project camel by apache.
the class DefaultRestletBinding method populateRestletResponseFromExchange.
public void populateRestletResponseFromExchange(Exchange exchange, Response response) throws Exception {
Message out;
if (exchange.isFailed()) {
// 500 for internal server error which can be overridden by response code in header
response.setStatus(Status.valueOf(500));
Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
if (msg.isFault()) {
out = msg;
} else {
// print exception as message and stacktrace
Exception t = exchange.getException();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
response.setEntity(sw.toString(), MediaType.TEXT_PLAIN);
return;
}
} else {
out = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
}
// get content type
MediaType mediaType = out.getHeader(Exchange.CONTENT_TYPE, MediaType.class);
if (mediaType == null) {
Object body = out.getBody();
mediaType = MediaType.TEXT_PLAIN;
if (body instanceof String) {
mediaType = MediaType.TEXT_PLAIN;
} else if (body instanceof StringSource || body instanceof DOMSource) {
mediaType = MediaType.TEXT_XML;
}
}
// get response code
Integer responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
if (responseCode != null) {
response.setStatus(Status.valueOf(responseCode));
}
// set response body according to the message body
Object body = out.getBody();
if (body instanceof WrappedFile) {
// grab body from generic file holder
GenericFile<?> gf = (GenericFile<?>) body;
body = gf.getBody();
}
if (body == null) {
// empty response
response.setEntity("", MediaType.TEXT_PLAIN);
} else if (body instanceof Response) {
// its already a restlet response, so dont do anything
LOG.debug("Using existing Restlet Response from exchange body: {}", body);
} else if (body instanceof Representation) {
response.setEntity(out.getBody(Representation.class));
} else if (body instanceof InputStream) {
response.setEntity(new InputRepresentation(out.getBody(InputStream.class), mediaType));
} else if (body instanceof File) {
response.setEntity(new FileRepresentation(out.getBody(File.class), mediaType));
} else if (body instanceof byte[]) {
byte[] bytes = out.getBody(byte[].class);
response.setEntity(new ByteArrayRepresentation(bytes, mediaType, bytes.length));
} else {
// fallback and use string
String text = out.getBody(String.class);
response.setEntity(text, mediaType);
}
LOG.debug("Populate Restlet response from exchange body: {}", body);
if (exchange.getProperty(Exchange.CHARSET_NAME) != null) {
CharacterSet cs = CharacterSet.valueOf(exchange.getProperty(Exchange.CHARSET_NAME, String.class));
response.getEntity().setCharacterSet(cs);
}
// set headers at the end, as the entity must be set first
// NOTE: setting HTTP headers on restlet is cumbersome and its API is "weird" and has some flaws
// so we need to headers two times, and the 2nd time we add the non-internal headers once more
Series<Header> series = new Series<Header>(Header.class);
for (Map.Entry<String, Object> entry : out.getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
boolean added = setResponseHeader(exchange, response, key, value);
if (!added) {
// we only want non internal headers
if (!key.startsWith("Camel") && !key.startsWith("org.restlet")) {
String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, value);
if (text != null) {
series.add(key, text);
}
}
}
}
}
// set HTTP headers so we return these in the response
if (!series.isEmpty()) {
response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, series);
}
}
use of org.restlet.representation.Representation in project vcell by virtualcell.
the class SimDataValuesServerResource method get_html.
@Override
public Representation get_html() {
VCellApiApplication application = ((VCellApiApplication) getApplication());
User vcellUser = application.getVCellUser(getChallengeResponse(), AuthenticationPolicy.ignoreInvalidCredentials);
SimDataValuesRepresentation simDataValues = getSimDataValuesRepresentation(vcellUser);
Map<String, Object> dataModel = new HashMap<String, Object>();
// +"?"+VCellApiApplication.REDIRECTURL_FORMNAME+"="+getRequest().getResourceRef().toUrl());
dataModel.put("loginurl", "/" + VCellApiApplication.LOGINFORM);
dataModel.put("logouturl", "/" + VCellApiApplication.LOGOUT + "?" + VCellApiApplication.REDIRECTURL_FORMNAME + "=" + Reference.encode(getRequest().getResourceRef().toUrl().toString()));
if (vcellUser != null) {
dataModel.put("userid", vcellUser.getName());
}
dataModel.put("userId", getAttribute(PARAM_USER));
dataModel.put("simId", getQueryValue(PARAM_SIM_ID));
Long startRowParam = getLongQueryValue(PARAM_START_ROW);
if (startRowParam != null) {
dataModel.put("startRow", startRowParam);
} else {
dataModel.put("startRow", 1);
}
Long maxRowsParam = getLongQueryValue(PARAM_MAX_ROWS);
if (maxRowsParam != null) {
dataModel.put("maxRows", maxRowsParam);
} else {
dataModel.put("maxRows", 10);
}
dataModel.put("simdatavalues", simDataValues);
int numVars = simDataValues.getVariables().length;
if (numVars > 1) {
StringBuffer buffer = new StringBuffer();
String firstRow = "\"";
for (int i = 0; i < numVars; i++) {
firstRow += simDataValues.getVariables()[i].getName();
if (i < numVars - 1) {
firstRow += ",";
}
}
firstRow += "\\n\" + \n";
buffer.append(firstRow);
int numTimes = simDataValues.getVariables()[0].getValues().length;
for (int t = 0; t < numTimes; t++) {
String row = "\"";
for (int v = 0; v < numVars; v++) {
row += simDataValues.getVariables()[v].getValues()[t];
if (v < numVars - 1) {
row += ",";
}
}
row += "\\n\"";
if (t < numTimes - 1) {
row += " + \n";
}
buffer.append(row);
}
String csvdata = buffer.toString();
// String csvdata = "\"t,x,y\\n\" + \n" +
// "\"0,0,0\\n\" + \n" +
// "\"1,1,1\\n\" + \n" +
// "\"2,2,4\\n\" + \n" +
// "\"3,3,9\\n\" + \n" +
// "\"4,4,16\\n\" + \n" +
// "\"5,5,25\\n\"";
dataModel.put("csvdata", csvdata);
}
Gson gson = new Gson();
dataModel.put("jsonResponse", gson.toJson(simDataValues));
Configuration templateConfiguration = application.getTemplateConfiguration();
Representation formFtl = new ClientResource(LocalReference.createClapReference("/simdatavalues.ftl")).get();
TemplateRepresentation templateRepresentation = new TemplateRepresentation(formFtl, templateConfiguration, dataModel, MediaType.TEXT_HTML);
return templateRepresentation;
}
use of org.restlet.representation.Representation in project vcell by virtualcell.
the class NewUserRestlet method handle.
@Override
public void handle(Request request, Response response) {
if (request.getMethod().equals(Method.POST)) {
Representation entity = request.getEntity();
if (entity.getMediaType().equals(MediaType.APPLICATION_JSON)) {
handleJsonRequest(request, response);
return;
}
String content = request.getEntityAsText();
System.out.println(content);
Form form = new Form(entity);
String userid = form.getFirstValue(VCellApiApplication.NEWUSERID_FORMNAME, "");
String password1 = form.getFirstValue(VCellApiApplication.NEWPASSWORD1_FORMNAME, "");
String password2 = form.getFirstValue(VCellApiApplication.NEWPASSWORD2_FORMNAME, "");
String email = form.getFirstValue(VCellApiApplication.NEWEMAIL_FORMNAME, "");
String firstName = form.getFirstValue(VCellApiApplication.NEWFIRSTNAME_FORMNAME, "");
String lastName = form.getFirstValue(VCellApiApplication.NEWLASTNAME_FORMNAME, "");
String institute = form.getFirstValue(VCellApiApplication.NEWINSTITUTE_FORMNAME, "");
String country = form.getFirstValue(VCellApiApplication.NEWCOUNTRY_FORMNAME, "");
String notify = form.getFirstValue(VCellApiApplication.NEWNOTIFY_FORMNAME, "on");
String formprocessing = form.getFirstValue(VCellApiApplication.NEWFORMPROCESSING_FORMNAME, null);
Status status = null;
String errorMessage = "";
// validate
if (!password1.equals(password2)) {
status = Status.CLIENT_ERROR_FORBIDDEN;
errorMessage = "passwords dont match";
}
int MIN_PASSWORD_LENGTH = 5;
if (password1.length() < MIN_PASSWORD_LENGTH || password1.contains(" ") || password1.contains("'") || password1.contains("\"") || password1.contains(",")) {
status = Status.CLIENT_ERROR_FORBIDDEN;
errorMessage = "password must be at least " + MIN_PASSWORD_LENGTH + " characters, and must not contains spaces, commas, or quotes";
}
if (email.length() < 4) {
status = Status.CLIENT_ERROR_FORBIDDEN;
errorMessage = "valid email required";
}
if (userid.length() < 4 || !userid.equals(org.vcell.util.TokenMangler.fixTokenStrict(userid))) {
status = Status.CLIENT_ERROR_FORBIDDEN;
errorMessage = "userid must be at least 4 characters and contain only alpha-numeric characters";
}
if (errorMessage.length() > 0 && formprocessing != null) {
Form newform = new Form();
newform.add(VCellApiApplication.NEWERRORMESSAGE_FORMNAME, errorMessage);
newform.add(VCellApiApplication.NEWUSERID_FORMNAME, userid);
newform.add(VCellApiApplication.NEWPASSWORD1_FORMNAME, password1);
newform.add(VCellApiApplication.NEWPASSWORD2_FORMNAME, password2);
newform.add(VCellApiApplication.NEWEMAIL_FORMNAME, email);
newform.add(VCellApiApplication.NEWFIRSTNAME_FORMNAME, firstName);
newform.add(VCellApiApplication.NEWLASTNAME_FORMNAME, lastName);
newform.add(VCellApiApplication.NEWINSTITUTE_FORMNAME, institute);
newform.add(VCellApiApplication.NEWCOUNTRY_FORMNAME, country);
newform.add(VCellApiApplication.NEWNOTIFY_FORMNAME, notify);
Reference redirectRef;
try {
redirectRef = new Reference(request.getResourceRef().getHostIdentifier() + "/" + VCellApiApplication.REGISTRATIONFORM + "?" + newform.encode());
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
response.redirectSeeOther(redirectRef);
return;
}
// form new UnverifiedUserInfo
UserInfo newUserInfo = new UserInfo();
newUserInfo.company = institute;
newUserInfo.country = country;
newUserInfo.digestedPassword0 = new DigestedPassword(password1);
newUserInfo.email = email;
newUserInfo.wholeName = firstName + " " + lastName;
newUserInfo.notify = notify.equals("on");
newUserInfo.title = " ";
newUserInfo.userid = userid;
Date submitDate = new Date();
// one hour
long timeExpiresMS = 1000 * 60 * 60 * 1;
Date expirationDate = new Date(System.currentTimeMillis() + timeExpiresMS);
DigestedPassword emailVerifyToken = new DigestedPassword(Long.toString(System.currentTimeMillis()));
UnverifiedUser unverifiedUser = new UnverifiedUser(newUserInfo, submitDate, expirationDate, emailVerifyToken.getString());
// add Unverified UserInfo and send email
VCellApiApplication vcellApiApplication = (VCellApiApplication) getApplication();
vcellApiApplication.getUserVerifier().addUnverifiedUser(unverifiedUser);
try {
// Send new password to user
PropertyLoader.loadProperties();
BeanUtils.sendSMTP(PropertyLoader.getRequiredProperty(PropertyLoader.vcellSMTPHostName), new Integer(PropertyLoader.getRequiredProperty(PropertyLoader.vcellSMTPPort)).intValue(), PropertyLoader.getRequiredProperty(PropertyLoader.vcellSMTPEmailAddress), newUserInfo.email, "new VCell account verification", "You have received this email to verify that a Virtual Cell account has been associated " + "with this email address. To activate this account, please follow this link: " + request.getResourceRef().getHostIdentifier() + "/" + VCellApiApplication.NEWUSER_VERIFY + "?" + VCellApiApplication.EMAILVERIFYTOKEN_FORMNAME + "=" + emailVerifyToken.getString());
} catch (Exception e) {
e.printStackTrace();
response.setStatus(Status.SERVER_ERROR_INTERNAL);
response.setEntity("we failed to send a verification email to " + newUserInfo.email, MediaType.TEXT_PLAIN);
}
response.setStatus(Status.SUCCESS_CREATED);
response.setEntity("we sent you a verification email at " + newUserInfo.email + ", please follow the link in that email", MediaType.TEXT_PLAIN);
}
}
use of org.restlet.representation.Representation in project vcell by virtualcell.
the class RegistrationFormRestlet method handle.
@Override
public void handle(Request request, Response response) {
Representation entity = request.getEntity();
Form form = request.getResourceRef().getQueryAsForm();
String userid = form.getFirstValue(VCellApiApplication.NEWUSERID_FORMNAME, "");
String password1 = form.getFirstValue(VCellApiApplication.NEWPASSWORD1_FORMNAME, "");
String password2 = form.getFirstValue(VCellApiApplication.NEWPASSWORD2_FORMNAME, "");
String firstname = form.getFirstValue(VCellApiApplication.NEWFIRSTNAME_FORMNAME, "");
String lastname = form.getFirstValue(VCellApiApplication.NEWLASTNAME_FORMNAME, "");
String email = form.getFirstValue(VCellApiApplication.NEWEMAIL_FORMNAME, "");
String institute = form.getFirstValue(VCellApiApplication.NEWINSTITUTE_FORMNAME, "");
String country = form.getFirstValue(VCellApiApplication.NEWCOUNTRY_FORMNAME, "");
String notifyString = form.getFirstValue(VCellApiApplication.NEWNOTIFY_FORMNAME, "");
String errorMessage = form.getFirstValue(VCellApiApplication.NEWERRORMESSAGE_FORMNAME, "");
String notifyChecked = "unchecked";
if (notifyString.length() == 0 || notifyString.equals("on")) {
notifyChecked = "checked";
}
String html = "<html>\n" + "<form name='login' action='" + "/" + VCellApiApplication.NEWUSER + "' method='post'>\n" + // error message
((errorMessage.length() > 0) ? ("<h2><font color='f00'>" + errorMessage + "</font></h2>") : ("")) + // fields
"userid <input type='text' name='" + VCellApiApplication.NEWUSERID_FORMNAME + "' value='" + userid + "'/>*<br/>\n" + "password <input type='password' name='" + VCellApiApplication.NEWPASSWORD1_FORMNAME + "' value='" + password1 + "'/>* \n" + "retype password <input type='password' name='" + VCellApiApplication.NEWPASSWORD2_FORMNAME + "' value='" + password2 + "'/>*<br/>\n" + "first name <input type='text' name='" + VCellApiApplication.NEWFIRSTNAME_FORMNAME + "' value='" + firstname + "'/>*<br/>\n" + "last name <input type='text' name='" + VCellApiApplication.NEWLASTNAME_FORMNAME + "' value='" + lastname + "'/>*<br/>\n" + "valid email <input type='text' name='" + VCellApiApplication.NEWEMAIL_FORMNAME + "' value='" + email + "'/>*<br/>\n" + "institution <input type='text' name='" + VCellApiApplication.NEWINSTITUTE_FORMNAME + "' value='" + institute + "'/><br/>\n" + "country <input type='text' name='" + VCellApiApplication.NEWCOUNTRY_FORMNAME + "' value='" + country + "'/><br/>\n" + "notify <input type='checkbox' name='" + VCellApiApplication.NEWNOTIFY_FORMNAME + "' value='on' checked='" + notifyChecked + "'/><br/>\n" + "<input type='hidden' name='" + VCellApiApplication.NEWFORMPROCESSING_FORMNAME + "' value='yes'/><br/>\n" + // submit button
"<input type='submit' value='register'/>\n" + "</form>\n" + "<h3>* : required</h3>\n" + "</html>\n";
response.setEntity(html, MediaType.TEXT_HTML);
}
Aggregations