the private mib is define as below:
1.3.6.1.4.1.49763.1.2.5
userTrap NOTIFICATION-TYPE
OBJECTS{
userName,
userType,
userStatus
}
STATUS current
DESCRIPTION
"Traps of user operation"
::={stationTrap 2}
My code is supported by SNMP4J as below
public void processPdu(CommandResponderEvent CREvent) {
if (CREvent != null && CREvent.getPDU() != null) {
try {
Vector<? extends VariableBinding> recVBs =
CREvent.getPDU().getVariableBindings();
for (int i = 0; i < recVBs.size(); i++) {
VariableBinding recVB = recVBs.elementAt(i);
System.out.println(recVB.getOid() + " : " +
recVB.getVariable());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want to know what is the response type of this trap ,how to get userName and userType in the OBJECTS
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'm very new in spring development because I'm not a back developer.
I create a back to manage sports training.
I has several times a TransactionSystemException like
Exceptionorg.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
I don't understand what it mean.
I have a class Person who contains a Coordinates object on #OneToOne relation.
Each class have a Service class that has a method of adding.
In PersonService's add method, I call the Coordinates add method which save and return saved object.
This is the add method of PersonClass
public ResponseService<ObjectCreatedModel<UUID, PersonneMorale>> add(PersonneMorale personneMorale) {
String messageErreur = TAG + " - add - ";
StatusReturn status = StatusReturn.ERROR;
String message = null;
ObjectCreatedModel<UUID, PersonneMorale> objectCreatedModel = null;
if (personneMorale != null) {
if (personneMorale.getId() == null) {
personneMorale.setId(UUID.randomUUID());
try {
// Gestion des coordonnees
ResponseService<ObjectCreatedModel<UUID, Coordonnees>> responseServiceCoordonnees =
coordonneesService.add(personneMorale.getCoordonnees());
if (responseServiceCoordonnees.isSuccess() || responseServiceCoordonnees.exist()) {
ResponseService<Coordonnees> responseServiceCoordonneesGet = coordonneesService
.getOne(responseServiceCoordonnees.getObjectReturn().getId());
Coordonnees coordonnees = responseServiceCoordonneesGet.getObjectReturn();
personneMorale.setCoordonnees(coordonnees);
personneMorale = personneMoraleRepository.save(personneMorale);
if (personneMorale != null) {
status = StatusReturn.SUCCESS;
objectCreatedModel = new ObjectCreatedModel<>(personneMorale.getId(), null);
} else {
message = messageErreur + StringResource.E_OCCURRED;
}
} else {
status = responseServiceCoordonnees.getStatusReturn();
message = responseServiceCoordonnees.getMessage();
}
} catch (ConstraintViolationException violationException) {
status = StatusReturn.EXCEPTION;
message = messageErreur + ConstraintViolationReader.extractException(violationException);
} catch (Exception ex) {
status = StatusReturn.EXCEPTION;
message = messageErreur + ex.toString();
}
} else {
message = messageErreur + StringResource.E_MUST_NULL;
}
} else {
message = messageErreur + StringResource.E_SET_PARAMETER;
}
return new ResponseService<>(status, message, objectCreatedModel);
}
This is the add method of CoordinatesService
public ResponseService<ObjectCreatedModel<UUID, Coordonnees>> add(Coordonnees coordonnees) {
StatusReturn status = StatusReturn.ERROR;
String message = "";
ObjectCreatedModel<UUID, Coordonnees> objectCreatedModel = null;
if (coordonnees != null) {
if (coordonnees.getIdCoordonnees() == null) {
try {
coordonnees.setIdCoordonnees(UUID.randomUUID());
Coordonnees coordonneesBase = coordonneesRepository.save(coordonnees);
if (coordonneesBase != null) {
status = StatusReturn.SUCCESS;
objectCreatedModel = new ObjectCreatedModel<>(coordonneesBase.getIdCoordonnees(), null);
} else {
message = StringResource.E_ERROR_OCCURRED;
}
} catch (ConstraintViolationException violationException) {
status = StatusReturn.EXCEPTION;
message = "Exception" + ConstraintViolationReader.extractException(violationException);
} catch (Exception ex) {
status = StatusReturn.EXCEPTION;
message = "Exception" + ex.toString();
}
} else {
message = "Coordonnées" + ErrorsString.ERROR_COMMON_ID_MUST_BE_EMPTY;
}
} else {
message = ErrorsString.ERROR_COORDINATES_MANDATORY;
}
return new ResponseService<>(status, message, objectCreatedModel);
}
The error occurs when CoordinatesService try to save coordinates and pass to the catch (Exception e)
Could you help me to understand what Transaction error mean with an example like my code please ?
I am trying save the data's which i get from API and my function is as below
try {
// Simulate network access.
mNetworkSubscription = NetworkRequest.performAsyncRequest(api.getPatientsData(tenantID), (data) -> {
// Update UI on main thread
try {
// long pat_id = 0;
if(data != null) {
if(data.getAsJsonObject().get("error") != null){
publishResults("getPatientsData",STATUS_ERROR, null);
}
if (data != null && data.get("result") != null && data.get("result").toString() != "false") {
Realm realm = Realm.getDefaultInstance();
JsonParser parser = new JsonParser();
// realm.beginTransaction();
// realm.where(Patient.class).findAll().deleteAllFromRealm();
//realm.commitTransaction();
try {
JsonArray casesJsonArray = data.get("result").getAsJsonArray();//parser.parse(data.get("result").getAsJsonObject().toString()).getAsJsonArray();
Log.v(Constants.TAG,"PatientJsonArray: "+casesJsonArray);
if(casesJsonArray.size() > 0) {
Patient patientRecord = new Patient();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
for (int i = 0; i < casesJsonArray.size(); i++) {
try {
JsonObject jsonObject = (JsonObject) casesJsonArray.get(i);
Log.e(Constants.TAG, "execute: jsonObject "+jsonObject);
Log.e(Constants.TAG, "execute: id "+id);
if(realm.where(Patient.class).max("id") != null) {
id = realm.where(Patient.class).max("id").intValue();
Log.e(Constants.TAG, "execute:getPatientsData : In DataSync: " + id);
}
Log.e(Constants.TAG, "execute: jsonObject "+jsonObject);
Log.e(Constants.TAG, "execute: id "+pat_id);
patientRecord.setId(id + 1);
patientRecord.setTenantID(jsonObject.get("tenant_id").getAsLong());
patientRecord.setPatientID(jsonObject.get("patient_id").getAsLong());
patientRecord.setFirstName(jsonObject.get("first_name").getAsString());
patientRecord.setLastName(jsonObject.get("last_name").getAsString());
patientRecord.setPatientWeight(jsonObject.get("patient_weight").getAsString());
patientRecord.setPatientAge(jsonObject.get("patient_age").getAsString());
patientRecord.setGender(jsonObject.get("gender").getAsString());
patientRecord.setStreetAddress(jsonObject.get("street_address").getAsString());
patientRecord.setArea(jsonObject.get("area").getAsString());
patientRecord.setCity(jsonObject.get("city").getAsString());
patientRecord.setZipcode(jsonObject.get("zipcode").getAsString());
patientRecord.setState(jsonObject.get("state").getAsString());
patientRecord.setEmail(jsonObject.get("email").getAsString());
patientRecord.setEnqNumber(jsonObject.get("alternate_number").getAsString());
patientRecord.setEnqName(jsonObject.get("enquirer_name").getAsString());
realm.copyToRealmOrUpdate(patientRecord);
}catch (Exception e){
Log.v(Constants.TAG,"caseList Insert exception: "+e.toString());
}
}
}
});
//realm.close();
}
} catch (Exception e) {
Log.v(Constants.TAG, "getPatientsData Exception: " + e.toString());
}
realm.close();
}
}
} catch (Exception e) {
Log.e(Constants.TAG, "getPatientsData() exception: " + e.toString());
publishResults("getPatientsData",STATUS_ERROR, null);
}finally {
publishResults("getPatientsData",STATUS_FINISHED, null);
}
}, (error) -> {
// Handle Error
Log.e(Constants.TAG,"getPatientsData() Error: "+error.getCause());
publishResults("getPatientsData",STATUS_ERROR, null);
});
}catch (Exception e){
Log.e(Constants.TAG,"getPatientsData() Exception: "+e.toString());
publishResults("getPatientsData",STATUS_ERROR, null);
}
But realm.copyOrUpdate(patientRecords);
is not creating/saving a record in local.
First confirm, if there is no exceptions arises?
Try following workarounds,
Check casesJsonArray.size() > 0 must be true. (OR)
Remove realm.close() and try it once. Sometime it will close realm database connection in between the operation. (OR)
Try with hardcoded(dummy) data.
If above doesn't work then post your Patient Model here.
Note: For auto increment of id you can use following code which will reduce no of database calls-
Number num = realm.where(Patient.class).max("id");
int l_id;
if (num == null) {
i_id = 0;
} else {
i_id = num.intValue() + 1;
}
My java application was running fine, but now only some functionality of it throws this error
Exception in thread "http-apr-8080-exec-11" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2367)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:587)
at java.lang.StringBuilder.append(StringBuilder.java:214)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:575)
functionalities are add campaign and delete campaign. When i try to add a campaign or delete a campaign this error is thrown.
Theres option of adding keywords in each campaign, that is running fine. and also other parts of application is running fine.
code snippet of the delete campaign service
public String deleteSerpsCampaign() {
objRequest = ServletActionContext.getRequest();
//initializing http session object
objSession = objRequest.getSession();
//checking for 'customerID' attribute in session
if (objSession.getAttribute("customerID") != null) {
Integer campaignId = 0;
campaignId = Integer.parseInt(jString);
System.out.println("Site id is:::" + campaignId);
//reading the 'customerID' from session and type casting it to integer
Integer customerID = (Integer) objSession.getAttribute("customerID");
//now invoking the deleteCampaign() method of CampaignsServiceImpl
String campaignName = objCampaignsService.deleteCampaign(campaignId, customerID);
message = "'" + campaignName + "' - Campaign has been Deleted";
objSession.setAttribute("message", message);
return SUCCESS;
}
//if session attribute 'customerID' is null then return result parameter as 'LOGIN'
//this result parameter is mapped in 'struts.xml'
return LOGIN;
}
deleteCampaign method
public String deleteCampaign(Integer campaignId, Integer customerID) {
int delCount = 0;
Campaigns objcamp = (Campaigns) getSession().get(Campaigns.class, campaignId);
try {
Collection objserpkeywords = objcamp.getSerpkeywordsCollection();
Iterator itr = objserpkeywords.iterator();
while (itr.hasNext()) {
Serpkeywords objserpkeys = (Serpkeywords) itr.next();
if (objserpkeys.getVisibility() == 1) {
delCount++;
objserpkeys.setVisibility(0);
getSession().update(objserpkeys);
}
}
Collection objseokeywords = objcamp.getSeokeyworddetailsCollection();
Iterator ittr = objseokeywords.iterator();
while (ittr.hasNext()) {
Seokeyworddetails objseokeys = (Seokeyworddetails) itr.next();
if (objseokeys.getVisibility() == 1) {
objseokeys.setVisibility(0);
getSession().update(objseokeys);
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
String sQuery = "update campaigns set visibility=0 where CampaignID=:campaignId";
SQLQuery objQuery = getSession().createSQLQuery(sQuery);
objQuery.setParameter("campaignId", campaignId);
objQuery.executeUpdate();
} catch (DataAccessResourceFailureException | IllegalStateException | HibernateException ex) {
l.error(ex + " " + ex.getMessage());
}
Customers objCustomers = (Customers) getSession().get(Customers.class, customerID);
try {
objCustomers.setActiveSerpCampaignsCount(objCustomers.getActiveSerpCampaignsCount() - 1);
objCustomers.setActiveKeywordCount(objCustomers.getActiveKeywordCount() - delCount);
getSession().update(objCustomers);
} catch (DataAccessResourceFailureException | IllegalStateException | HibernateException ex) {
l.error(ex + " " + ex.getMessage());
}
return objcamp.getCampaign();
}
I have using Google (GDATA) Gmail API for retrieving the contact list from gmail, It is working successfully on windows environment, but when I run the same code on Linux, I get error of Invalid Credentials.
I googled it, but can't get much help,
here is my code
public static String getGmailContactList() {
String response = "";
StringBuilder str = new StringBuilder();
String statusString = "";
ArrayList list = new ArrayList();
ContactsService myService = new ContactsService("");
String email = "xxxxx#gmail.com";
String password = "xxxxxxxx";
try
{
try
{
myService.setUserCredentials(email, password);
}
catch (AuthenticationException ex)
{
ex.printStackTrace();
//****I got exception here when using this code on LINUX ENVIORMENT** ***
}
response = printAllContacts(myService, email);
Iterator itr = list.iterator();
while (itr.hasNext())
{
ArrayList contact = (ArrayList) itr.next();
try
{
str.append(contact.get(1)).append(",");
}
catch (Exception e)
{
log.debug("Exception ocurred inside fethching gmail contact >
>
>
" + e);
str.append("no contacts found");
}
str.substring(0, str.length() - 1);
}
}
catch (Exception ae)
{
response = statusString;
log.debug("Exception ocurred inside ReadContacts : getGmailContactList()" + ae);
}
return response;
}
public static String printAllContacts(ContactsService myService, String emailSent)//
throws ServiceException, IOException
{
URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/" + emailSent + "/full");
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(100);
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
String phones = null;
String emails = null;
log.debug(resultFeed.getTitle().getPlainText());
StringBuilder contacts = new StringBuilder();
contacts.append("<?xml version=\"1.0\"><Contacts>");
for (int i = 0; i < resultFeed.getEntries().size(); i++)
{
contacts.append("<Contact>");
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasName())
{
Name name = entry.getName();
if (name.hasFullName())
{
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi())
{
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
contacts.append("<Name>").append(fullNameToDisplay).append("</Name>");
}
else
{
contacts.append("<Name>").append("").append("</Name>");
}
}
else
{
contacts.append("<Name>").append("").append("</Name>");
}
StringBuilder emailIds = new StringBuilder();
if (entry.hasEmailAddresses())
{
List<Email> email = entry.getEmailAddresses();
if (email != null && email.size() > 0)
{
for (Email e : email)
{
emailIds.append(e.getAddress()).append(",");
}
emailIds.trimToSize();
if (emailIds.indexOf(",") != -1)
{
emails = emailIds.substring(0, emailIds.lastIndexOf(","));
}
contacts.append("<Email>").append(emails).append("</Email>");
}
else
{
contacts.append("<Email>").append("").append("</Email>");
}
}
else
{
contacts.append("<Email>").append("").append("</Email>");
}
contacts.append("</Contact>");
}
contacts.append("</Contacts>");
return contacts.toString();
}
so where I am lacking behind, some sort of help will be appriciated
here is the stack trace
com.google.gdata.client.GoogleService$InvalidCredentialsException: Invalid credentials
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:660)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:560)
at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:319)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303)
at com.gmail.ReadContacts.getGmailContactList(ReadContacts.java:55)