Cannot Send Email in AppEngine Tutorial - android

I am simply following the tutorial outlined in: https://cloud.google.com/solutions/mobile/firebase-app-engine-android-studio, section Add the backend module.
The Servlet code I have is:
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
static Logger Log = Logger.getLogger("com.example.username.myapplication.backend.MyServlet");
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Log.info("Got cron message, constructing email.");
//Create a new Firebase instance and subscribe on child events.
Firebase firebase = new Firebase("[firebase-DB]");
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Build the email message contents using every field from Firebase.
final StringBuilder newItemMessage = new StringBuilder();
newItemMessage.append("Hello main user");
//Now Send the email
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
//Make sure you substitute your project-id in the email From field
msg.setFrom(new InternetAddress("anything#firebasebackendserver.appspotmail.com",
"Todo Nagger"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress("myEmail#gmail.com", "Recipient"));
msg.setSubject("Good Morning!");
msg.setText(newItemMessage.toString());
Transport.send(msg);
} catch (MessagingException | UnsupportedEncodingException e) {
Log.warning(e.getMessage());
}
}
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
And the cron.xml file as:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/hello</url>
<description>Send me an email of outstanding items in the morning</description>
<schedule>every 1 minutes</schedule>
</cron>
</cronentries>
After completing an in Firebase, the AppEngine dashboard does register that a request has occurred, however, the email is never sent, all I see in the logs is the error:
Caused by: com.google.apphosting.api.ApiProxy$FeatureNotEnabledException: The Socket API will be enabled for this application once billing has been enabled in the admin console.
Even though I have already enabled billing for this app.
Is there some sort of grace period after billing is enabled before you can actually begin to use it...?
What is wrong with the code layout?

I suspect you're sending from a disallowed sender. Here's an excerpt from the docs:
For security purposes, the sender address of a message must be one of the following:
The Gmail or Google Apps Account of the user who is currently signed in
Any email address of the form anything#appname.appspotmail.com or anything#appalias.appspotmail.com
Any email address listed in the Cloud Platform Console under Email API Authorized Senders
If this is the case, you will see an error in the logs.

Related

How to access and retrieve Salesforce objects via Volley API calls in Android?

I'm trying to access and retrieve SFDC Objects via an Android Application. How would we be able to do so?
I'm told that we can make use of SFDC's REST APIs like below and make CRUD operations like below:
https://yourorg.com/services/data/v48.0/sobjects/custom-object
But I'm no sure how to go on with the authentication part. Help me out!
Below is the code I've written so far
package com.example.shoppingstore;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class SalesforceRESTAPI {
String accessToken = "my access token";
public void getCategories(final Context context){
String URL = "my URL";
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//the categories are returned
Log.e("Response REST", response.toString());
Toast.makeText(context, "Worked", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
//error occured while retriving the categories
Log.e("Response REST", error.toString());
Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Type", "oAuth2.0");
params.put("Authentication", accessToken);
params.put("Accept-Encoding", "gzip, deflate, br");
params.put("Connection", "keep-alive");
params.put("Accept", "*/*");
return params;
}
};
requestQueue.add(jsonObjectRequest);
}
}
Uh, this can be a massive topic. How do you plan to authenticate. Will you have 1 service account that connects to SF from all mobile devices? If you do - how are you going to store credentials? What if somebody hacks into the package and you need to mass change password?
Or will you let people login to SF using their own Salesforce username and password. Maybe not even display a form for them to type stuff in, you'd just show them SF login page and on success they're redirected back to your app. This is especially cool when they don't really have a SF password, the company has configured Single Sign On and they login to SF via their Google/Windows/Facebook/what-have-you account...
These things have been solved in the past. If you haven't done so already - read up about OAuth2 and what OAuth2 flows you can do with Salesforce.
https://trailhead.salesforce.com/content/learn/projects/build-a-connected-app-for-api-integration
https://trailhead.salesforce.com/en/content/learn/modules/connected-app-basics/connected-app-basics-api-integration
https://help.salesforce.com/articleView?id=remoteaccess_oauth_flows.htm&type=5
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_oauth.htm
I know, it's just a bunch of links but try to read through if not execute at least the trailheads. Few hours of reading and planning can save you weeks of coding yourself into a corner.
I mean I've never written an app in my life but chances are Android SDK & articles here already have everything you need: https://developer.salesforce.com/developer-centers/mobile/. Looks like SDK even comes with sample apps: https://developer.salesforce.com/docs/atlas.en-us.mobile_sdk.meta/mobile_sdk/android_sample_app.htm

