I am trying to develop a simple application for android using azure mobile services and database, I have used the following code snippets but can't seem to insert any data into my azure table.
The following is the code I used to add the data:
public void createTable(String name, String userBirthday, String email)
{
userInformationTable = mClient.getTable(UserInformation.class);
item = new UserInformation();
item.mId = "1";
item.mEmail = email;
item.mUserBirthday = userBirthday;
item.mName = name;
mClient.getTable(UserInformation.class).insert(item, new TableOperationCallback<UserInformation>()
{
public void onCompleted(UserInformation entity, Exception exception, ServiceFilterResponse response)
{
if (exception == null) {
// Insert succeeded
Log.e("Succeed", "Insert Succeeded");
} else {
// Insert failed
Log.e("Nope", "Insert Failed");
}
}
});
}
The UserInformation Class is as below:
public class UserInformation {
#com.google.gson.annotations.SerializedName("id")
public String mId;
#com.google.gson.annotations.SerializedName("name")
public String mName;
#com.google.gson.annotations.SerializedName("email")
public String mEmail;
#com.google.gson.annotations.SerializedName("user_birthday")
public String mUserBirthday;
public UserInformation(){
}
public UserInformation(String Id, String name, String email, String userBirthday)
{
}
}
There could be many different error roots for that.
Improve your log using this code, this will give you further information about the error nature.
public void createTable(String name, String userBirthday, String email)
{
userInformationTable = mClient.getTable(UserInformation.class);
if(userInformationTable == null)
{
// Insert succeeded
Log.e("Table problem", "There's no table");
}
else
{
item = new UserInformation();
item.mId = "1";
item.mEmail = email;
item.mUserBirthday = userBirthday;
item.mName = name;
userInformationTable.insert(item, new TableOperationCallback<UserInformation>()
{
public void onCompleted(UserInformation entity, Exception exception, ServiceFilterResponse response)
{
if (exception == null) {
// Insert succeeded
Log.e("Succeed", "Insert Succeeded");
} else {
// Insert failed
Log.e("Error Message", exception.getMessage());
Log.e("Error Full", exception.toString());
}
}
});
}
}}
Most probably a connection issue or less probably there aren't tables with that name.
Related
I'am creating a restapi , i am using java spring and i'am getting the following error.
Error:
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
My daoImpl class
#Override
public String getLoginDetails(VendorLogin vendorlogin) {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ?
and password=?";
String name =null;
try{
name = (String) jdbcTemplate.queryForObject(getVendorData,new Object[]{
vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()}, String.class);
}catch(Exception e){
e.printStackTrace();
}
return name;
}
my controller
#RequestMapping(value = Constants.REQ_MAP_LOGIN,
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public String vendorloginMethodPost(#RequestBody VendorLogin vendoridlogin) {
String message = Constants.EMPTY_STRING;
String id = dao.getLoginDetails(vendoridlogin);
String password = dao.getLoginDetails(vendoridlogin);
if (id == null && password==null) {
message = "login FAIL";
}else{
message =" login Successfully";
}
return message;
}
SOLUTION
#Override
public String getLoginDetails(VendorLogin vendorlogin) {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ? and password=?";
try {
name = (String) jdbcTemplate.queryForObject(
getVendorData,
new Object[]{vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()},
new RowMapper<YourVendorObject>() {
public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException {
// we suppose that your vendor_ID is String in DB
String vendor_ID = rs.getString("vendor_ID");
// if you wanna return the whole object use setters and getters
// from rs.getInt ... rs.getString ...
return vendor_ID;
}
});
return name;
} catch (EmptyResultDataAccessException e) {
return null;
}
}
public class EmptyResultDataAccessException extends IncorrectResultSizeDataAccessException
Data access exception thrown when a result was expected to have at least one row (or element) but zero rows (or elements) were actually returned.
The problem is, Spring throws an EmptyResultDataAccessException, instead of returning a null when record not found :
JdbcTemplate .java
package org.springframework.jdbc.core;
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
//...
public <T> T queryForObject(String sql, Object[] args,
RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
return DataAccessUtils.requiredSingleResult(results);
}
DataAccessUtils.java
package org.springframework.dao.support;
public abstract class DataAccessUtils {
//...
public static <T> T requiredSingleResult(Collection<T> results)
throws IncorrectResultSizeDataAccessException {
int size = (results != null ? results.size() : 0);
if (size == 0) {
throw new EmptyResultDataAccessException(1);
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, size);
}
return results.iterator().next();
}
check it here : source
try {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ? and password=?";
String name =null;
name = (String) jdbcTemplate.queryForObject(getVendorData,new Object[]{vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()}, String.class);
} catch (EmptyResultDataAccessException e) {
return null;
}
This question already has answers here:
readobject method throws ClassNotFoundException
(2 answers)
Closed 7 years ago.
I am working on windows application in java:
I just test a button that make function login in my system:
My button action performed code:
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
if(emp.isSelected()) // get the selected radio button
{
Account a = new Account();
Emp e = new Emp();
a.setUsername(username.getText().toUpperCase());
a.setPassword(password.getText().toUpperCase());
e.login(a);
this.dispose();
}
else if(supp.isSelected())
{
}
else if(admin.isSelected())
{
Account a = new Account();
Admin m = new Admin();
a.setUsername(username.getText().toUpperCase());
a.setPassword(password.getText().toUpperCase());
m.login(a);
this.dispose();
}
else
JOptionPane.showMessageDialog(null, "Please select a choice", "Alert", JOptionPane.INFORMATION_MESSAGE);
}
The function login code:
public class Emp
{
public void login(Account a)
{
boolean find = false;
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("C:\\Users\\فاطمة\\Downloads\\employees.bin"));
ArrayList<Account> b = (ArrayList)in.readObject();
Iterator<Account> i = b.iterator();
while(i.hasNext())
{
Account ac = i.next();
if(ac.getUsername().equals(a.getUsername()) && ac.getPassword().equals(a.getPassword()))
{
find = true;
}
else
JOptionPane.showMessageDialog(null, "Wrong username or password .. try again !!", "Login Failed",JOptionPane.ERROR_MESSAGE);
}
if(find)
{
JOptionPane.showMessageDialog(null, "Welcome " + a.getUsername(), "Login Success", JOptionPane.INFORMATION_MESSAGE);
emp_page e = new emp_page();
e.setLocation(350, 150);
e.setSize(400, 490);
e.setTitle("Products Management");
e.setVisible(true);
}
} catch (FileNotFoundException ex) {
//Logger.getLogger(Emp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ClassNotFoundException ex) {
//Logger.getLogger(Emp.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
//Logger.getLogger(Emp.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
The account class code:
import java.io.Serializable;
public class Account implements Serializable{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I have a problem: i receive error:
java.lang.classnotfoundexcetpion:Account
and after searching for error reason i found that serialization is the problem of throwing this error because i test this code before in another function that dont use serialization and its worked perfectly.
so my question is: how to fix this error?
NOTE: my application is not a client-server application ... so there is no two projects created ... just only one.
long discussions about this:
ClassNotFoundException when deserializing a binary class file's contents
ClassNotFoundException during Deserialization of a just-serializaed class
Java SerialIzation: 'ClassNotFoundException' when deserializing an Object
3 advices :
be sure to put the private static final long serialVersionUID = XXX;
be sure to embark your class in your classpath/jar
force it in code with Account ac=new Account(); // See if problem here
it helps ?
I have 15 usernames with me, I need to pull worklog entries of these users and manipulate it from JAVA client
Below are the jar files am using to connect JIRA api and fetch values
The code is pasted below
public class JiraConnector {
JiraRestClient jira;
public JiraConnector() throws URISyntaxException {
String url = prop().getUrl();
String userName = prop().getUser() ;
String password = prop().getpwd() ;
JerseyJiraRestClientFactory clientFactory = new JerseyJiraRestClientFactory();
jira = clientFactory.createWithBasicHttpAuthentication(new URI(url),
userName, password);
System.out.println("Connection established to >> " + url);
}
public void printIssueDetails(String jiraNumber) {
System.out.println("JiraNumber is " + jiraNumber);
Issue issue = jira.getIssueClient().getIssue(jiraNumber, null);
System.out.println(issue.getSummary());
System.out.println(issue.getDescription());
}
public void printUserWorkLog(String userName) {
System.out.println("user details invoked ... ");
User user = jira.getUserClient().getUser(userName, null);
System.out.println(user.getDisplayName());
System.out.println(user.getEmailAddress());
}
For any given username, am able to print his displayName and emailAdress (all those basic infos).
But I need to get the list of worklogs for the given user. Not sure how to proceed
You can find all worklog records for selected issue:
List<Worklog> worklogByIssue = ComponentAccessor.getWorklogManager().getByIssue(issue);
After that you can parse all worklog records to determine for what user this record created:
for (Worklog worklogByIssueItem : worklogByIssue)
{
int timeSpent = worklogByIssueItem.getTimeSpent().intValue();
String worklogAuthorName = worklogByIssueItem.getAuthorObject().getName();
...
}
And last task is search of issues by some params:
public static List<Issue> searchIssues(SearchParametersAggregator searchParams)
{
String jqlQuery = searchParams.getJqlQuery();
String projectId = searchParams.getProjectId();
String condition = createCondition(jqlQuery, projectId);
JqlQueryBuilder jqlQueryBuilder = prepareJqlQueryBuilder(condition);
return searchIssues(jqlQueryBuilder);
}
static List<Issue> searchIssues(JqlQueryBuilder jqlQueryBuilder)
{
Query query = jqlQueryBuilder.buildQuery();
SearchService searchService = ComponentAccessor.getComponent(SearchService.class);
try
{
ApplicationUser applicationUser = ComponentAccessor.getJiraAuthenticationContext().getUser();
User user = applicationUser.getDirectoryUser();
SearchResults searchResults = searchService.search(user, query, PagerFilter.getUnlimitedFilter());
List<Issue> issues = searchResults.getIssues();
return issues;
}
catch (SearchException e)
{
LOGGER.error("Error occurs during search of issues");
e.printStackTrace();
}
return new ArrayList<Issue>();
}
static JqlQueryBuilder prepareJqlQueryBuilder(String condition)
{
try
{
Query query = jqlQueryParser.parseQuery(condition);
JqlQueryBuilder builder = JqlQueryBuilder.newBuilder(query);
return builder;
}
catch (JqlParseException e)
{
throw new RuntimeException("JqlParseException during parsing jqlQuery!");
}
}
I am doing the Java project with spring.So I am using the Jackson library to convert to get the JSON format.
My java Class will be ,
public class ChatInteraction extends Interaction{
private int ticketId;
private String name;
private String interactionType ;
private LinkedList<InteractionInfo> interactions;
public ChatInteraction(Message response) {
super(response);
interactions = new LinkedList<InteractionInfo>();
}
public int getTicketId() {
return ticketId;
}
public void setTicketId(int ticketId) {
this.ticketId = ticketId;
System.out.println("Ticket Id for Interaction : "+this.ticketId);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println("Name for Interaction : "+this.name);
}
public LinkedList<InteractionInfo> getInteractions() {
return interactions;
}
public String getInteractionType() {
return interactionType;
}
public void setInteractionType(String interactionType) {
this.interactionType = interactionType;
}
public void addInteraction(InteractionInfo interaction) {
this.interactions.add(interaction);
}
public void accept(int proxyId,String intxnId,int ticketId){
RequestAccept reqAccept = RequestAccept.create();
reqAccept.setProxyClientId(proxyId);
reqAccept.setInteractionId(intxnId);
reqAccept.setTicketId(ticketId);
System.out.println("New Chat RequestAccept Request Object ::: "+reqAccept.toString());
try{
if(intxnProtocol.getState() == ChannelState.Opened){
Message response = intxnProtocol.request(reqAccept);
System.out.println("New Chat RequestAccept Response ::: "+response.toString());
if(response != null ){
if( response.messageId() == EventAck.ID){
System.out.println("Accept new chat success !");
//EventAccepted accept = (EventAccepted)response;
//return "New chat Interaction accepted";
}else if(response.messageId() == EventError.ID){
System.out.println("Accept new chat Failed !");
//return "New chat Interaction rejected";
}
}
}else{
System.out.println("RequestAccept failure due to Interaction protocol error !");
}
}catch(Exception acceptExcpetion){
acceptExcpetion.printStackTrace();
}
}
public void join(String sessionId, String subject) {
RequestJoin join = RequestJoin.create();
join.setMessageText(MessageText.create(""));
join.setQueueKey("Resources:"); //Add the chat-inbound-key in multimedia of the optional tab values of the softphone application in CME
join.setSessionId(sessionId);
join.setVisibility(Visibility.All);
join.setSubject(subject);
KeyValueCollection kvc = new KeyValueCollection();
join.setUserData(kvc);
System.out.println("Join Request Object ::: "+join.toString());
try {
if(basicProtocol != null && basicProtocol.getState() == ChannelState.Opened){
Message response = basicProtocol.request(join);
if(response != null){
System.out.println("RequestJoin response ::: "+response);
if (response.messageId() == EventSessionInfo.ID) {
System.out.println("Join Request success !");
}else{
System.out.println("Join Request Failed !");
}
}
}else{
System.out.println("BasicChat protocol Error !");
//return "BasicChat protocol Error !";
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
I need to get only the interactionType and interactions property of this class in the JSON format like ,
{"interactionType":"invite","interactions" : [{"xx":"XX","yy":"YY"},{"xx":"XX","yy":"YY"}]}
Note :
I don't need the other properties of this class.
Also there is no SETTER for the interactions property . Instead of that I have the addInteractions() method . Does this affects any behaviour of JSON conversion ?
Also I have some other methods like accept(...) , Join(...).
I am using the jackson-all-1.9.0.jar
You can annotate the unneeded fields with #JsonIgnore - see Jackson's manual on annotations. That's what it will look like, using your code:
public class ChatInteraction extends Interaction{
#JsonIgnore
private int ticketId;
#JsonIgnore
private String name;
private String interactionType ;
private LinkedList<InteractionInfo> interactions;
You can use achieve this by using the #JsonIgnoreProperties annotation that can be used on class level.
From JavaDoc:
Annotation that can be used to either suppress serialization of
properties (during serialization), or ignore processing of JSON
properties read (during deserialization).
Example:
// to prevent specified fields from being serialized or deserialized
// (i.e. not include in JSON output; or being set even if they were included)
\#JsonIgnoreProperties({ "internalId", "secretKey" })
Example, In your case:
#JsonIgnoreProperties({ "ticketId", "name" })
public class ChatInteraction extends Interaction{
....
}
Finally I got the solution by others answers in the thread and similar answers in stackoverflow,
I marked the #JsonIgnore in the unwanted field in the sub class and super class suggested by fvu.
I have used the myObjectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); in my objectMapper suggested in other thread like,
ObjectMapper mapp = new ObjectMapper();
mapp.setVisibility(JsonMethod.FIELD, Visibility.ANY);
try {
json = mapp.writeValueAsString(info);
info.clear();
System.out.println("Chat Info in JSON String is :::> "+json);
} catch (Exception e) {
e.printStackTrace();
}
I am trying to make a game with auth system in Java. When I am trying to run it, i can see an exception thrown in the console log but there is no error in the project. I know this is runtime error
The console log displays the following information:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to Auth$Profile
at Auth.<init>(Auth.java:30)
Here is my code:
public Auth(File profilesFile) {
try {
ProfilesJSON e = (ProfilesJSON)this.gson.fromJson(new FileReader(profilesFile), ProfilesJSON.class);
Map ps = e.authenticationDatabase;
Iterator var5 = ps.keySet().iterator();
while(var5.hasNext()) {
String name = (String)var5.next();
Profile p = (Profile)ps.get(name);
if(p != null) {
if(p.displayName == null || p.displayName.length() == 0) {
p.displayName = p.username;
}
this.profiles.add(p);
}
}
} catch (FileNotFoundException var7) {
;
} catch (NullPointerException var8) {
;
}
}
public class Profile {
public String username;
public String password;
public String uid;
public String displayName;
public String name;
public String playerUID;
public Profile(String u, String t, String id, String d) {
this.username = u;
this.password = t;
this.uid = id;
this.displayName = d;
}
}
public class ProfilesJSON {
public Map profiles;
public String selectedProfile;
public String password;
public Map authenticationDatabase;
}
Line 30 is:
Profile p = (Profile)ps.get(name);
This is a part of my code, my idea is if the player press "Remember Password", the game will generate a .json file to store his infomation..I just want to know what I did wrong, other code i can write it myself
Your ps.get(name) is returning a com.google.gson.internal.LinkedTreeMap object instead of Profile.
try to change it to:
LinkedTreeMap p = (LinkedTreeMap )ps.get(name);
Your code doesn't show you errors because there's no error in compile time, ClassCastException is a runtime exception.