Spring Rest API TransactionSystemException - java

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 ?

Related

JSchException Cannot find message

I want to know some of the reasons that can cause below exception. I am unable to find this message Cannot find message in jsch-0.1.54.jar. There exists some straight forward messages like file not found and others that make sense. But I need more information about this one so that I can reach to the root cause.
SftpException while running get ---> 2: Cannot find message [/destination/file.txt]
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2289)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1741)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1758)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:786)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:750)
at com.iyi.ftp.SFTP.get(SFTP.java:99)
Here is my calling method.
public boolean get(final String remoteFile, final String localFile) throws JSchException {
Vector connection = null;
Session session = null;
ChannelSftp c = null;
boolean status = false;
try {
connection = this.connect();
session = connection.get(0);
c = connection.get(1);
c.get(remoteFile, localFile);
status = true;
}
catch (JSchException e) {
SFTP.LGR.warn((Object)("JSchException in SFTP::get() ---> " + FTPFactory.getStackTrace((Throwable)e)));
throw e;
}
catch (SftpException e2) {
SFTP.LGR.warn((Object)("SftpException while running get ---> " + FTPFactory.getStackTrace((Throwable)e2)));
throw new JSchException(e2.getMessage());
}
catch (CredentialDecryptionException e3) {
SFTP.LGR.error((Object)"##CredentialDecryptionException##", (Throwable)e3);
throw new JSchException(e3.getMessage(), (Throwable)e3);
}
finally {
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
}
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
return status;
}
These methods are fetched from jsch-0.1.54.jar which is an open source utility.
public void get(String src, String dst, final SftpProgressMonitor monitor, final int mode) throws SftpException {
boolean _dstExist = false;
String _dst = null;
try {
((MyPipedInputStream)this.io_in).updateReadSide();
src = this.remoteAbsolutePath(src);
dst = this.localAbsolutePath(dst);
final Vector v = this.glob_remote(src);
final int vsize = v.size();
if (vsize == 0) {
throw new SftpException(2, "No such file");
}
final File dstFile = new File(dst);
final boolean isDstDir = dstFile.isDirectory();
StringBuffer dstsb = null;
if (isDstDir) {
if (!dst.endsWith(ChannelSftp.file_separator)) {
dst += ChannelSftp.file_separator;
}
dstsb = new StringBuffer(dst);
}
else if (vsize > 1) {
throw new SftpException(4, "Copying multiple files, but destination is missing or a file.");
}
for (int j = 0; j < vsize; ++j) {
final String _src = v.elementAt(j);
final SftpATTRS attr = this._stat(_src);
if (attr.isDir()) {
throw new SftpException(4, "not supported to get directory " + _src);
}
_dst = null;
if (isDstDir) {
final int i = _src.lastIndexOf(47);
if (i == -1) {
dstsb.append(_src);
}
else {
dstsb.append(_src.substring(i + 1));
}
_dst = dstsb.toString();
if (_dst.indexOf("..") != -1) {
final String dstc = new File(dst).getCanonicalPath();
final String _dstc = new File(_dst).getCanonicalPath();
if (_dstc.length() <= dstc.length() || !_dstc.substring(0, dstc.length() + 1).equals(dstc + ChannelSftp.file_separator)) {
throw new SftpException(4, "writing to an unexpected file " + _src);
}
}
dstsb.delete(dst.length(), _dst.length());
}
else {
_dst = dst;
}
final File _dstFile = new File(_dst);
if (mode == 1) {
final long size_of_src = attr.getSize();
final long size_of_dst = _dstFile.length();
if (size_of_dst > size_of_src) {
throw new SftpException(4, "failed to resume for " + _dst);
}
if (size_of_dst == size_of_src) {
return;
}
}
if (monitor != null) {
monitor.init(1, _src, _dst, attr.getSize());
if (mode == 1) {
monitor.count(_dstFile.length());
}
}
FileOutputStream fos = null;
_dstExist = _dstFile.exists();
try {
if (mode == 0) {
fos = new FileOutputStream(_dst);
}
else {
fos = new FileOutputStream(_dst, true);
}
this._get(_src, fos, monitor, mode, new File(_dst).length());
}
finally {
if (fos != null) {
fos.close();
}
}
}
}
catch (Exception e) {
if (!_dstExist && _dst != null) {
final File _dstFile2 = new File(_dst);
if (_dstFile2.exists() && _dstFile2.length() == 0L) {
_dstFile2.delete();
}
}
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
private SftpATTRS _stat(final byte[] path) throws SftpException {
try {
this.sendSTAT(path);
Header header = new Header();
header = this.header(this.buf, header);
final int length = header.length;
final int type = header.type;
this.fill(this.buf, length);
if (type != 105) {
if (type == 101) {
final int i = this.buf.getInt();
this.throwStatusError(this.buf, i);
}
throw new SftpException(4, "");
}
final SftpATTRS attr = SftpATTRS.getATTR(this.buf);
return attr;
}
catch (Exception e) {
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
The error message comes from your server. It's indeed quite strange message, but I assume that it's some custom SFTP server that deals with some "messages" rather than plain files.
So the message basically translates to "Cannot find file" error of a traditional SFTP server. Even the error code 2 (SSH_FX_NO_SUCH_FILE) supports that.
Your path in remoteFile is probably wrong.

IllegalStateException while reading response

I am reading JAVAX response using readEntity() method but I am getting following stacktrace :
java.lang.IllegalStateException: Entity input stream has already been closed.
at org.glassfish.jersey.message.internal.EntityInputStream.ensureNotClosed(EntityInputStream.java:225) ~[jersey-common.jar:?]
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:832) ~[jersey-common.jar:?]
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:785) ~[jersey-common.jar:?]
at the line
Map<String, Map> mapEntityFromResponse = res.readEntity(Map.class);
Here is my code
public Output getClaimsFromAPI(#NonNull final Input xyzInput)
throws PermanentException, TransientException {
final Response res = fetchHealBeamServiceResponse(webTarget, xyzInput);
Object respondentMapObject;
Map<String, Map> mapEntityFromResponse = res.readEntity(Map.class);
if (mapEntityFromResponse != null) {
respondentMapObject = mapEntityFromResponse.get(ServiceConstants.MAP_KEY);
return getOutputFromResponseMap(respondentMapObject, xyzInput);
} else {
throw new RuntimeException("The response returned does not contain map");
}
}
private Response fetchHealBeamServiceResponse(WebTarget healBeamTarget,
Input xyzInput)
throws PermanentException, TransientException {
Response res = null;
try {
res = healBeamTarget
.path(HealBeamServiceConstants.GET_CUSTOMER_PATH)
.register(Configurator.getSoaOpNameFeatureForCustomerResource())
.resolveTemplate(ServiceConstants.ID, xyzInput.getId())
.request(MediaType.APPLICATION_JSON_TYPE)
.property(HealBeamServiceConstants.SERVICE_KEY, SOA_SERVICE_NAME)
.property(HealBeamServiceConstants.OPERATION_KEY, SOA_OP_NAME_GET_CUSTOMER)
.acceptLanguage(java.util.Locale.getDefault())
.get();
if (Response.Status.REQUEST_TIMEOUT.getStatusCode() == res.getStatusInfo().getStatusCode()) {
throw new TransientException("Request timed out with status" + res.getStatusInfo().getStatusCode());
} else if (Response.Status.OK.getStatusCode() != res.getStatusInfo().getStatusCode()) {
log.error("Some Error"):
}
return res;
} catch (RuntimeException e) {
throw new PermanentException("Unexpected Exception Occured, Exception Message " + e.getMessage());
} finally {
if (res != null) {
res.close();
}
}
}
You are closing your response in finally right before it gets returned, that is the reason, why you can't read from it in your calling method getClaimsFromAPI().
Just to demonstrate: What do you think the method main() posted below would print?
public class NewApp {
public static void main(String[] args) {
Person p = demonstrate();
System.out.println(p.name);
}
public static Person demonstrate(){
Person person = new Person();
try {
person.name = "name set in try";
return person;
} catch (Exception ex) {
throw ex;
} finally {
person.name = "name set in finally";
}
}
}
class Person {
public String name;
}

How to get response of snmptrap v2 with private mib

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

Exception in thread "http-apr-8080-exec-11"

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

How to properly return a string from a method with try and catch

Every time I called this method it always return null even if the value of userProfile.get("facebookId") is not null.
public String updateProfilePicture() {
String facebookId = null;
if (currentUser.get("profile") != null) {
JSONObject userProfile = currentUser.getJSONObject("profile");
try {
if (userProfile.getString("facebookId") != null) {
facebookId = userProfile.get("facebookId").toString();
} else {
facebookId = null;
}
} catch (JSONException e) {
// handle error
facebookId = null;
}
}
return facebookId;
}

Categories