using JDBC with android studio, unable to find suitable driver

I am new to this JDBC driver. I am looking for ways to save user data from my android app to the google cloud mySQL. I happen to come across that JDBC might get this done.
However, I encounter this error No suitable driver found for jdbc:mysql://google/waveUserData?cloudSqlInstance=wavdata&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false
I have already downloaded the JDBC driver and put inside /library/java/extensions
Please help me with this, or please recommend me a method to efficiently user data from app to Google cloud mysql.
This is the code I am referring to: https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory/blob/master/examples/compute-engine/src/main/java/com/google/cloud/sql/mysql/example/ListTables.java
package com.google.cloud.sql.mysql.example;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* A sample app that connects to a Cloud SQL instance and lists all available tables in a database.
*/
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
// TODO: fill this in
// The instance connection name can be obtained from the instance overview page in Cloud Console
// or by running "gcloud sql instances describe <instance> | grep connectionName".
String instanceConnectionName = "<insert_connection_name>";
// TODO: fill this in
// The database from which to list tables.
String databaseName = "mysql";
String username = "root";
// TODO: fill this in
// This is the password that was set via the Cloud Console or empty if never set
// (not recommended).
String password = "<insert_password>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
//[START doc-example]
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s"
+ "&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false",
databaseName,
instanceConnectionName);
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
//[END doc-example]
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SHOW TABLES");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}
}
}

How to like/unlike and subscribe a YouTube video from a android app

