I have a project where you can ask for resources that are served by jax-rs in the json format. Everything works properly in the browser when I query the rest URL the json appears.
Now I want my GWT project to request those resources and process them and show them in my interface. The simplest way I found to do so is using a request builder and an overlay. Code is lower. The problem is, it seems when the code is running it never goes into the actual RequestCallback(). The status string is never changed. I thought it could be a SOP so I added the <add-linker name="xs"/> but still doesn't work. Any ideal?
package com.workoutcell.client;
//import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.http.client.*;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
/**
*
* #author
*/
public class RestToInfoSession{
String queryReturn = null;
JsArray<InfoJSO> arrayOfInfo = null;
String host = "http://localhost:8080/mysite";
String restModule = "/calendar/getinfo";
String id = null;
String year = null;
String month = null;
String status = "Not Initialized";
public RestToInfoSession(String id, String year, String month){
this.id =id;
this.year = year;
this.month = month;
String url = host + restModule + "/"+this.id + "/"+this.year + "/"+this.month;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
status = "Initialized at Url " + builder.getUrl();
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
status = "Error on connecting to Server";
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// arrayOfInfo = jsonToJsArray(response.getText());
status = "JSON has been Fetched. Result is:" + response.getText();
} else if(0 == response.getStatusCode()) {
status = "Error is 0";
} else {
status = "Error in JSON Request:" + response.getStatusCode();
//response.getStatusText();
}
}
});
} catch (RequestException ex) {
status = "Error in Request Builder Startup";
}
}
//get an jso object in array
private final native JsArray<InfoJSO> jsonToJsArray(String json) /*-{
return eval(json);
}-*/;
public JsArray<InfoJSO> getInfoArray (){
return arrayOfInfo;
}
}
UPDATE: My problem is the same as Referring to a non-final variable data inside an inner class . I wasn't aware of asynchronous calls working mechanism. I still don't know how to pass my response.getText() to update a label that isn't part of my RestToInfoSession class any ideas?
Consider using the RestyGWT project. It will make calling JAXRS JSON resources as easy as using GWT-RPC. Plus you can typically reuse the same request response DTOs from the server side on the client side.
I have put a timer that checks every 1000ms if my json string has updated from null to the xhttp requested data. This works, but I got a feeling there is a more elegant way of resolving this problem.
Related
First, I want to say thanks to everyone that took their time to help me figure this out because I was searching for more than a week for a solution to my problem. Here it is:
My goal is to start a custom workflow in Alfresco Community 5.2 and to set some custom properties in the first task trough a web script using only the Public Java API. My class is extending AbstractWebScript. Currently I have success with starting the workflow and setting properties like bpm:workflowDescription, but I'm not able to set my custom properties in the tasks.
Here is the code:
public class StartWorkflow extends AbstractWebScript {
/**
* The Alfresco Service Registry that gives access to all public content services in Alfresco.
*/
private ServiceRegistry serviceRegistry;
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
#Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
// Create JSON object for the response
JSONObject obj = new JSONObject();
try {
// Check if parameter defName is present in the request
String wfDefFromReq = req.getParameter("defName");
if (wfDefFromReq == null) {
obj.put("resultCode", "1 (Error)");
obj.put("errorMessage", "Parameter defName not found.");
return;
}
// Get the WFL Service
WorkflowService workflowService = serviceRegistry.getWorkflowService();
// Build WFL Definition name
String wfDefName = "activiti$" + wfDefFromReq;
// Get WorkflowDefinition object
WorkflowDefinition wfDef = workflowService.getDefinitionByName(wfDefName);
// Check if such WorkflowDefinition exists
if (wfDef == null) {
obj.put("resultCode", "1 (Error)");
obj.put("errorMessage", "No workflow definition found for defName = " + wfDefName);
return;
}
// Get parameters from the request
Content reqContent = req.getContent();
if (reqContent == null) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing request body.");
}
String content;
content = reqContent.getContent();
if (content.isEmpty()) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Content is empty");
}
JSONTokener jsonTokener = new JSONTokener(content);
JSONObject json = new JSONObject(jsonTokener);
// Set the workflow description
Map<QName, Serializable> params = new HashMap();
params.put(WorkflowModel.PROP_WORKFLOW_DESCRIPTION, "Workflow started from JAVA API");
// Start the workflow
WorkflowPath wfPath = workflowService.startWorkflow(wfDef.getId(), params);
// Get params from the POST request
Map<QName, Serializable> reqParams = new HashMap();
Iterator<String> i = json.keys();
while (i.hasNext()) {
String paramName = i.next();
QName qName = QName.createQName(paramName);
String value = json.getString(qName.getLocalName());
reqParams.put(qName, value);
}
// Try to update the task properties
// Get the next active task which contains the properties to update
WorkflowTask wfTask = workflowService.getTasksForWorkflowPath(wfPath.getId()).get(0);
// Update properties
WorkflowTask updatedTask = workflowService.updateTask(wfTask.getId(), reqParams, null, null);
obj.put("resultCode", "0 (Success)");
obj.put("workflowId", wfPath.getId());
} catch (JSONException e) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST,
e.getLocalizedMessage());
} catch (IOException ioe) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST,
"Error when parsing the request.",
ioe);
} finally {
// build a JSON string and send it back
String jsonString = obj.toString();
res.getWriter().write(jsonString);
}
}
}
Here is how I call the webscript:
curl -v -uadmin:admin -X POST -d #postParams.json localhost:8080/alfresco/s/workflow/startJava?defName=nameOfTheWFLDefinition -H "Content-Type:application/json"
In postParams.json file I have the required pairs for property/value which I need to update:
{
"cmprop:propOne" : "Value 1",
"cmprop:propTwo" : "Value 2",
"cmprop:propThree" : "Value 3"
}
The workflow is started, bpm:workflowDescription is set correctly, but the properties in the task are not visible to be set.
I made a JS script which I call when the workflow is started:
execution.setVariable('bpm_workflowDescription', 'Some String ' + execution.getVariable('cmprop:propOne'));
And actually the value for cmprop:propOne is used and the description is properly updated - which means that those properties are updated somewhere (on execution level maybe?) but I cannot figure out why they are not visible when I open the task.
I had success with starting the workflow and updating the properties using the JavaScript API with:
if (wfdef) {
// Get the params
wfparams = {};
if (jsonRequest) {
for ( var prop in jsonRequest) {
wfparams[prop] = jsonRequest[prop];
}
}
wfpackage = workflow.createPackage();
wfpath = wfdef.startWorkflow(wfpackage, wfparams);
The problem is that I only want to use the public Java API, please help.
Thanks!
Do you set your variables locally in your tasks? From what I see, it seems that you define your variables at the execution level, but not at the state level. If you take a look at the ootb adhoc.bpmn20.xml file (https://github.com/Activiti/Activiti-Designer/blob/master/org.activiti.designer.eclipse/src/main/resources/templates/adhoc.bpmn20.xml), you can notice an event listener that sets the variable locally:
<extensionElements>
<activiti:taskListener event="create" class="org.alfresco.repo.workflow.activiti.tasklistener.ScriptTaskListener">
<activiti:field name="script">
<activiti:string>
if (typeof bpm_workflowDueDate != 'undefined') task.setVariableLocal('bpm_dueDate', bpm_workflowDueDate);
if (typeof bpm_workflowPriority != 'undefined') task.priority = bpm_workflowPriority;
</activiti:string>
</activiti:field>
</activiti:taskListener>
</extensionElements>
Usually, I just try to import all tasks for my custom model prefix. So for you, it should look like that:
import java.util.Set;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.apache.log4j.Logger;
public class ImportVariables extends AbstractTaskListener {
private Logger logger = Logger.getLogger(ImportVariables.class);
#Override
public void notify(DelegateTask task) {
logger.debug("Inside ImportVariables.notify()");
logger.debug("Task ID:" + task.getId());
logger.debug("Task name:" + task.getName());
logger.debug("Task proc ID:" + task.getProcessInstanceId());
logger.debug("Task def key:" + task.getTaskDefinitionKey());
DelegateExecution execution = task.getExecution();
Set<String> executionVariables = execution.getVariableNamesLocal();
for (String variableName : executionVariables) {
// If the variable starts by "cmprop_"
if (variableName.startsWith("cmprop_")) {
// Publish it at the task level
task.setVariableLocal(variableName, execution.getVariableLocal(variableName));
}
}
}
}
Hello I am using a webservice which returns a output upon completion of code execution. Is it possible that webservice may return the status in chunks like custom strings: Test Started, Test In Progress, Test Completed etc.
What I need to do to achieve this. Here is my current code where I am expecting a json string as input, supplied json is parsed and further processing is being performed.
//Class
public class WebserviceClient
{
/** calling constructor to initialize logger */
Utils c = new Utils();
Logger logger = Logger.getLogger(WebserviceClient.class.getName());
#Path("/test")
#POST
#Consumes(MediaType.APPLICATION_JSON)
//#Produces(MediaType.APPLICATION_JSON)
public String processRequest(final String inputData)
{
String executionID = "NOT_FOUND" ;
String result = "";
try
{
/** creating a pool of threads to submit a task to a callable thread */
ExecutorService ex = Executors.newFixedThreadPool(5);
Future<String> futureObject = ex.submit(new Callable<String>() {
#Override
public String call() throws Exception
{
logger.info("Parsing Received Request: "+inputData);
String rID = new JSONObject(inputData).getString("id");
logger.info("Received Id: "+rID + " From Request: "+inputData);
if(new RunTest().isTestCompleted(rID))
{
return rID;
}
else
{
return "777";
}
}
});
result = futureObject.get();
if(futureObject.get()!=null)
{
ex.shutdown();
}
else{
logger.debug("call id: "+executionID +" result is not generated yet. ");
}
logger.info("call id && Result: "+result);
}
catch(Exception e)
{
logger.error("call id: "+executionID, e);
}
return result;
}
}
You need to do a continuous polling to the server at high frequency to achieve the current status.
For little more information have a look at the :
Continuous polling of output using spring ,rest and angular js
This includes design consideration of using WebSockets etc, but there is no straight forward solution that I'm aware of.
I am trying to update a Confluence page using this code:
https://bitbucket.org/jaysee00/confluence-rest-api-example/src/master/src/main/java/com/atlassian/api/examples/Main.java
Code is:
public class Confluence {
/**
* Demonstrates how to update a page using the Conflunence 5.5 REST API.
*/
private static final Logger LOGGER = Logger.getLogger(Confluence.class);;
private static final String BASE_URL = "http://confluence:8080";
private static final String USERNAME = "admin";
private static final String PASSWORD = "admin";
private static final String ENCODING = "utf-8";
private String getContentRestUrl(Long contentId, String[] expansions)
throws UnsupportedEncodingException {
String expand = URLEncoder.encode(StringUtils.join(expansions, ","),
ENCODING);
return String
.format("%s/rest/api/content/%s?expand=%s&os_authType=basic&os_username=%s&os_password=%s",
BASE_URL, contentId, expand,
URLEncoder.encode(USERNAME, ENCODING),
URLEncoder.encode(PASSWORD, ENCODING));
}
public void publish() throws ClientProtocolException, IOException, Exception {
final long pageId = 36307446;
HttpClient client = new DefaultHttpClient();
// Get current page version
String pageObj = null;
HttpEntity pageEntity = null;
try {
String restUrl = getContentRestUrl(pageId,
new String[] { "body.storage", "version", "ancestors" });
HttpGet getPageRequest = new HttpGet(restUrl);
HttpResponse getPageResponse = client.execute(getPageRequest);
pageEntity = getPageResponse.getEntity();
pageObj = IOUtils.toString(pageEntity.getContent());
LOGGER.info("Get Page Request returned "
+ getPageResponse.getStatusLine().toString());
LOGGER.info(pageObj);
LOGGER.info((int)pageObj.trim().charAt(0));
} finally {
if (pageEntity != null) {
EntityUtils.consume(pageEntity);
}
}
// Parse response into JSON
JSONObject page = new JSONObject(pageObj.trim());
// Update page
// The updated value must be Confluence Storage Format
// NOT HTML.
page.getJSONObject("body").getJSONObject("storage")
.put("value", "hello, world");
int currentVersion = page.getJSONObject("version").getInt("number");
page.getJSONObject("version").put("number", currentVersion + 1);
// Send update request
HttpEntity putPageEntity = null;
try {
HttpPut putPageRequest = new HttpPut(getContentRestUrl(pageId,
new String[] {}));
StringEntity entity = new StringEntity(page.toString());
entity.setContentType("application/json");
putPageRequest.setEntity(entity);
HttpResponse putPageResponse = client.execute(putPageRequest);
putPageEntity = putPageResponse.getEntity();
System.out.println("Put Page Request returned "
+ putPageResponse.getStatusLine().toString());
System.out.println("");
System.out.println(IOUtils.toString(putPageEntity.getContent()));
} finally {
EntityUtils.consume(putPageEntity);
}
}
}
The response is alway 'HTTP 404 - Page not found'. I have changed the page id to one I know exists in Confluence.
An exception follows when it tries to parse the response into a JSON object:
avvvaorg.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
at com.openet.report.publish.Confluence.publish(Confluence.java:74)
at com.openet.report.miner.ReportMiner.generateSummary(ReportMiner.java:268)
at com.openet.report.miner.ReportMiner.runReport(ReportMiner.java:251)
at com.openet.report.miner.ReportMiner.main(ReportMiner.java:138)
Updating confluence pages using REST is not supported by Confluence 4.3.1. The API is much more limited:
https://docs.atlassian.com/atlassian-confluence/REST/4.3.1/
You can however update confluence using XML RPC:
public void publish() throws IOException {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
XWikiXmlRpcClient rpc = new XWikiXmlRpcClient(CONFLUENCE_URI);
try {
rpc.login(USER_NAME, PASSWORD);
//The info macro would get rendered an info box in the Page
Page page = new Page();
page.setSpace("Some space");
page.setTitle("Testing XML RPC calls in confluence_" + df.format(today));
//page.setContent(
String s = String.format("||Heading 1||Heading 2||Heading 3||%s|col A1|col A2|col A3|", "\r\n");
page.setContent(s);
page.setParentId(PAGEID);
rpc.storePage(page);
} catch (XmlRpcException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated catch block
}
This requires the following libraries:
import org.apache.xmlrpc.XmlRpcException;
import org.codehaus.swizzle.confluence.Page;
import org.w3c.dom.Document;
import org.xwiki.xmlrpc.XWikiXmlRpcClient;
Note that these libraries are not in the standard maven repository. You will have to update your repository manager (artifactory in my case) to sync with the XWiki maven repo. You will also need the service rocket plugin (https://community.servicerocket.com/servicerocket/topics/the-license-could-not-be-verified-there-is-no-license-certificate-installed-for-customware-scaffolding-plugin-for-confluence) configured correctly on Confluence.
I've been using JPA in the Play Framework for some time now, and everything was going fine - however, I have now come up against an error which I'm not seeing any obvious solutions to. Just for some context, what I am trying to create is a basic social network.
I have a Post class:
public class Post extends Model {
private String owner;
private long timestamp;
#ElementCollection
private List<String> viewers;
private String content;
public Post(String owner, List<String> viewers, String content) {
this.timestamp = System.currentTimeMillis();
this.owner = owner;
this.viewers = viewers;
this.content = content;
System.out.println("Saving post by " + owner + " with timestamp:" + this.timestamp);
}
(Getters and setters ignored here)
}
I have a User class which adds posts:
public long addPost(String viewers, String content) {
LinkedList<String> viewersList = new LinkedList(Arrays.asList(viewers.split(",")));
Post newPost = new Post(this.name, viewersList, content);
newPost.save();
return newPost.getTimestamp();
}
And I have a StreamManager handling notification of posts and retrieval of posts.
public static void executePost(String content, String viewers) {
System.out.println("Post content: " + content);
String user = session.get("username");
User u = User.connect(user);
if (u == null) {
System.out.println("User is null");
}
/* Add post to local record of posts */
long timestamp = u.addPost(viewers, content);
/* Send notification of post to server */
}
I'm running my application with a thread pool of 3 threads, which means that there is some amount of concurrency in the system. While the system is waiting for a response from the server after notification (end of executePost), another thread is trying to access the newly created Post using this code:
public static void retrievePost(String owner, String timestamp) {
byte[] postAndKey = new byte[1024];
byte[] post = null;
byte[] encryptedKey = null;
User u = User.connect(owner);
Post.findAll();
//List<Post> posts = (Post.find("byOwner", owner).fetch());
System.out.println("Looking for post by " + owner + " at timestamp: " + timestamp);
//System.out.println("Looking through: " + posts.size() + " posts");
At Post.findAll() the framework throws a nasty error, telling me that there is a Timeout trying to lock table "POST". I suspect that this is because one thread is still in executePost() while another is trying to access the post in retrievePost(). Considering that the Post has been 'saved', however, shouldn't the lock have been released? Is this really the reason, and is there any way around the error?
Thanks.
Just for reference, if anyone else is having a similar issue: I fixed it by explicitly sleeping the calling thread using await(), which meant that it gave up all its locks, allowing the thread in retrievePost() acess to the table.
I currently have a piece of code in my Android application that picks up the devices IMEI and sends that IMEI as a parameter to a PHP script that is hosted on the Internet.
The PHP script then takes the IMEI parameter and checks a file to see if the IMEI exists in the file, if it does I want to be able to let my Android application know that the IMEI exists. So essentially I just want to be able to return True to my application.
Is this possible using PHP?
Here is my code so far:
Android/Java
//Test HTTP Get for PHP
public void executeHttpGet() throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://testsite.com/" +
"imei_script.php?imei=" + telManager.getDeviceId()
));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The above sends the IMEI as a parameter to the PHP script which picks it up successfully and runs a check against the file successfully, however I neeed to then be able to send a positive response back from the PHP script if the IMEI matches one in the file.
Here is the PHP:
<?php
// to return plain text
header("Content-Type: plain/text");
$imei = $_GET["imei"];
$file=fopen("imei.txt","r") or exit("Unable to open file!");
while(!feof($file))
{
if ($imei==chop(fgets($file)))
echo "True";
}
fclose($file);
?>
So instead of echo True I want to be able to let my application know that the IMEI was found, is this possible and if so what should I be using to achieve it?
this is good stuff! actually, you're nearly there. your php shouldn't change, your java should! you just need to check the result of the response inside your java code. redeclare your java method as
public String executeHttpGet() {
then, let this method return the variable page.
now you can create a helper method somewhere. if you put it in the same class as executeHttpGet, it will look like this:
public boolean imeiIsKnown(){
return executeHttpGet().equals("True");
}
now you can call this method to find out if your imei is known in your php backend.
I'm not sure is it good for you or not - but you can use headers. If the IMEI was found you can send header("Status: HTTP/1.1 200 OK") otherwise send header("Status: 404 Not Found").
And then you should check response status in your application.
your code is basically sound, all you need to do is tweak it up a bit. i mixed and matched the answers above, because i needed to accomplish exactly what you were trying to. i created a database, instead of checking txt files.
CREATE TABLE IF NOT EXISTS `user_device` (
`Id_User_Device` int(11) NOT NULL auto_increment,
`Nr_User_Device` varchar(60) collate utf8_bin NOT NULL,
`Ic_User_Device_Satus` int(11) NOT NULL default '1',
PRIMARY KEY (`Id_User_Device`),
KEY `Nr_User_Device` (`Nr_User_Device`,`Ic_User_Device_Satus`)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=20 ;
the java android code would be (dont forget to create the proper adjustements in the main.xml layout file, inserting 2 elements to a classical helloworld screen:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class ZdeltestEMEIActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(this);
String deviceUuid = deviceUuidFactory.getDeviceUuid().toString();
Log.d("tgpost",deviceUuid);
try {
String webPostAnswer = deviceIdCheck(deviceUuid);
if (webPostAnswer != null) {
TextView tv1 = (TextView) findViewById(R.id.textdisplay01);
TextView tv2 = (TextView) findViewById(R.id.textdisplay02);
tv1.setText(webPostAnswer);
tv2.setText(deviceUuid);
Log.d("tgpost", "okok "+webPostAnswer);
} else {
Log.d("tgpost", "nono empty");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("tgpost", "exc " + e.getMessage());
Log.i("tgpost", e.toString());
Log.e("tgpost", e.getStackTrace().toString());
e.printStackTrace();
}
}
public String deviceIdCheck(String deviceUuidIn) throws Exception {
boolean flagOK = false;
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
Log.v("tgpost", "okok");
//"imei_script.php?deviceId="; + telManager.getDeviceId()
request.setURI(new URI("http://www.you.net/" +
"deviceIdCheck.php?deviceId=" + deviceUuidIn
));
HttpResponse response = client.execute(request);
Log.d("tgpost", "php answered> "+response);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
Log.d("tgpost", "php answered HUMAN> "+page);
return page;
} catch (Exception e) {
return "problems with connection "+e.getMessage();
}
}
}
with an addtional class
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class DeviceUuidFactory {
protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id";
protected static UUID uuid;
public DeviceUuidFactory(Context context) {
if( uuid ==null ) {
synchronized (DeviceUuidFactory.class) {
if( uuid == null) {
final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
final String id = prefs.getString(PREFS_DEVICE_ID, null );
if (id != null) {
// Use the ids previously computed and stored in the prefs file
uuid = UUID.fromString(id);
} else {
final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
// Use the Android ID unless it's broken, in which case fallback on deviceId,
// unless it's not available, then fallback on a random number which we store
// to a prefs file
try {
if (!"9774d56d682e549c".equals(androidId)) {
uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
} else {
final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Write the value out to the prefs file
prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
}
}
}
}
}
/**
* Returns a unique UUID for the current android device. As with all UUIDs, this unique ID is "very highly likely"
* to be unique across all Android devices. Much more so than ANDROID_ID is.
*
* The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
* TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
* on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
* usable value.
*
* In some rare circumstances, this ID may change. In particular, if the device is factory reset a new device ID
* may be generated. In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
* to a newer, non-buggy version of Android, the device ID may change. Or, if a user uninstalls your app on
* a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
*
* Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
* change after a factory reset. Something to be aware of.
*
* Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
*
* #see http://code.google.com/p/android/issues/detail?id=10603
*
* #return a UUID that may be used to uniquely identify your device for most purposes.
*/
public UUID getDeviceUuid() {
return uuid;
}
}
on the php side:
<?php
// to return plain text
// header("Content-Type: plain/text");
include('/home/public_html/ConnStrDB.php');
$deviceId = $_GET["deviceId"];
$sql = "SELECT Nr_User_Device FROM user_device WHERE Nr_User_Device = '".$deviceId."'";
$result = mysql_query($sql);
if ($result) {
$row = mysql_fetch_array($result);
if ($row[0]) {$deviceIdFile = $row[0];} else {$deviceIdFile = "device not found";}
} else {
$deviceIdFile = "no check was made, empty set";
}
echo $_GET["deviceId"]." ".$deviceIdFile;
?>
and (so that you dont have to insert the numbers manually (just change the php fileName in the submit):
<?php
// to return plain text
// header("Content-Type: plain/text");
include('/home/public_html/ConnStrDB.php');
$deviceId = $_GET["deviceId"];
$sql = "SELECT Nr_User_Device, Ic_User_Device_Status FROM user_device WHERE Nr_User_Device = ".$deviceId;
$sql = "INSERT INTO user_device (Nr_User_Device) VALUES ('".$deviceId."')";
$result = mysql_query($sql);
if ($result) {
$deviceIdFile = "device inserted";
} else {
$deviceIdFile = "not inserted";
}
echo $_GET["deviceId"]." ".$deviceIdFile;
?>
if succesful, your mobile screen will display the imei 3 times (the one on the device, the one received in php and the one retrieved on the database).
ConnStrDB.php is a file that contains your complete connection to MySQL database.
if you reply with long text, the android application will receive it, as well as the verbose version of any php warning. if you dont need json, you can answer any xml thru a php echo. thanx for your question, very useful! and thanx for the EXCELLENT answers!