I am new to Camel and learning to setup routes.
So I started with a simple scenario, a URL that I hit and it returns me some data. For this example I have used http://services.groupkt.com/country/get/all for returning that data.
This is the setup for my path
from("direct:greet")
.autoStartup(true)
.routeId("greet")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.GET))
.to("http4://services.groupkt.com/country/get/all")
Now I have requestMapping to a URL /check and when I hit this URL http://localhost:8080/check it returns this
{
"timestamp": 1527882311362,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/check"
}
I was expecting the JSON response to show up with the data for all the countries listed which you see when you hit the URL(http://services.groupkt.com/country/get/all) in your browser.
The mapping is in other class:
#RequestMapping(value = "/check", method = RequestMethod.GET)
public String get(#RequestParam(value = "name") String name) {
return serviceProcessor.getServiceResponse(name);
getServiceResponse goes as follows:
public String getServiceResponse(String name) {
final ModelCamelContext context = userServiceRoute.getContext();
final ProducerTemplate template = new DefaultProducerTemplate(context);
try {
template.start();
} catch (Exception e) {
LOGGER.error("Error starting producerTemplate with userServiceRoute" + e);
}
final Endpoint endpoint = context.getEndpoint("direct:greet");
template.setDefaultEndpoint(endpoint);
return template.requestBody((Object)name, String.class);
}
Is there something wrong with the path setup or the approach itself is wrong here?
Related
I am trying to send json data from angularjs service to controller in spring.
But getting error:
angular.js:10661 POST http://localhost:8080/shoping/product/add 500 (Internal Server Error)
product_service.js:35 Error while adding product
product_controller.js:30 {productId: null, productName: "sdfv", productPrice: 43, description: "sfdv", imageUrl: "csd"}
This is my function in service in angularJs
function addProduct(product){
var deferred = $q.defer();
$http.post(REST_SERVICE_URI+"add", product)
.then(
function(response){
deferred.resolve(response.data);
},
function(errResponse){
console.log('Error while adding product');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
This is my method in spring controller
#RestController
#RequestMapping("/product/")
public class ProductRestController {
#Autowired
ProductDao productDao;
RequestMapping(value = "add", method= RequestMethod.POST, consumes="application/json")
public ResponseEntity<Void> createProduct(#RequestBody Product product) {
System.out.println("Creating Product " + product.getProductName());
if (productDao.isProductExit(product)) {
System.out.println("A Product with name " + product.getProductName() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
productDao.add(product);
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
Also I have a $http.delete method in angular service
$http.delete(REST_SERVICE_URI+"delete/"+id)
And there is also an error saying Syntax error on token ".", , expected
UPDATE
Product.java
#Entity
#Table(name ="product")
public class Product implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "product_price")
private Float productPrice;
#Column(name = "description")
private String description;
#Column(name = "image_url")
private String imageUrl;
//getter and setter
UPDATE: 2
Sorry the NUllPointerException was occuring when I tried to send empty json . There is no error in the spring console
MainController.java
#Controller
#RequestMapping("/")
public class MainController {
#Autowired
UserDao userDao;
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public String defaultPage() {
return "ProductManagement";
}
Now the error in angluar is :
angular.js:10661 POST http://localhost:8080/shoping/product/add 404 (Not Found)
UPDATE 3:
When I make get request instead of post then it is not giving error but adding empty value data in database and it also doesn't support media type json. Now I think that most probably the problem is in the URI and http request.
Here is my github repo of the project : https://github.com/Bk073/Shopping
From this amount of information (no logs) it seems there must be something wrong with JDBC. If everything has been set as default, then I suppose that the id must be auto increment and sending it a null without catching any exceptions just might be the cause... try to omit id from your product object (json) and see what happens...
I have problem when I try to send message from client to server on Spring websocket.
I have configuration Websocket on server and create #Message on controller.
I send data from client via javascript.
It just work sometimes, but sometimes it fail and throw message on server: MissingSessionUserException: No "user" header in message
Here're my WebsocketConfig:
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/connectsocket").withSockJS();
}
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/");
}
}
Here're my MessageController:
#RestController
public class MessageController {
#Autowired
private SimpMessagingTemplate template;
#MessageMapping("/websocket/message")
public synchronized void message(Message<Object> messageObj,
WebMessage message, Principal principal) throws Exception {
if (principal != null) {
String name = principal.getName();
template.convertAndSendToUser(name, "/topic/dynamic", new MessagePojo("stage", "value", "message"));
}
}
}
Here're my Javascript-backbonejs code:
app.Models.WebsocketModel = Backbone.Model.extend({
fetchData : function() {
console.log("WebsocketModel: fetchData");
var socket = new SockJS(url + "/connectsocket");
var client = Stomp.over(socket);
var onConnect = function(frame) {
console.log('Connected: ' + frame);
client.subscribe("/user/topic/dynamic", function(data) {
var jsonBody = JSON.parse(data.body);
console.log(jsonBody);
});
};
client.connect({}, onConnect);
setInterval(function() {
client.send("/websocket/message", {}, JSON.stringify({
"message" : "Hello world!!!",
"toUser" : "Someone"
}));
}, 10000);
}
});
Here're my server error log:
[2016 Apr 14 - 02:13:19] ERROR:
[org.springframework.web.socket.messaging.WebSocketAnnotationMethodMessageHandler]
- Unhandled exception org.springframework.messaging.simp.annotation.support.MissingSessionUserException:
No "user" header in message at
org.springframework.messaging.simp.annotation.support.PrincipalMethodArgumentResolver.resolveArgument(PrincipalMethodArgumentResolver.java:42)
at
org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
at
org.springframework.messaging.handler.invocation.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:139)
at
org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:108)
at
org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMatch(AbstractMethodMessageHandler.java:490)
at
org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.handleMatch(SimpAnnotationMethodMessageHandler.java:497)
at
org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.handleMatch(SimpAnnotationMethodMessageHandler.java:87)
at
org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessageInternal(AbstractMethodMessageHandler.java:451)
at
org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.handleMessage(AbstractMethodMessageHandler.java:389)
at
org.springframework.messaging.support.ExecutorSubscribableChannel$SendTask.run(ExecutorSubscribableChannel.java:135)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
You are trying to subscribe to a user destination so the user must be authenticated.
If that is an anonymous user who want to subscribe to the topic, answer to this question will help.
You'll have to assign an anonymous identify to the user and there are two options:
Configure a sub-class of DefaultHandshakeHandler that overrides determineUser and assigns some kind of identity to every WebSocketSession.
The WebSocket session will fall back on the value returned from HttpServletRequest.getUserPrincipal on the handshake HTTP request. You could have a servlet Filter wrap the HttpServletRequest and decide what to return from that method. Or if you're using Spring Security which has the AnonymousAuthenticationFilter, override its createAuthentication method.
I am trying to call a Google Cloud Endpoint API (developed on App Engine) via Google Apps Script. The endpoint is up and running, honestly I don't know which URL I should use but through Google Chrome Web Tools it looks like the URL is something like:
https://myapp.appspot.com/_ah/api/myendpointapi/v1/myEndPointMethod/
Along with API parameters directly included in the URL, separeted by slashes:
https://myapp.appspot.com/_ah/api/myendpointapi/v1/myEndPointMethod/param1value/param2value/...
Now, in order to call that API from Google App Script I am using the following code snippet:
function myFunction() {
var params =
{
"param1" : "param1value",
"param2" : "param2value",
};
var result = UrlFetchApp.fetch('https://myapp.appspot.com/_ah/api/myendpointapi/v1/myEndPointMethod/', params);
DocumentApp.getUi().alert(result);
}
However I always get a 404 error. If I have to be honest I don't even know if UrlFetchApp is the correct way of calling the API. I noticed this thread on StackOverflow but no one answered. What's the correct URL to use? Many thanks.
EDIT: Now I am trying with an API method which does not require any parameter. I found a way to call a specific URL (using method='get' as suggested by the answer below) but now I get a 401 error because it says I am not logged in. I believe I need to use some kind of OAuth parameter now. Any idea? I tryed using OAuthConfig but no luck with that as well :( From App Engine logs I can see the following error:
com.google.api.server.spi.auth.GoogleIdTokenUtils verifyToken: verifyToken: null
com.google.api.server.spi.auth.AppEngineAuthUtils getIdTokenEmail:
getCurrentUser: idToken=null
function myFunction() {
var result = UrlFetchApp.fetch('myurl', googleOAuth_());
result = result.getContentText();
}
function googleOAuth_() {
var SCOPE = 'https://www.googleapis.com/auth/drive';
var NAME = 'myAPIName';
var oAuthConfig = UrlFetchApp.addOAuthService(NAME);
oAuthConfig.setRequestTokenUrl('https://www.google.com/accounts/OAuthGetRequestToken?scope='+SCOPE);
oAuthConfig.setAuthorizationUrl('https://www.google.com/accounts/OAuthAuthorizeToken');
oAuthConfig.setAccessTokenUrl('https://www.google.com/accounts/OAuthGetAccessToken');
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:NAME, oAuthUseToken:'always'};
}
UrlFetchApp is the only way to call a Google Cloud Endpoints API at the moment. The second parameter to UrlFetchApp.fetch is a special key-value map of advanced options. To pass POST parameters, you need to do the following:
UrlFetchApp.fetch(url, {
method: 'post',
payload: {
"param1" : "param1value",
"param2" : "param2value",
}
});
I was fighting a similar (not the same) problem, when testing feasibility of a GCM backed by EndPoints server. Basically testing if it is possible to get the Google Spreadsheet Appscript to send notification to an Android device. Please bear with me, the following explanation may be a bit convoluted;
Starting with a standard 'Cloud Messaging for Android', backed by the 'App Engine Backend with Google Cloud Messaging', I managed to build a test system that would send messages between Android devices (Github here).
Here is a VERY sparse EndPoints server code that handles register / un-register Android devices, as well as reporting registered devices and sending a message to a list of registered devices.
WARNING: This is not a production quality code, it is stripped of any logging, error handling in order to keep it short.
#Api( name = "gcmEP", version = "v1",
namespace = #ApiNamespace(ownerDomain = "epgcm.example.com", ownerName = "epgcm.example.com", packagePath = "" )
)
public class GcmEP {
#ApiMethod(name = "registToken")
public void registToken(#Named("token") String token) {
if (ofy().load().type(TokenRec.class).filter("token", token).first().now() == null) {
ofy().save().entity(new TokenRec(token)).now();
}
}
#ApiMethod(name = "unregToken")
public void unregToken(#Named("token") String token) {
TokenRec record = ofy().load().type(TokenRec.class).filter("token", token).first().now();
if (record != null) {
ofy().delete().entity(record).now();
}
}
#ApiMethod(name = "listTokens")
public CollectionResponse<TokenRec> listTokens() {
return CollectionResponse.<TokenRec>builder().setItems(ofy().load().type(TokenRec.class).list()).build();
}
#ApiMethod(name = "sendMsg")
public void sendMsg(#Named("message") String message) throws IOException {
if (message != null && message.length() > 0) {
Sender sender = new Sender(System.getProperty("gcm.api.key"));
Message msg = new Message.Builder().addData("message", message).build();
for (TokenRec record : ofy().load().type(TokenRec.class).list()) {
Result result = sender.send(msg, record.getToken(), 4);
if (result.getMessageId() != null) {
// handle CanonicalRegistrationId
} else {
// handle errors, delete record
}
}
}
}
}
Android code for registration and message sending is shown here, even if it is not relevant.
GcmEP mRegSvc;
String mToken;
// register device on EndPoints backend server
private void registerMe() {
new Thread(new RegisterMe(this)).start();
}
private class RegisterMe implements Runnable {
Activity mAct;
public RegisterMe(Activity act) { mAct = act; }
public void run() {
String senderId = null;
if (mAct != null) try {
if (mRegSvc == null) {
mRegSvc = new GcmEP
.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null).setRootUrl(UT.ROOT_URL).build();
}
senderId = getString(R.string.gcm_defaultSenderId);
mToken = InstanceID.getInstance(mAct).getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
mRegSvc.registToken(mToken).execute();
GcmPubSub.getInstance(mAct).subscribe(mToken, "/topics/global", null); // subscribing to all 'topics' from 'mToken'
} catch (IOException e) { e.printStackTrace(); }
}
}
// send message to EndPoints backend server
new Thread(new Runnable() {
#Override
public void run() {
if (mRegSvc != null) try {
mRegSvc.sendMsg("hello").execute();
} catch (IOException e) { e.printStackTrace(); }
}
}).start();
// receive GCM message
public class GcmListenSvc extends GcmListenerService {
#Override
public void onMessageReceived(String senderId, Bundle data) {
Log.i("_X_", data.getString("message"));
}
}
What is relevant, thought, there is also an APIs Explorer created for the project, that can be used to send messages to your Android device from any browser.
If you use this Explorer, you can see the GET, POST requests for your EndPoints backend server, i.e.
list all registered devices:
GET https://epgcm.appspot.com/_ah/api/gcmEP/v1/tokenrec?fields=items
send a message to all registered devices:
POST https://epgcm.appspot.com/_ah/api/gcmEP/v1/sendMsg/Hello%20World!
Now, you can use this knowledge to send messages to your Android device from an AppScript code as shown:
Version 1: Get list of registered devices and send a GCM message to all of them (or a filtered set).
function sendMsg() {
var msg = 'test from CODE.GS';
var url = 'https://epgcm.appspot.com/_ah/api/gcmEP/v1/tokenrec?fields=items';
var params = { method : 'get'};
var response = UrlFetchApp.fetch(url, params);
var data = JSON.parse(response.getContentText());
var regIds = [];
for (i in data.items)
regIds.push(data.items[i].token);
var payload = JSON.stringify({
'registration_ids' : regIds,
'data' : { 'message' : msg }
});
var params = {
'contentType' : 'application/json',
'headers' : {'Authorization' : 'key=AIza............................'},
'method' : 'post',
'payload' : payload
};
url = 'https://android.googleapis.com/gcm/send';
UrlFetchApp.fetch(url, params);
}
This version relies on code from an old YouTube video, and I don't know if the call to 'android.googleapis.com' is still supported (but it works).
Version 2: Use the EndPoints's 'sendMsg' directly.
function sendMsg() {
var msg = 'test from CODE.GS';
var params = { method : 'post'};
var url = 'https://demoepgcm.appspot.com/_ah/api/gcmEP/v1/sendMsg/' + encodeURIComponent(msg.trim());
UrlFetchApp.fetch(url, params);
}
I have to admit I've never written a line of JavaScript code before, so it may not be up-to-par, but I made it work as a 'proof of concept'.
I would like to get feedback about this problem from people-who-know, since there is so little published info on this specific issue.
I have OpenID login in GAE:
private static final Map<String, String> openIdProviders;
static {
openIdProviders = new HashMap<String, String>();
openIdProviders.put("Google", "https://www.google.com/accounts/o8/id");
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
UserService userService = UserServiceFactory.getUserService();
Principal princ = req.getUserPrincipal();
Set<String> attributes = new HashSet<String>();
String provider =req.getParameter("openIdProvider");
for (String providerName : openIdProviders.keySet()) {
String providerUrl = openIdProviders.get(providerName);
if(providerName.equals(provider)){
String loginUrl = userService.createLoginURL("/test/manager.jsp", null, providerUrl, attributes);
resp.sendRedirect(loginUrl);
return;
}
}
}
Everything Works greate!
BUT I need to redirect to WEB-INF/test/manager.jsp
I know that I cant do this without RequestDispatcher.
1 QUESTION when I use RequestDispatcher for loginUrl :
RequestDispatcher dispatch = req.getRequestDispatcher(loginUrl);
dispatch.forward(req, resp);
I have error
java.lang.NullPointerException at com.google.appengine.api.users.dev.LoginCookieUtils.encodeEmailAsUserId(LoginCookieUtils.java:91)
Quesiton 2.
Then I try another sulotuion (redirect to the servlet. in this UserProfilePanel servlet I' will use RequestDispatcher .
String loginUrl = userService.createLoginURL("/UserProfilePanel", null, providerUrl, attributes);
resp.sendRedirect(loginUrl);
But, I have then that error:
Problem accessing /UserProfilePanel. Reason:
Response has already been committed
Caused by:
java.lang.IllegalStateException: Response has already been committed
at com.google.appengine.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:153)
I was testing at localhost: I was tedirected to localhost:8888/_ah/login?continue=/FUserProfilePanel when I enter my mail, error of "Response has already been committed".
what can I do? I cant find solutions
in a remember, things in WEB-INF folder couldn't be served like you seems to want to do.
Try to put you test.jsp file somewhere "normal" ( root or in a subfolder of root)
I've been trying this for hours, so maybe a fresh set of eyes will help.
I'm trying to upload a file to the server using GWT (using UiBinder) on Google App Engine. Following all the examples I can find, things look like they should work, but the server's 'post' method is showing 0 items uploaded.
Here's the client code:
FormUploader.ui.xml:
<g:FormPanel action="/formImageUploader" ui:field="formPanel">
<g:VerticalPanel>
<g:FileUpload ui:field="uploader"></g:FileUpload>
<g:Button ui:field="submit">Submit</g:Button>
</g:VerticalPanel>
</g:FormPanel>
FormUploader.java:
#UiField
FormPanel formPanel;
#UiField
FileUpload uploader;
#UiField
Button submit;
public FormUploader() {
initWidget(uiBinder.createAndBindUi(this));
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.setMethod(FormPanel.METHOD_POST);
addSubmitHandlers();
}
private void addSubmitHandlers() {
formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
Core.log("Inside submitComplete");
Window.alert(event.getResults());
}
});
}
web.xml:
<servlet>
<servlet-name>formImageUploader</servlet-name>
<servlet-class>com.company.server.FormImageUploader</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>formImageUploader</servlet-name>
<url-pattern>/formImageUploader</url-pattern>
</servlet-mapping>
FormImageUploader.java:
public class FormImageUploader extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
log.info("Request.getContentLength(): " + request.getContentLength());
log.info("Content type: " + request.getContentType());
log.info("Parm names: ");
for (Object paramName : request.getParameterMap().keySet()) {
log.info("__Param name: " + paramName.toString());
}
log.info("Attribtue names: ");
Enumeration enu = request.getAttributeNames();
while (enu.hasMoreElements()) {
log.info("__Attribute name: " + enu.nextElement().toString());
}
log.info("Header names: ");
enu = request.getHeaderNames();
while (enu.hasMoreElements()) {
log.info("__Header name: " + enu.nextElement().toString());
}
resp.getWriter().println("Post Code has finished executing");
}
All this executes just fine, the client shows an alert box containing Post Code has finished executing, but I can't figure out how to get the content of the file I want to upload.
Here's the server side log:
Request.getContentLength(): 63
Content type: multipart/form-data; boundary=---------------------------194272772210834546661
Parm names:
Attribtue names:
__Attribute name: com.google.apphosting.runtime.jetty.APP_VERSION_REQUEST_ATTR
Can anyone help me see why I'm not seeing any files on the server after clicking "submit" on the client?
Thanks in advance
Edit:
Still can't figure out why I can't get the form data on the server. I'm following this example, and just trying to write the response out to the client, but the server is definitely not seeing any content from the client.
Server code:
try {
log.info("Inside try block");
ServletFileUpload upload = new ServletFileUpload();
log.info("created the servlet file upload");
res.setContentType("text/plain");
log.info("set the content type to text/plain");
FileItemIterator iterator = upload.getItemIterator(req);
log.info("Got the iterator for items");
while (iterator.hasNext()) {
log.info("__inside iterator.hasNext");
FileItemStream item = iterator.next();
log.info("__assigned the file item stream");
InputStream stream = item.openStream();
log.info("__opened said stream");
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName());
} else {
log.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
res.getOutputStream().write(buffer, 0, len);
}
log.info("Done writing the input to the output stream");
}
}
} catch (Exception ex) {
log.severe("Exception; " + ex);
throw new ServletException(ex);
}
log.info("Done parseInput3");
Logs:
Inside parseInput3
Inside try block
created the servlet file upload
set the content type to text/plain
Got the iterator for items
Done parseInput3
Again, it's definitely not able to iterate over the file items on the server... any idea why?
Turns out, GAE has a completely different way of uploading files (Blobs):
http://code.google.com/appengine/docs/java/blobstore/overview.html#Uploading_a_Blob
You need to supply the form's on the client with a Blobstore Upload URL (which times out) from the server, retrieved using:
blobstoreService.createUploadUrl('urlToRedirectToAfterUploadComplete')
After setting that upload URL on the form's action, the form will be submitted and the blobstore service will redirect to the supplied URL, which can then access the BlobKey of the object stored by Google.
So with this, I added the following ChangeHandler to my GWT FileUpload:
private void addChangeListener() {
Core.log("Selected file: " + uploader.getFilename());
uploader.addChangeHandler(new ChangeHandler() {
#Override
public void onChange(ChangeEvent event) {
MyApp.SERVICES.getUploadUrl(new SuccessAsyncCallback<String>() {
#Override
public void onSuccess(String uploadUrl) {
form.setAction(uploadUrl);
form.submit();
Core.log("Submitted form with upload url: " + uploadUrl);
}
});
}
});
}
Then in the servlet I have the GAE redirect to after uploads:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws Exception {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
// where 'uploader' is the name of the FileUploader (<input type='file'>) control on the client
List<BlobKey> blobKeys = blobs.get("uploader");
resp.getOutputStream().print(blobKeys.get(0).getKeyString());
}
Note!
GAE will throw a OutOfMemory exception when trying to get the uploaded blob's value if the FileUpload control doesn't have a name="whateveryouwantthenametobe" attribute defined, even if you tell it (using UiBinder) that the id is ui:field="nameofControl"
You cannot write to the local file system - you should take a look at the files api.