I'm trying to create a YouTube video android app.Currently there no issue to play video and fetch a playlist because there are sample for this.But I'm unable to find any good reference to like/unlike and subscribe events in YouTube.
So How to like/unlike and subscribe a YouTube video from a android app ?
Any help will be highly appreciated.
I don't think you can do it in your own application.
You will have to redirect the user of your application to the channel he wants to subscribe to through the YouTube App.
You can use this method from the YouTube API : createChannelIntent (link). From there, your user will be able to subscribe to the channel, as it will be opened into the YouTube App.
Make sure that the YouTube App is installed before (link) ! :)
Hope it helps !
You need to use the YouTube Data apis. Here you can read how to like/dislike a video.
maybe you can use this code:
// Sample Java code for user authorization
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.youtube.YouTubeScopes;
import com.google.api.services.youtube.model.*;
import com.google.api.services.youtube.YouTube;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
public class ApiExample {
/** Application name. */
private static final String APPLICATION_NAME = "API Sample";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".credentials/java-youtube-api-tests");
/** Global instance of the {#link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/drive-java-quickstart
*/
private static final Collection<String> SCOPES = Arrays.asList("YouTubeScopes.https://www.googleapis.com/auth/youtube.force-ssl YouTubeScopes.https://www.googleapis.com/auth/youtubepartner");
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
* #return an authorized Credential object.
* #throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in = ApiExample.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader( in ));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized API client service, such as a YouTube
* Data API client service.
* #return an authorized API client service
* #throws IOException
*/
public static YouTube getYouTubeService() throws IOException {
Credential credential = authorize();
return new YouTube.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException {
YouTube youtube = getYouTubeService();
try {
HashMap<String, String> parameters = new HashMap<>();
parameters.put("id", "E6UTz_Doic8");
parameters.put("rating", "like");
YouTube.Videos.Rate videosRateRequest = youtube.videos().rate(parameters.get("id").toString(), parameters.get("rating").toString());
videosRateRequest.execute();
} catch (GoogleJsonResponseException e) {
e.printStackTrace();
System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
can be more complete later,
This

SafetyNet attestation fails with internal error

I want to use the SafetyNet Attestation API (mind that this documentation seems to be outdated since the methods it uses are deprecated). Using the latest version of Play Services (11.0.1) I came up with the following code:
SecureRandom secureRandom = new SecureRandom();
byte[] nonce = new byte[16];
secureRandom.nextBytes(nonce); // just some random bytes for testing
SafetyNet.getClient(this)
.attest(nonce, API_KEY)
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
SafetyNetApi.AttestationResponse result = task.getResult();
String jws = result.getJwsResult();
Log.d(TAG, "JWS: " + jws);
} else {
Exception e = task.getException();
if (e instanceof ApiException) {
Log.e(TAG, "Attestation failure: " + ((ApiException) e).getStatusMessage() + ", code: " + ((ApiException) e).getStatusCode(), e);
} else {
Log.e(TAG, "Attestation failure: " + e, e);
}
}
});
where API_KEY is the API key from the Google Developer Console. This code is called in an Activity's onCreate(...). Whatever I tried, it results in failure and the e is an instance of ApiException, but it does not provide any useful information about what went wrong since the status message is null and the status code is 8, which - according to the documentation - is an "internal error". I tried to call this with a 5 second delay but no success. The test device has API 24 and Google Play services 11.0.55.
Anyone has any idea what goes wrong and what's the solution for this?
Edit: the old SafetyNet.SafetyNetApi.attest(googleApiClient, nonce) way seems to work fine but it's deprecated so I don't want to use it.
Based from this thread, if you get error code 8 (INTERNAL_ERROR), please double check your app registration in dev console. Note that every registered Android client is uniquely identified by the (package name, Android Signing Certificate SHA-1) pair. If you have multiple package names / signing certificate for your debug and production environments, make sure to register every pair of them.
To verify:
Open the Credentials page and select your project
Make sure every pair has an Android typed OAuth 2.0 client IDs. To create a new OAuth 2.0 client ID for your Android client, select New Credentials->OAuth2 Client ID from the dropdown, select Android and input your Package name / Signing-certificate fingerprint there.
If it doesn't work, I recommend you to contact the Google Play team for help. You can reach them from this link here: https://support.google.com/googleplay#topic=3364260&contact=1.
Ensure that you are using correct WEB API KEY in your following code:
SafetyNet.getClient(this)
.attest(nonce, WEB_API_KEY)......
See following image to find WEB API KEY:
FCM Console
// Build.gradle
implementation 'com.google.firebase:firebase-core:17.2.1'
implementation 'com.google.firebase:firebase-messaging:20.1.0'
implementation 'com.android.support:support-annotations:28.0.0'
implementation 'com.google.android.gms:play-services-safetynet:17.0.0'
implementation 'com.google.android.gms:play-services-tasks:17.0.0'
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.gms.safetynet.SafetyNetClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.safetynet.SafetyNet;
import com.google.android.gms.safetynet.SafetyNetApi;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.safetynet.SafetyNet;
import com.google.android.gms.safetynet.SafetyNetApi;
import com.google.android.gms.safetynet.SafetyNetClient;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.safetynet.SafetyNetApi.AttestationResponse;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Random;
#Override
public void onConnected(Bundle bundle) {
Log.d("My Project Name:", "Google play services connected");
runSafetyNetTest(mContext);
}
private byte[] getRequestNonce(String data) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[24];
mRandom.nextBytes(bytes);
try {
byteStream.write(bytes);
byteStream.write(data.getBytes());
} catch (IOException e) {
return null;
}
public void runSafetyNetTest(Context context) {
String nonceData = "734K78J56KJ745JH78LKJ9CSOC3477tj35f345j7" + System.currentTimeMillis();
byte[] nonce = getRequestNonce(nonceData);
SafetyNetClient client = SafetyNet.getClient(context);
Task<SafetyNetApi.AttestationResponse> task = client.attest(nonce, this.googleDeviceVerificationApiKey);
task.addOnSuccessListener( mSuccessListener).addOnFailureListener(mFailureListener);
}
private OnSuccessListener<SafetyNetApi.AttestationResponse> mSuccessListener =
new OnSuccessListener<SafetyNetApi.AttestationResponse>() {
#Override
public void onSuccess(SafetyNetApi.AttestationResponse attestationResponse) {
mResult = attestationResponse.getJwsResult();
// writeLog( "Success! SafetyNet result:\n" + mResult + "\n");
final String jwsResult = mResult;
final SafetyNetResponse response = parseJsonWebSignature(jwsResult);
lastResponse = response;
//only need to validate the response if it says we pass
if (!response.isCtsProfileMatch() || !response.isBasicIntegrity()) {
// This is Result........
callback.success(response.isCtsProfileMatch(), response.isBasicIntegrity());
return;
} else {
//validate payload of the response
if(true/*validateSafetyNetResponsePayload(response)*/) {
if (googleDeviceVerificationApiKey != "")
{
//if the api key is set, run the AndroidDeviceVerifier
AndroidDeviceVerifier androidDeviceVerifier = new AndroidDeviceVerifier(googleDeviceVerificationApiKey, jwsResult);
androidDeviceVerifier.verify(new AndroidDeviceVerifier.AndroidDeviceVerifierCallback() {
#Override
public void error(String errorMsg) {
callback.error(RESPONSE_ERROR_VALIDATING_SIGNATURE, "Response signature validation error: " + errorMsg);
}
#Override
public void success(boolean isValidSignature) {
if (isValidSignature) {
callback.success(response.isCtsProfileMatch(), response.isBasicIntegrity());
} else {
callback.error(RESPONSE_FAILED_SIGNATURE_VALIDATION, "Response signature invalid");
}
}
});
} else {
Log.w(TAG, "No google Device Verification ApiKey defined");
callback.error(RESPONSE_FAILED_SIGNATURE_VALIDATION_NO_API_KEY, "No Google Device Verification ApiKey defined. Marking as failed. SafetyNet CtsProfileMatch: " + response.isCtsProfileMatch());
}
} else {
callback.error(RESPONSE_VALIDATION_FAILED, "Response payload validation failed");
}
}
}
};
private OnFailureListener mFailureListener = new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// An error occurred while communicating with the service.
mResult = null;
if (e instanceof ApiException) {
// An error with the Google Play Services API contains some additional details.
ApiException apiException = (ApiException) e;
writeLog( "Error: " +
CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()) + ": " +
apiException.getStatusMessage());
} else {
// A different, unknown type of error occurred.
writeLog( "ERROR! " + e.getMessage());
}
}
};

