Session null jsf getExternalContext() - jsf

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);
}
}

Related

Unauthorized exception with SPSecurity.RunWithElevatedPrivileges?

I'm checking, if a given user is part of a group by this code below. I'm getting
unauthorized exception
(0x80070005)
and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.
So, try and modify the below code as per your requirement :
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using(SPSite site = new SPSite(web.Site.ID))
{
using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
{
if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = elevatedWeb.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
}
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}

Unable to use Web API OData v3 feed in Excel

I have a self-hosted Web API OData v3 service:
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
app.UseWebApi(config);
}
}
I also have the following Controller, which exposes a full CRUD:
public class ProductsController : ODataController
{
ApplicationDbContext db = new ApplicationDbContext();
private bool ProductExists(int key)
{
return db.Products.Any(p => p.Id == key);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery]
public IQueryable<Product> Get()
{
return db.Products;
}
[EnableQuery]
public SingleResult<Product> Get([FromODataUri] int key)
{
IQueryable<Product> result = db.Products.Where(p => p.Id == key);
return SingleResult.Create(result);
}
public async Task<IHttpActionResult> Post(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return Created(product);
}
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var entity = await db.Products.FindAsync(key);
if (entity == null)
{
return NotFound();
}
product.Patch(entity);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(entity);
}
public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != update.Id)
{
return BadRequest();
}
db.Entry(update).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(update);
}
public async Task<IHttpActionResult> Delete([FromODataUri] int key)
{
var product = await db.Products.FindAsync(key);
if (product == null)
{
return NotFound();
}
db.Products.Remove(product);
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
}
I am able to access this feed from a browser without any issues.
However, when I try to get Excel 2013 to use this data feed (using this url: http://localhost:8080/Products), I get this error:
"We can't use the data from this feed. Make sure the external data feed server is available and your connection information is correct"
What can I do to make Excel 2013 to work with this data feed?

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");
}
}

foursquare adding a tip exception

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();
}
}

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