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!");
}
}
Related
I have user role saved in DB, so based on role ID authentication has to be done for each API.
I tried few approaches but did not succeed.
Code Snippet:
CONTROLLER:
#PreAuthorize("#AuthService.getUserRole(1)")
#PostMapping(name = "POST - Save the user info to Automation Counter table", path = "userlogininfo")
#Operation(summary = "Save the user info to Automation Counter table")
public ResponseEntity<ApiResponse> saveUserInfoinDB(#RequestBody SaveUserInfo saveUserInfoDetails, Principal principal)
{
try
{
saveUserInfoDetails.ntid = principal.getName().split("\\n")[0];
if (saveUserInfoDetails.firstName != null && saveUserInfoDetails.lastName != null && saveUserInfoDetails.ntid != null && saveUserInfoDetails.applicationName !=null)
{
ApiResponse apiResponse = restService.osmAPIPost("/dashboard/userlogininfo",saveUserInfoDetails);
return ResponseEntity.ok(apiResponse);
}
else
{
ApiResponse response = new ApiResponse<>(false, "Did not receive data in correct format", null);
return ResponseEntity.badRequest().body(response);
}
}
catch (Exception ex)
{
String logMessage = SharedUtils.logErrorMessage(this.getClass().getSimpleName(), ex, "Error while saving user info in DB.");
ApiResponse response = new ApiResponse<>(false, logMessage, null);
return ResponseEntity.badRequest().body(response);
}
}
SERVICE:
#Service
public class AuthService {
private final AuthRepository authRepository;
public AuthService(AuthRepository authRepository)
{
this.authRepository = authRepository;
}
public boolean getUserRole(int roleId)
{
try
{
boolean userRole=authRepository.getUserLoginInfo(Principal.class.getName().split("\\n")[0],roleId);
return userRole;
}
catch (Exception ex)
{
throw ex;
}
}
}
REPOSITORY:
#Transactional
public boolean getUserLoginInfo(String ntid, int roleId )
{
try
{
String returnValue=null;
String sql = "SELECT Alias FROM Users where NTID=? AND RoleId=?" ;
returnValue= osmv2JdbcTemplate.queryForObject(sql,String.class,ntid,roleId);
if(returnValue!=null)
{
return true;
}
else
{
return false;
}
}
catch(Exception ex)
{
String logMessage = SharedUtils.logErrorMessage(this.getClass().getSimpleName(), ex, "Could not fetch the User alias based on role ID and NTID from DB");
LOGGER.info(logMessage);
return false;
}
}
I have created custom method that will be used in #PreAuthorize but it did not work. The method is fetching the role id from DB based on username.Please help.. Thanks in advance:)
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;
}
I am writing a program that acts as a service and picks up emails from the email queue table, processes them and sends them out. Here is something along how I did it, and it does work fine.
MySqlConnect con = new MySqlConnect();
public PreparedStatement preparedStatement = null;
public Connection con1 = con.connect();
//pick up queue and send email
public void email() throws Exception {
try {
while(true) {
String sql = "SELECT id,user,subject,recipient,content FROM emailqueue WHERE status='Pending' ";
PreparedStatement statement = con1.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
String subject = rs.getString("subject");
String recipient = rs.getString("recipient");
String content = rs.getString("content");
String id = rs.getString("id");
String username = rs.getString("user");
String emailStatus = "DONE";
String errormsg = sendEmail(recipient, subject, content, id,username);
if (!errormsg.equals("")) {
emailStatus = "FAILED";
}
TerminalLogger.printMsg("Status : " + emailStatus);
}
statement.close();
rs.close();
}
} catch(Exception e) {
e.printStackTrace();
TerminalLogger.printMsg("Exception: "+e.toString());
}
con1.close();
Thread.sleep(2000);
}
Now, I am clearly using JDBC to obtain the result set in the loop and process them as shown. Of course, I also need to specify my database connection in MySqlConnect.java properties. While all this works perfectly fine, I was wondering is there another way of achieving the same goal without using JDBC, i.e. specifying the connection properties?
I was thinking of Java Persistence. I am new to this.
Edit
I have been told to use JPA to achieve this and I have written it in this way:
public void email() throws Exception {
try {
while(true) {
String sql = "select p.id,p.user,p.subject,p.recipient,p.content from Emailqueue p where " +
"status='Pending'";
List<Object[]> list = em.createQuery(sql).getResultList();
for (Object[] obj : list) {
System.out.println(obj[0]);
System.out.println(obj[1]);
System.out.println(obj[2]);
System.out.println(obj[3]);
System.out.println(obj[4]);
}
}
} catch(Exception e) {
e.printStackTrace();
TerminalLogger.printMsg("Exception: " + e.toString());
}
From here, I would pass the parameters I want to the method. Is this way feasible?
Edit 2
Did it a bit different like below:
String id = ejbCon.getSettingsFacade().getid();
String username = ejbCon.getSettingsFacade().getUser();
String subject = ejbCon.getSettingsFacade().getSubject();
String recipient = ejbCon.getSettingsFacade().getRecipient();
String content = ejbCon.getSettingsFacade().getContent();
String errormsg = sendEmail(recipient, subject, content, id,username);
public String getContent() {
try {
String sql="Select content FROM emailqueue WHERE status='Pending'";
if (em == null) {
throw new Exception("could not found subject");
}
return (String) em.createNativeQuery(sql).getSingleResult();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Just a bit idea of how the method looks like, the other methods follow the same concept.
List<EmailQueue> emailList = em.createQuery(sql).getResultList();
for (EmailQueue obj : emailList) {
String emailStatus = "DONE";
String errormsg=sendEmail(obj.getRecipient(), obj.getSubject, obj.getContent(),obj.getId(),obj.getUsername());
if (!errormsg.equals("")) {
emailStatus = "FAILED"
}
TerminalLogger.printMsg("Status : " + emailStatus);
}
}
Before using JPA ,you must read about it WHY JPA
As discussed in the comments above, Spring Batch and Spring JPA is a good choice for your use-case,
you can follow and study about on the internet and follow the official document
Spring JPA tutorial link
Spring Batch tutorial link
Happy Learning, Hope more users would suggest other good options that you can choose from and apply to your use-case post evaluating their pros and cons
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.
here I am having three tables ringeeUser, event , eventuserrelation . ringee_user_id and event_id are foreign key in eventuserrelation table .
now I am trying to add a data or insert a data to eventuserrelation table I got a error like this
error while adding user relation for event id5
Cannot add or update a child row: a foreign key constraint fails (`ringeeapp_dev`.`event_user_relation`, CONSTRAINT `FK_EVT_RINGEE_USER_ID` FOREIGN KEY (`RINGEE_USER_ID`) REFERENCES `ringee_user` (`RINGEE_USER_ID`))
here I am post the code for addeventUserrelationDAOImpl
#Override
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public List<EventUserRelationDO> addEventUserRelationMapping(ArrayList<UserDO> userDOs, long eventId) throws UserDataException {
JdbcTemplate jd = this.getJdbctemplate();
int totalAdded = 0;
int IS_DELETE = IRingeeConstants.IS_NOT_DELETED;
int IS_INVITE = IRingeeConstants.IS_NOT_INVITED;
List<EventUserRelationDO> eventUserRelationDOLst = new ArrayList<EventUserRelationDO>(userDOs.size());
for (UserDO userDO : userDOs) {
try {
long ringeeUserId = userDO.getRingeeUserId();
Long eventUserRelationId = jd.queryForObject(EVENT_USER_RELATION_KEY, Long.class);
jd.update(ADD_EVENT_USER_RELATION_MAPPING, new Object[] { eventUserRelationId, eventId, ringeeUserId, IS_INVITE, IS_DELETE });
/*EventUserRelationDO eventUserRelationDO = new EventUserRelationDO();
eventUserRelationDO.setEventUserRelationId(eventUserRelationId);
eventUserRelationDO.setEventId(eventId);
eventUserRelationDO.setRingeeUserId(ringeeUserId);
eventUserRelationDOLst.add(eventUserRelationDO);*/
} catch (DuplicateKeyException dExp) {
Long eventUserExistId = jd.queryForObject(GET_USER_RELATION_EXIST_KEY, Long.class, new Object[] { eventId, userDO.getRingeeUserId() });
int isAdded = jd.update(UPDATE_EVENT_USER_RELATION, new Object[] { 0, 0, eventUserExistId });
totalAdded = totalAdded + isAdded;
} catch (EmptyResultDataAccessException empExp) {
throw new UserDataException("emtpy user relation key returned" + eventId, empExp);
} catch (DataAccessException dExp) {
throw new UserDataException("error while adding user relation for event id" + eventId, dExp);
}
}
return eventUserRelationDOLst;
}
this is the code for addEventUserRelationServiceImpl
#Override
#Transactional(propagation = Propagation.REQUIRES_NEW)
public int addEventUserRealtionMapping(ArrayList<UserBO> userBOs, long eventId) throws UserServiceException {
List<EventUserRelationDO> totalAddedCount;
ArrayList<UserDO> userDOs = new ArrayList<>();
try {
for (UserBO userBO : userBOs) {
UserDO userDO = mapper.mapUserBOToDO(userBO, new UserDO());
userDOs.add(userDO);
}
EventBO eventBO = getEventByEventId(eventId);
MessageBO messageBO = new MessageBO();
messageBO.setEventId(eventBO.getEventId());
messageBO.setEventTitle(eventBO.getText());
messageBO.setMessage(eventBO.getText());
messageBO.setRingeeUserId(eventBO.getRingeeUserId());
messageBO.setMessageType(IRingeeConstants.MESSAGE_TYPE_INVITATION);
totalAddedCount = eventDAOImpl.addEventUserRelationMapping(userDOs, eventId);
if (totalAddedCount.size() == userDOs.size()) {
manageMessageService.sendMessageToGroup(userBOs, messageBO);
}
} catch (UserDataException dExp) {
throw new UserServiceException(" exception while adding user relationship for eventId " + eventId, dExp);
}
return totalAddedCount.size();
}
this is the code for testcase of addEventuserrelation in service layer
#Test
#Rollback(false)
public void addEventUserRealtionMapping() {
ArrayList<UserBO> userBOs = new ArrayList<>();
EventBO eventBO = getEventBO();
UserBO userBO = getUserBO();
userBOs.add(getUserBO1());
try {
manageUserServiceImpl.addUser(userBO);
eventBO.setRingeeUserId(userBO.getRingeeUserId());
manageEventServiceImpl.addEvent(eventBO);
int addedTotalCount = manageEventServiceImpl.addEventUserRealtionMapping(userBOs, eventBO.getEventId());
Assert.assertEquals(userBOs.size(), addedTotalCount);
} catch (UserServiceException e) {
e.printStackTrace();
Assert.fail();
}
}
here only I got the error above I mentioned.
this is the code for adduser (this is for ur reference)
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void addEvent(EventDO eventDO) throws UserDataException {
JdbcTemplate jd = this.getJdbctemplate();
long userId = eventDO.getRingeeUserId();
try {
long eventId = jd.queryForObject(EVENT_KEY, Long.class);
int isAdded = jd.update(ADD_EVENT, eventId, userId, eventDO.getText(), eventDO.getPlace(), eventDO.getEventDate(), eventDO.getStartTime(), eventDO.getEndTime(), eventDO.getIsDelete());
// setting event id which is newly generated
if (isAdded == 0) {
throw new UserDataException("Adding new event count returns zero, hence insertion of new event failed for user " + userId);
}
eventDO.setEventId(eventId);
} catch (DataAccessException dExp) {
throw new UserDataException("Error while adding new event for user id " + userId, dExp);
}
}
this is ADDEVENT query
private static final String ADD_EVENT = "INSERT EVENT (EVENT_ID, RINGEE_USER_ID, TEXT, PLACE, EVENT_DATE, START_TIME, END_TIME, IS_DELETE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
this is the code for addUser
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void addUser(UserDO userDO) throws UserDataException {
long userId = 0;
JdbcTemplate jdbcTemplate = this.getJdbctemplate();
try {
userId = jdbcTemplate.queryForObject(USER_KEY, Long.class);
userDO.setRingeeUserId(userId);
int isAddedUser = jdbcTemplate.update(ADD_USER, new Object[] { userId, userDO.getUserName(), userDO.getRegistrationId(), userDO.getImeiCode(), userDO.getMobileNumber() });
if (isAddedUser == 0)
throw new UserDataException("Adding new user failed");
} catch (DuplicateKeyException dupkeyExp) {
log.debug("dupliate user , either mobile number, imei code or register id matches with existing user");
System.out.println("dupliate user , either mobile number, imei code or register id matches with existing user");
UserDO foundUserDO = isUserExists(userDO);
if (null == foundUserDO) {
log.debug("user neither available nor able to add new user , situation is unrealistic");
throw new UserDataException("user neither available nor able to add new user , situation is unrealistic");
}
// case 1 :- when both mobile and imei code are same then
// considering user uses same mobile
// to login in app again, in this scenario we update user details
// we are updating user details in this case, since user might get
// assigned new google registration id, hence updating the user
// details
if (userDO.getImeiCode().equals(foundUserDO.getImeiCode()) && userDO.getMobileNumber().equals(foundUserDO.getMobileNumber())) {
log.error("Already installed device user id " + userId);
userDO.setRingeeUserId(foundUserDO.getRingeeUserId());
int isUserUpdated = jdbcTemplate.update(UPDATE_USER,
new Object[] { userDO.getUserName(), userDO.getRegistrationId(), userDO.getImeiCode(), userDO.getDeleted(), foundUserDO.getRingeeUserId() });
if (isUserUpdated == 0)
throw new UserDataException("updating user failed");
// case 2 :- when mobile number and imei code not matching, then
// consider that user user different mobile
// to login app, this is very important scenario, since many
// ways this can happen.
// 1. one user downloaded app on a mobile , registered and later
// he transfers mobile to another user, and he uses different
// mobile
// to login , here mobile number will be different , but imei
// code is same
// 2. same user same mobile , but uses different mobile number
// in both cases, we make first user deactivate and new user
// activate with that mobile number
} else if (userDO.getImeiCode().equals(foundUserDO.getImeiCode()) && !userDO.getMobileNumber().equals(foundUserDO.getMobileNumber())) {
// set deleted = 1, deactivating already existing/registered
// user, since new mobile number getting assigned to this mobile
foundUserDO.setDeleted(1);
int isUserUpdated = jdbcTemplate.update(UPDATE_USER, new Object[] { foundUserDO.getUserName(), foundUserDO.getRegistrationId(), foundUserDO.getImeiCode(), foundUserDO.getDeleted(),
foundUserDO.getRingeeUserId() });
if (isUserUpdated == 1) {
// calling recursive method to add user after found user
// deactivated.
addUser(userDO);
} else if (isUserUpdated == 0) {
throw new UserDataException("deacitivation existing user and add new user for the mobile number " + userDO.getMobileNumber() + " failed");
}
} else {
// if already user return 0
userDO.setRingeeUserId(0);
}
} catch (DataAccessException dataAccExp) {
throw new UserDataException("User Registration Failed", dataAccExp);
}
}
this is the query for ADDUSER
private static final String ADD_USER = "INSERT RINGEE_USER (RINGEE_USER_ID, USER_NAME, REGISTRATION_ID, IMEI_CODE, MOBILE_NUMBER, CREATED_DTTM) VALUES ( ?, ?, ?, ?, ?, CURRENT_TIMESTAMP())";