How to make a connection with my ontology?

I created an ontology with Protégé. Then I created an Android interface which contains two edit texts and a button. The main function of my code is to make a connection between my application and the ontology and store these data into it. I use a triple store for storage.
But it didn't work correctly. I'm using Sesame as server but I don't know how to get the correct URL of the "update" service. I might have made other errors but here is my activity's code:
package com.example.ontologie1;
import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import java.io.IOException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button buttonconnexion;
private EditText editpseudo;
private EditText editpassword;
public String ps;
public String pa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editpseudo = (EditText) findViewById(R.id.welcomeedittextlogin);
editpassword = (EditText) findViewById(R.id.welcomeedittextpassword);
buttonconnexion = (Button) findViewById(R.id.welcomebuttonconnexion);
buttonconnexion.setOnClickListener(click1);
}
protected OnClickListener click1 = new OnClickListener() {
public void onClick(View arg0) {
ps= editpseudo.getText().toString();
pa= editpassword.getText().toString();
try {
connexion(ps , pa);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
protected void connexion(String pseudo,String password) throws IOException {
String requete = "<http://www.w3.org/2002/07/owl#> .\n"
+ "INSERT DATA {\n"
+ " <http://www.owl-ontologies.com/Ontology_profile.owl#USER> a onto:USER;\n"
+ " onto:Login " + pseudo + ";\n"
+ " onto:Password " + password + ";\n"
+ "}";
PostMethod post = new PostMethod("<http://www.openrdf.org/config/repository#>");
NameValuePair[] paramRequete = {
new NameValuePair("query", requete),
};
post.setRequestBody(paramRequete);
InputStream in = post.getResponseBodyAsStream();
Toast t = null ;
t.setText(in.toString());
t=new Toast(null);
}
}
I don't have experience with Android programming, but there are some issues that suggest you need to rethink your goals.
An ontology is not a database. You don't store data in an ontology, and you don't need an ontology to store data in a triplestore.
To store data in a triplestore (using SPARQL), your triplestore needs a SPARQL endpoint. That endpoint has a URI that you send your POST or GET request to. If you installed Sesame on your local machine, that URI may look like http://localhost:8080/sparql. If you want to insert data, the triplestore needs to allow that.
You also need a valid SPARQL query, which your requete is not. The first line,
<http://www.w3.org/2002/07/owl#> .
is not complete. Usually there are PREFIXes on the first lines of a SPARQL query, but they don't end with a .. For example:
PREFIX owl: <http://www.w3.org/2002/07/owl#>
To use the prefix onto: as you do, you need to define it in the same way. For a complete SPARQL tutorial, see this.
Also, the lines
Toast t = null ;
t.setText(in.toString());
t=new Toast(null);
will generate a NullPointerException, as you call a method on t that is null.

Categories

Resources