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();
}
Related
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 ?
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
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I created a website with JSP and Java, it simply displays a form (it's a user registration form) where the user can fill it, then I want it to be stored in a database.
I installed Eclipse, Tomcat (to host on localhost 8080) and Wampserver (to have phpmyadmin and my SQL database).
I've tried to create an ORM (Object-relational mapping), so when the client submits the form, it sends the datas to my ORM, my ORM then stores the datas in my database.
The issue is, when the user submit submits the form, my table is created (I can see it on phpmyAdmin), so it's very good. But it crashes on my website and creates an error
HTTP500, java.lang.NullPointerException.
It says the problem is on
com.jweb.bdd.Orm.Perform(Orm.java:139)
Here is my code in my CreateClient.java file, this java file handles the servlet of my registration form:
public class CreationClient extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
[...]
String lastName= request.getParameter( CHAMP_LASTNAME);
String Name= request.getParameter( CHAMP_NAME);
String mailAdress = request.getParameter( CHAMP_MAILADRESS);
String phoneNumber= request.getParameter( CHAMP_PHONENUMBER);
String login= request.getParameter( CHAMP_LOGIN);
[...]
Orm orm = new Orm();
String[] field = {"login", "firstName", "lastName", "mailAdress", "adress", "phoneNumber", "password"};
String[] values = {login, firstName, lastName, mailAdress, adress, phoneNumber, password};
orm.Insert("client", field);
orm.Values(values);
orm.Perform();
orm.CloseConnection();
[...]
}
}
Here is my Perfom() function in my ORM class:
public void Perform(){
ResultSet rst = null;
if (select != null){
if (from != null && where != null){
try {
rst = statement.executeQuery(select + from + where);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
int i = 0;
while (rst.next()){
res[i] = rst.getString(0) + ":" + rst.getString(1)+ ":" + rst.getString(3) + ":" + rst.getString(4) +":" + rst.getString(5) + ":" + rst.getString(6)+ ":" + rst.getString(7) + ";";
i++;
}
} catch (SQLException e){
e.printStackTrace();
}
}
}
else if (insert != null){
if (values != null){
try {
// statement = connexion.creatStatemnt();
int res = statement.executeUpdate(insert + values);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
try {
rst.close();
} catch (SQLException ignore){
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
}
And the error on the line 139 is the int res = statement.executeUpdate(insert + values); :
else if (insert != null){
if (values != null){
try {
int res = statement.executeUpdate(insert + values);
} catch (SQLException e) {
e.printStackTrace();
}
}
Do you have any idea how to fix this issue of NullPointer?
Thanks.
You need to initialize your statement object, In your code you used statement.executeQuery() but not statement = connection.createStatement() initialize statement object.
So, i have this program, and it works okey. But i have a problem. You aren't suppose to be able to add an ID that's already in the ID table in my array.
This is the code for my listener on my add button (laggTill)
I don't know how to make the exception stop the data from being added. So when i for example put letters in my ID box im not suppose to be able to add it. But it still does. By JOptionPane comes upp and says the error message but still add it to the array. How do i stop this from happening?
I though an exception stopped everything, but apparently it doesn't.
And i also need the exception for ID checking to work.. i don't know how to do it.. i haven't been doing this for a while so i can't figure it out.
So, Basicly, My questions are: how do you make an exception hinder the data from being added. And how do i make my class check if the ID is unique?
Main class:
private class Listener implements ActionListener {
String getId;
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == laggTill) {
DTODjur dto = new DTODjur();
dto.djurNamn = textFieldNamn.getText();
dto.djurKategori = (String) comboBox.getSelectedItem();
try {
dto.djurID = Integer.parseInt(textFieldId.getText());
dao.laggTill(dto);
} catch (WrongDjurID ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
textArea.setText("Lade till: \nID: " + textFieldId.getText() + "\nNamn: " + textFieldNamn.getText() + "\nKategori: "+ comboBox.getSelectedItem());
}
DAO class:
public void laggTill(DTODjur dto) throws WrongDjurID {
boolean found = false;
openDB();
try {
int djurid = dto.djurID;
String djurnamn = dto.djurNamn;
String djurkategori = dto.djurKategori;
String SQL = "INSERT INTO h12mjont_djur(djurID,djurNamn,djurKategori) VALUES('" + djurid + "','" + djurnamn + "','" + djurkategori + "')";
System.out.println(SQL);
st.executeUpdate(SQL);
found=true;
} catch (SQLException ex) {
}
if (!found) {
throw new WrongDjurID("Id ska inte innehålla bokstäver");
}else {
dtodjur = getAll();
}
closeDB();
dtodjur = getAll();
}
Your problem is you are catching exceptions then proceeding as if nothing had happened by writing code after the catches. I'd suggest moving all catch logic to the very end of each method. In your first block change it to this:
String getId;
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == laggTill) {
DTODjur dto = new DTODjur();
dto.djurNamn = textFieldNamn.getText();
dto.djurKategori = (String) comboBox.getSelectedItem();
try {
dto.djurID = Integer.parseInt(textFieldId.getText());
dao.laggTill(dto);
textArea.setText("Lade till: \nID: " + textFieldId.getText() + "\nNamn: " + textFieldNamn.getText() + "\nKategori: "+ comboBox.getSelectedItem());
} catch (WrongDjurID ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
2nd block of code:
public void laggTill(DTODjur dto) throws WrongDjurID {
openDB();
try {
int djurid = dto.djurID;
String djurnamn = dto.djurNamn;
String djurkategori = dto.djurKategori;
String SQL = "INSERT INTO h12mjont_djur(djurID,djurNamn,djurKategori) VALUES('" + djurid + "','" + djurnamn + "','" + djurkategori + "')";
System.out.println(SQL);
st.executeUpdate(SQL);
dtodjur = getAll();
} catch (SQLException ex) {
throw new WrongDjurID("Id ska inte innehålla bokstäver");
} finally {
closeDB();
}
}
Now the getAll() call will not be run if an exception is thrown. Previously you were running getAll() even if an exception was thrown which would re-read the list. Remember to use finally clause to clean up after you read the DB regardless of if it was successful or an exception was thrown.
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)