foursquare adding a tip exception - foursquare

I am working on foursquare API v2 in Android.
In my application User can check-in and add a tip.
check- in method is working good but add a tip method got error.
private void methodTipAdd(String venueId, String tip, boolean auth) {
StringBuilder urlBuilder = new StringBuilder("https://api.foursquare.com/v2/");
urlBuilder.append("tips/add");
urlBuilder.append('?');
try{
urlBuilder.append("venueId").append('=');
urlBuilder.append(URLEncoder.encode(venueId, "UTF-8")).append('&');
}catch(Exception e) {
e.printStackTrace();
}
try{
urlBuilder.append("text").append('=');
urlBuilder.append(URLEncoder.encode(tip, "UTF-8")).append('&');
}catch(Exception e) {
e.printStackTrace();
}
if (auth) {
urlBuilder.append("oauth_token=");
urlBuilder.append(getAccessToken());
} else {
urlBuilder.append("client_id=");
urlBuilder.append(CLIENT_ID);
urlBuilder.append("&client_secret=");
urlBuilder.append(CLIENT_SECRET);
}
urlBuilder.append("&v=" + getVersion());
String url = urlBuilder.toString();
String result = null;
try {
URL aUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) aUrl.openConnection();
try {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
int code = connection.getResponseCode();
if (code == 200) {
InputStream inputStream = connection.getInputStream();
result = convertStreamToString(inputStream);
android.util.Log.e(tag, "result: " + result);
// handle tip
} else {
android.util.Log.e(tag, "HttpURLConnection response code: " + code);
}
} finally {
connection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
request url : https://api.foursquare.com/v2/tips/add?venueId=[venue id]&text=[utf-8 encoded text]&oauth_token=[my_oauth_token]&v=20120730
ex) https://api.foursquare.com/v2/tips/add?venueId=XXX123YYY&text=Good&oauth_token=XXX123YYY&v=20120730
http response code: 400
I want to know why i got the HTTP_BAD_REQUEST response code.

when doing a POST the parameters should not be part of the URL (specify them as parameters to the POST).

I solved the problem.
private void methodTipAdd3(String venueId, String tip) {
String url = "https://api.foursquare.com/v2/tips/add";
StringBuilder sb = new StringBuilder();
sb.append("oauth_token=");
sb.append(getAccessToken()).append('&');
try{
sb.append("venueId").append('=');
sb.append(URLEncoder.encode(venueId, "UTF-8")).append('&');
}catch(Exception e) {
e.printStackTrace();
}
try{
sb.append("text").append('=');
sb.append(URLEncoder.encode(tip, "UTF-8")).append('&');
}catch(Exception e) {
e.printStackTrace();
}
sb.append("v=" + getVersion());
String params = sb.toString();
String result = null;
int httpcode = 200;
try {
URL aUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) aUrl.openConnection();
try {
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
byte buf[] = params.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(buf.length));
connection.setDoOutput(true);
OutputStream outputstream = connection.getOutputStream();
outputstream.write(buf);
outputstream.flush();
outputstream.close();
httpcode = connection.getResponseCode();
if (httpcode == 200) {
InputStream inputStream = connection.getInputStream();
result = convertStreamToString(inputStream);
// handle tip
android.util.Log.e(tag, "result: " + result);
} else {
android.util.Log.e(tag, "http response code: " + httpcode);
}
} finally {
connection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Error converting Blob data from MySql DB to google cloud storage

I am trying to do the data migration. We used to store image as mediumblob data in MySQL DB, I want to read this image(blob data) and upload to the google cloud storage bucket. The upload works but the image are corrupted in cloud storage.
code to upload file
const id: string = uuidv4();
const buffer: Buffer = image.ImageBin; //image.ImageBin contains blob data from DB
let file = {
originalname: imageId + ".JPG",
buffer,
};
return await upload(file, id);
upload function
public async upload(file, imageId): Promise<string> {
try {
const bucket = this.storage.bucket(process.env.IMAGE_BUCKET);
return new Promise((resolve, reject) => {
let { originalname, buffer } = file;
originalname = imageId + ":" + originalname;
originalname = originalname.replace(/ /g, "_");
const blob = bucket.file(originalname);
const blobStream = blob.createWriteStream({
resumable: false,
});
blobStream
.on("finish", () => {
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`
);
resolve(originalname);
})
.on("error", (error) => {
reject(error);
})
.end(buffer);
});
} catch (error) {
this.logger.log(`error uploading file error:${error}`);
}
}
earlier Java code that used to get image from mysql and this code is working fine.
public Response getImage(Integer imageid, HttpServletResponse resp)
{
Response response = null;
UserPhotoUpload UserPhotoUpload = new UserPhotoUpload();
Blob imageBlob;
OutputStream out = null;
try
{
// get the image to upload
UserPhotoUpload = userPhotoUploadDAO.getImage(imageid);
if (UserPhotoUpload != null)
{
imageBlob = UserPhotoUpload.getImageBin();
if (imageBlob != null)
{
// get the output stream
out = resp.getOutputStream();
// add header info
resp.setHeader("Content-Disposition", "inline;filename=test.JPG");
resp.setContentType("Content-type: image/JPG");
// copy the image to the output stream
IOUtils.copy(imageBlob.getBinaryStream(), out);
out.flush();
out.close();
}
else
throw new ScottsAppException(CommonConstants.STATUS_MSG_ERROR_IMAGE_NOT_EXISTS);
}
else
throw new ScottsAppException(CommonConstants.STATUS_MSG_ERROR_IMAGE_NOT_EXISTS);
}
catch (ScottsAppException e)
{
response = new Response();
CommonUtil.responseErrorUpdate(response, e.getMessage(), CommonConstants.STATUS_CODE_APPLICATION_FAILURE);
}
catch (IOException e)
{
response = new Response();
log.error("Error", e);
CommonUtil.responseErrorUpdate(response, CommonConstants.STATUS_MSG_MISC_APPLICATION_FAILURE, CommonConstants.STATUS_CODE_APPLICATION_FAILURE);
}
catch (SQLException e)
{
response = new Response();
log.error("Error", e);
CommonUtil.responseErrorUpdate(response, CommonConstants.STATUS_MSG_MISC_APPLICATION_FAILURE, CommonConstants.STATUS_CODE_APPLICATION_FAILURE);
}
catch (Exception e)
{
response = new Response();
log.error("Error", e);
CommonUtil.responseErrorUpdate(response, CommonConstants.STATUS_MSG_MISC_APPLICATION_FAILURE, CommonConstants.STATUS_CODE_APPLICATION_FAILURE);
}
finally
{
try
{
out.flush();
}
catch (Exception e)
{
}
try
{
out.close();
}
catch (Exception e)
{
}
}
// return
return response;
}
if someone wan't to look at blob data https://justpaste.it/862mk
For someone coming here, The issue was in copy-paste of blob data from Database.
The above functions are working fine.

Session null jsf getExternalContext()

I generate a session in my code but then when using it in another file the session returns null, thx all!
this linux server primefaces,payara 5
public Usuarios loginUsuario(String usuario, String password) {
Usuarios user = null;
try {
UsuariosDAO us = new UsuariosDAO();
user = us.loginUsuario(usuario, password);
if (user != null) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuario", user); // here set user ok! not null
FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
} else {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion!", "User o Password Inconrrectos"));
}
} catch (Exception e) {
System.out.println(e);
}
return user;
}
public void probarSession() {
try {
FacesContext esta = FacesContext.getCurrentInstance();
System.err.println(esta.getExternalContext().getSessionMap().get("usuario")+"this is null!!!");
Usuarios us = (Usuarios) esta.getExternalContext().getSessionMap().get("usuario");
if (us == null) {
esta.getExternalContext().redirect("login.xhtml");
}
} catch (IOException e) {
System.err.println(e);
}
}

How to pass token from Nodejs to backend Java code

I am new to Nodejs .
I am trying to pass JWT token from Nodejs to java service class.
I am getting JWT token in a variable in Nodejs code that I need to pass to spring mvc application service class.
can anyone please help me on this?
And having confusion with how to integrate Nodejs with java if i pass variable from Nodejs to java?
Node code is,
module.exports = {
verifyReq: function (req, res, next) {
if (req.headers.authorization) {
res.setHeader('Content-Type', 'text/html');
res.write('<div id="_mscontent"><script src="URL"></script>');
var notAuthorized = false;
var authorization = req.headers.authorization;
console.log("authorization: " + authorization);
if (authorization) {
req.isAuthorized = true;
}
try {
var decodedJWT = JWT.decode(authorization.split(' ')[1], "", true);
} catch (e) {
notAuthorized = true;
}
else {
req.isAuthorized = false;
res.status(401);
res.end('Not Authorized!');
return;
}
return req.isAuthorized === true;
}
};
Java Code,
public class GetCarAssetValuesService {
private static String output;
private static String token;
private static Asset[] myObjects;
public void getAssets(String tokenToPass)
throws JsonParseException, JsonMappingException, IOException, JSONException {
System.out.println("In service");
HttpsURLConnection myURLConnection = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuilder strBuilder = new StringBuilder();
JSONObject jsonObj = new JSONObject(tokenToPass);
System.out.println("success_token= " + jsonObj);
token = jsonObj.getString("access_token");
System.out.println("Print token= " + token);
try {
URL url = new URL(
"Third Party URL");
myURLConnection = (HttpsURLConnection) url.openConnection();
String bearerAuth = "Bearer " + token;
myURLConnection.setRequestProperty("Authorization", bearerAuth);
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setDoOutput(true);
inputStream = myURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
if (myURLConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + myURLConnection.getResponseCode());
}
System.out.println("Here the control cars...");
System.out.println("Output from Server .... \n");
while ((output = bufferedReader.readLine()) != null) {
strBuilder.append(output);
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String mindsphereResponse = strBuilder.toString();
System.out.println("Responsesssssss" + mindsphereResponse);
ObjectMapper mapper = new ObjectMapper();
myObjects = mapper.readValue(mindsphereResponse, Asset[].class);
}
Here instead of passing "tokenToPass" i want to get this token from node js i.e.decodeJWT. This "tokenToPass" i am getting from other java service now i want it from Nodejs.
Thanks in Advance..!!!
You can set the JWT token in the HTTP Request header ( nodejs ) and API endpoint ( java ) can be get it from there.
HelloController.java
#Controller
public class HomeController {
#Autowire
private HomeService homeService;
#GetMapping("/hello")
public String home(HttpServletRequest request, Model model) {
helloService.invoke(request.getHeader('JWT_TOKEN_KEY'));
}
}
HelloService.java
#Service
public class HelloService {
public void invoke(jwtToken) {
// Use this jwttoken
}
}
NodeJS.js
var options = {
host: 'your_java_api_endpoint',
port: 80,
path: '/hello',
headers:{
'JWT_TOKEN_KEY':'json web token here'
}
};
http.get(options, function(res) {
res.on("data", function(responseData) {
console.log("data: " + responseData);
});
}).on('error', function(e) {
console.log("http error : " + e);
});

How to Set User login Windows Phone 8 using sqlite database?

Hi i am using windows phone 8 app. i want to set existing user login, i can add user registration but i can't do user login my code is give below.
public partial class LoginPage : PhoneApplicationPage
{
public LoginPage()
{
InitializeComponent();
}
public static class dal
{
public static SQLiteAsyncConnection connection;
public static bool isDatabaseExisting;
public static async void ConnectToDB()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Bestin.sqlite");
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
try
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Bestin.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
}
if (isDatabaseExisting)
{
connection = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Bestin.sqlite"), true);
}
}
}
private void Click_Login(object sender, RoutedEventArgs e)
{
dal.ConnectToDB();
var query = dal.connection.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if (query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
}
I am using your code.I got error The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
ok so do this ....
public static class dal
{
public static SQLiteAsyncConnection connection;
public static bool isDatabaseExisting;
public static async void ConnectToDB()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Bestin.sqlite");
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
try
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Bestin.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
}
if (isDatabaseExisting)
{
connection = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Bestin.sqlite"), true);
}
}
}
make a class like above code for your database connection and call this at your application startup like this dal.ConnectToDB();
then in your loginpage do like this...
private void Click_Login(object sender, RoutedEventArgs e)
{
var query = dal.connection.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if(query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
you can try this ..
private void Click_Login(object sender, RoutedEventArgs e)
{
dbConn = new SQLiteConnection(DB_PATH);
var query = dbconn.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if(query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
Hi i got solution in my question..,
using (var dbConn = new SQLiteConnection(DB_PATH))
{
var existing = dbConn.Query<Userlist>("select * from Userlist Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Text + "\'").FirstOrDefault();
if (existing != null)
{
NavigationService.Navigate(new Uri("/Input.xaml?selectedItem=", UriKind.Relative));
}
else
{
MessageBox.Show("invalid login");
}
}

Database in J2ME

I am new in J2ME.
In my Application, I want to add the Multiple Records in the Record Store and also want to access it.
How can I add the multiple Records in the Record Store and how can I access it?
Here is my library code for RMS, just study it, it is very easy to implement, all the methods like insert,updated, delete is there.
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotOpenException;
import com.project.gui.components.CustomAlert;
import com.project.gui.midlet.MyMidlet;
public class RMSStore
{
private RecordStore rs = null;
public void openRecordStore(String str)
{
try
{
if(rs == null)
{
rs = RecordStore.openRecordStore(str, true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void closeRecordStore()
{
try
{
if(rs!=null)
{
rs.closeRecordStore();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void deleteRecordStore(String storenName)
{
try
{
RecordStore.deleteRecordStore(storenName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void deleteRMS(String storenName)
{
int count = 0;
try
{
RecordStore newRS = RecordStore.openRecordStore(storenName, true);
count = newRS.getNumRecords();
newRS.closeRecordStore();
}
catch ( Exception e )
{
System.out.println ( "Error while Opening " + e.toString() );
}
if ( count > 0 )
{
try
{
RecordStore.deleteRecordStore(storenName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static String[] listAllRecordStore ()
{
return RecordStore.listRecordStores();
}
public boolean SearchRecord(String Rec)
{
String [] data = getRecordData();
for ( int i = 0 ; i < data.length ; i++ )
{
if ( Rec.toString().trim().equals(data[i].toString().trim()) )
{
data = null; // System.gc();
return true;
}
}
data = null; // System.gc();
return false;
}
public boolean SearchRecord(String Rec, int pos )
{
String [] data = getRecordData();
Rec = Rec.substring(0,pos);
for ( int i = 0 ; i < data.length ; i++ )
{
data[i] = data[i].substring(0, pos );
if ( Rec.toString().trim().equals(data[i].toString().trim()) )
{
data = null; // System.gc();
return true;
}
}
data = null; // System.gc();
return false;
}
public int getCurrentRecordID ( RMSStore rmsTable, String Rec )
{
RecordEnumeration re = null;
try
{
re = rmsTable.getRecordEnumData();
while ( re.hasNextElement() )
{
int id = re.nextRecordId();
String record = rmsTable.getRecordFromId(id);
if ( record.indexOf(Rec) != -1 )
{
return id;
}
}
}
catch ( Exception e ) { System.out.println ( "getCurrentRecordID Error:" + e.toString() ); }
return -1;
}
public int writeRecord(String str)
{
int id = 0;
try
{
id = rs.addRecord(str.getBytes(), 0, str.getBytes().length);
}
catch (RecordStoreFullException e)
{
CustomAlert memoryFullAlert = new CustomAlert("");
memoryFullAlert.setString("Memory Full");
MyMidlet.getDisplay().setCurrent(memoryFullAlert);
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public int writeByteRecord(byte[] data)
{
int id = -1;
try
{
id = rs.addRecord(data, 0, data.length);
}
catch (RecordStoreFullException e)
{
e.printStackTrace();
CustomAlert memoryFullAlert = new CustomAlert("");
memoryFullAlert.setString("Memory Full");
MyMidlet.getDisplay().setCurrent(memoryFullAlert);
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public int getRecordCount()
{
try
{
return rs.getNumRecords();
}
catch (Exception e)
{
e.printStackTrace();
}
return 0;
}
public byte[] getRecordDataFromId(int id)
{
byte[] data = null;
try
{
data = rs.getRecord(id);
}
catch (Exception e)
{
e.printStackTrace();
}
return data;
}
public String getRecordFromId(int id)
{
return new String(getRecordDataFromId(id));
}
public byte[] getRecordByteFromId(int id)
{
return getRecordDataFromId(id);
}
public void deleteRecord(int id)
{
try
{
rs.deleteRecord(id);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public boolean checkRecordExists(String compare)
{
for(int i = 0; i < getRecordCount(); i++)
{
if(compare.equals(getRecordFromId(i + 1)))
{
return true;
}
}
return false;
}
public int getMaxRMSSize()
{
int size = 0;
try
{
size = rs.getSizeAvailable() + rs.getSize();
}
catch (RecordStoreNotOpenException e)
{
e.printStackTrace();
}
return size;
}
public void setRecordById(String str, int id)
{
try
{
rs.setRecord(id, str.getBytes(), 0, str.getBytes().length);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public int getNextRecordId()
{
int id = 0;
try
{
id = rs.getNextRecordID();
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public RecordEnumeration getRecordEnumData ()
{
try
{
return rs.enumerateRecords(null, null, false);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public String [] getRecordData()
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = rs.enumerateRecords(null, null, false);
str = new String[rs.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
RMS is a record based data storage mechanism, so you can store multiple records very easily, see following blog to see how RMS works.
http://www.ibm.com/developerworks/library/wi-rms/

Resources