Updating database table is failing using update clause in hibernate - java

am trying to update a batch of columns in a table called customer . it works when i update two columns when hard coded the data.my aim is to fetch data from another table will updating the other. please here. it's not throwing any exception but just the code is not running . Thanks in advance
Session session = HibernateUtil.getSessionFactory().openSession();
customerdata.stream().forEach((row) -> {
session.beginTransaction();
// record data loggingg of customer import data transaction
String sql = "UPDATE Customer SET first_name = :first_name ,second_name = :second_name,"
+ "other_names = :other_name,gender = :gender,"
+ "date_opened = :date_opened,date_approved = :date_approved,branch_code = :branch_code,"
+ "national_id_number = :national_id_number,crb_number = :crb_number,"
+ "passport_number = :passport_number,passport_expiry_date = :passport_expiry_date,"
+ "voters_number = :voters_number,student_id_number = :student_id_number,"
+ "employer_id_number = :employer_id_number,finance_card_number = :finance_card_number,"
+ "driving_permit_number = :driving_permit_number,nssf_number = :nssf_number,tin_number = :tin_number,"
+ "police_id_number = :police_id_number,updf_number = :updf_number,"
+ "mobile = :mobile,telephone1 = :telephone1,telephone2 = :telephone2,"
+ "email = :email ,is_salaried = :is_salaried,plot_number = :plot_number,postal_address = :postal_address,"
+ "street = :street,account_operating_mode = :account_operating_mode,"
+ "primary_account_type = :primary_account_type,"
+ "address_type = :address_type,address_description = :address_description,dob_given = :dob_given,"
+ "date_of_birth = :date_of_birth, client_type = :client_type, country_of_origin = :country_of_origin,"
+ "city_of_origin = :city_of_origin,city_description = :city_description, employment_type = :employment_type,"
+ "introducer_details_available = :introducer_details_available,literacy_level = :literacy_level,"
+ "literacy_description = :literacy_description,marital_status = :marital_status,"
+ "marital_status_description = :marital_status_description,"
+ "nationality = :nationality,number_of_dependants = :number_of_dependants,residence = :residence,"
+ "residence_type = :residence_type ,resident_state = :resident_state,type_of_id = :type_of_id,"
+ "client_status = :client_status ,date_closed = :date_closed WHERE rim = :rim";
Query query = session.createQuery(sql);
query.setParameter("fname", row[2].toString());
query.setParameter("second_name", row[3].toString());
query.setParameter("other_name", row[4].toString());
query.setParameter("gender", row[5].toString());
query.setParameter("date_opened", (Date) row[6]);
query.setParameter("date_approved", (Date) row[7]);
query.setParameter("branch_code", row[8].toString());
query.setParameter("national_id_number", Integer.parseInt(row[9].toString()));
query.setParameter("crb_number", row[10].toString());
query.setParameter("passport_number", row[11].toString());
query.setParameter("passport_expiry_date", (Date) row[12]);
query.setParameter("voters_number", row[13].toString());
query.setParameter("student_id_number", row[14].toString());
query.setParameter("employer_id_number", row[15].toString());
query.setParameter("finance_card_number", row[16].toString());
query.setParameter("driving_permit_number", row[17].toString());
query.setParameter("nssf_number", row[18].toString());
query.setParameter("tin_number", row[19].toString());
query.setParameter("police_id_number", row[20].toString());
query.setParameter("updf_number", row[21].toString());
query.setParameter("mobile", row[22].toString());
query.setParameter("telephone1", row[23].toString());
query.setParameter("telephone2", row[24].toString());
query.setParameter("email", row[25].toString());
query.setParameter("is_salaried", (Boolean) row[26]);
query.setParameter("plot_number", row[27].toString());
query.setParameter("postal_address", Integer.parseInt(row[28].toString()));
query.setParameter("street", row[29].toString());
query.setParameter("account_operating_mode", Integer.parseInt(row[30].toString()));
query.setParameter("primary_account_type", Integer.parseInt(row[31].toString()));
query.setParameter("address_type", row[32].toString());
query.setParameter("address_description", row[33].toString());
query.setParameter("dob_given", (Boolean) row[34]);
query.setParameter("date_of_birth", (Date) row[35]);
query.setParameter("client_type", row[36].toString());
query.setParameter("country_of_origin", row[37].toString());
query.setParameter("city_of_origin", row[38].toString());
query.setParameter("city_description", row[39].toString());
query.setParameter("employment_type", row[40].toString());
query.setParameter("introducer_details_available", row[41].toString());
query.setParameter("literacy_level", row[42].toString());
query.setParameter("literacy_description", row[43].toString());
query.setParameter("marital_status", row[44].toString());
query.setParameter("marital_status_description", row[45].toString());
query.setParameter("nationality", row[46].toString());
query.setParameter("number_of_dependants", Integer.parseInt(row[47].toString()));
query.setParameter("residence", row[48].toString());
query.setParameter("residence_type", row[49].toString());
query.setParameter("resident_state", row[50].toString());
query.setParameter("type_of_id", Integer.parseInt(row[51].toString()));
query.setParameter("client_status", row[52].toString());
query.setParameter("date_closed", (Date) row[53]);
//setting rim data
query.setParameter("rim",row[1].toString());
query.executeUpdate();
session.getTransaction().commit();
System.err.println(xx++ + "RIM LOOPED:" + row[1].toString());
});
try {
session.close();
System.out.println("Update customer ends. . . . . . . . . . .");
} catch (NullPointerException nullPointer) {
System.out.println("updateing data log data property ::<updateEntireContent()>: Customer session object is closed.Exception handled. . .>>" + nullPointer);
}

Related

DoNotForward Graph Api Event With Java

I have an application I am working on where a user will make an reservation for an office. Once the user makes it they are sent a calendar event via graph api so their Calendar reflects their reservation. I am trying to use the DoNotForward Boolean type to send in the singleValueExtendedProperties setting but nothing has worked.
Please Only answer using Java as the language. Thank you
**Note that I am sending the event and receiving it without any trouble until I try to add the DoNotForward. Below is a portion of the code that represents the Graph API Event.
Questions:
Has anyone configured an Event with the DoNoForward Option?
Can you provide me some guidance on what I am doing wrong?
Event event = new Event();
ItemBody eventBody = new ItemBody();
eventBody.contentType = BodyType.HTML;
eventBody.content = doc.html();
event.body = eventBody;
event.subject = "MyWorkSpot Reservation (" + environmentName + ") : " + buildingName + " Floor: " + floorName + " Seat: " + seatCode + " Time: " + reservationTime;
event.showAs = FreeBusyStatus.FREE;
event.isReminderOn = false;
event.reminderMinutesBeforeStart = 0;
event.isAllDay = true;
DateTimeTimeZone start = new DateTimeTimeZone();
start.dateTime = formattedResAllDayStartDate + "T00:00:00";
start.timeZone = "Eastern Standard Time";
event.start = start;
DateTimeTimeZone end = new DateTimeTimeZone();
end.dateTime = nextDay + "T00:00:00";
end.timeZone = "Eastern Standard Time";
event.end = end;
LinkedList<Attendee> attendeesList = new LinkedList<Attendee>();
Attendee attendees = new Attendee();
EmailAddress emailAddressEvent = new EmailAddress();
emailAddressEvent.address = recipientEmailAddress;
attendees.emailAddress = emailAddressEvent;
attendees.type = AttendeeType.REQUIRED;
attendeesList.add(attendees);
event.attendees = attendeesList;
SingleValueLegacyExtendedPropertyCollectionResponse singleValColRes = new SingleValueLegacyExtendedPropertyCollectionResponse();
SingleValueLegacyExtendedProperty singleValProp = new SingleValueLegacyExtendedProperty();
singleValProp.id = "Boolean {00020329-0000-0000-C000-000000000046} Name DoNotForward";
singleValProp.value = "true";
singleValProp.oDataType = "Boolean";
singleValColRes.value.add(0, singleValProp);
event.singleValueExtendedProperties = new SingleValueLegacyExtendedPropertyCollectionPage(singleValColRes, null);

nonuniqueobjectexception when Updating Database and Database creating new records instead of updating existing ones

I'm having an issue which I don't really understand, especially since I just started working with databases. I keep getting an nonuniqueobjectexception, when I try to save two instances of the project into the database. When I save the session for Project it will keep all the information and update the database accordingly but the Inspection table which is connected to the Project database will continue to add new entries. I tried multiple fixes of trying to throw exceptions but I can't figure out a way to save the information in the table without creating new entries in the instance table. Can anyone give me any advice on how to tackle this issue and where to look?
public static void editProject(Long warehouseID, Long managerID, Long supervisorID,
Long classID, Long projectItemID, Long statusID,
Long stageID, Long typeID, String scope, Map<String, String>params, Long inspectionTN)
throws ClassNotFoundException, ParseException
{
//Initialize Services
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
//Get essential project data
Warehouse warehouse = (Warehouse) ProjectObjectService.get(warehouseID, "Warehouse");
Person manager = (Person) ProjectObjectService.get(new Long(managerID), "Person");
Person supervisor = (Person) ProjectObjectService.get(new Long(supervisorID), "Person");
ProjectClass projectClass = (ProjectClass) ProjectObjectService.get(new Long(classID), "ProjectClass");
ProjectStatus status = (ProjectStatus) ProjectObjectService.get(new Long(statusID), "ProjectStatus");
ProjectItem item = (ProjectItem) ProjectObjectService.get(new Long(projectItemID), "ProjectItem");
ProjectStage stage = (ProjectStage) ProjectObjectService.get(stageID, "ProjectStage");
ProjectType pType = (ProjectType) ProjectObjectService.get(typeID, "ProjectType");
String mcsNumString = params.get("mcsNumber");
//ID's
String iIDString = params.get("inspectionID");
String closeoutIDString = params.get("closeoutID");
int mcsNum = -1;
Long iID = (long)-1;
Long closeoutID = (long)-1;
//Parse mcsNumber, change to -1 if it's not a number
try
{
mcsNum = Integer.parseInt(mcsNumString);
iID = Long.parseLong(iIDString);
closeoutID = Long.parseLong(closeoutIDString);
}catch(Exception e){}
//Inspections inspections=(Inspections) ProjectObjectService.get(iID, "Inspections");
int shouldInvoice = Integer.parseInt(params.get("shouldInvoice"));
int actualInvoice = Integer.parseInt(params.get("actualInvoice"));
String notes = params.get("notes");
//Additional fields
String zachNotes = params.get("zachUpdates");
String cost = params.get("cost");
String customerNumber = params.get("customerNumber");
//Parse change orders from strong
String changeOrderJsonString = params.get("coItems");
ChangeOrderService orderService = new ChangeOrderService();
HashSet<ChangeOrder> changeOrders = ChangeOrderService.getChangeOrdersFromString(changeOrderJsonString);
Date fsalvageDate = null;
Date finitiatedDate = null;
Date fsurvey = null;
Date fcostco = null;
Date fproposal = null;
Date fasBuilts = null;
Date fpunchList = null;
Date falarmHvac = null;
Date fverisae = null;
Date fcloseoutBook = null;
Date fcloseoutNotes = null;
Date fstart = null;
Date fscheduled = null;
Date factual = null;
Date fairGas = null;
Date fpermits = null;
Date permitApp = null;
Date fframing = null ;
Date fceiling = null;
Date froughMech = null;
Date froughElec= null;
Date froughPlumb = null;
Date fmechLightSmoke = null;
Date fmechFinal = null;
Date felecFinal = null;
Date fplumbFinal = null;
Date ffireMarshal = null;
Date fhealth = null;
Date fbuildFinal = null;
//assign values to dates, if they are not null
if (!(params.get("salvageDate")).isEmpty())
fsalvageDate = formatter.parse(params.get("salvageDate"));
if (!(params.get("initiated")).isEmpty())
finitiatedDate = formatter.parse(params.get("initiated"));
if (!(params.get("survey")).isEmpty())
fsurvey = formatter.parse(params.get("survey"));
if (!(params.get("costco")).isEmpty())
fcostco = formatter.parse(params.get("costco"));
if (!(params.get("proposal")).isEmpty())
fproposal = formatter.parse(params.get("proposal"));
if (!(params.get("asBuilts")).isEmpty())
fasBuilts = formatter.parse(params.get("asBuilts"));
if (!(params.get("punchList")).isEmpty())
fpunchList = formatter.parse(params.get("punchList"));
if (!(params.get("alarmHvac")).isEmpty())
falarmHvac = formatter.parse(params.get("alarmHvac"));
if (!params.get("verisae").isEmpty())
fverisae = formatter.parse(params.get("verisae"));
if (!params.get("startDate").isEmpty())
fstart = formatter.parse(params.get("startDate"));
if (!params.get("scheduledTurnover").isEmpty())
fscheduled = formatter.parse(params.get("scheduledTurnover"));
if (!params.get("actualTurnover").isEmpty())
factual = formatter.parse(params.get("actualTurnover"));
if (!params.get("airGas").isEmpty())
fairGas = formatter.parse(params.get("airGas"));
if (!params.get("permits").isEmpty())
fpermits = formatter.parse(params.get("permits"));
if (!params.get("permitApp").isEmpty())
permitApp = formatter.parse(params.get("permitApp"));
if(!params.get("framing").isEmpty())
fframing = formatter.parse(params.get("framing"));
if(!params.get("ceiling").isEmpty())
fceiling = formatter.parse(params.get("ceiling"));
if(!params.get("roughMech").isEmpty())
froughMech = formatter.parse(params.get("roughMech"));
if(!params.get("roughElec").isEmpty())
froughElec = formatter.parse(params.get("roughElec"));
if(!params.get("roughPlumb").isEmpty())
froughPlumb = formatter.parse(params.get("roughPlumb"));
if(!params.get("mechLightSmoke").isEmpty())
fmechLightSmoke = formatter.parse(params.get("mechLightSmoke"));
if(!params.get("mechFinal").isEmpty())
fmechFinal = formatter.parse(params.get("mechFinal"));
if(!params.get("elecFinal").isEmpty())
felecFinal = formatter.parse(params.get("elecFinal"));
if(!params.get("plumbFinal").isEmpty())
fplumbFinal = formatter.parse(params.get("plumbFinal"));
if(!params.get("fireMarshal").isEmpty())
ffireMarshal = formatter.parse(params.get("fireMarshal"));
if(!params.get("health").isEmpty())
fhealth = formatter.parse(params.get("health"));
if(!params.get("buildFinal").isEmpty())
fbuildFinal = formatter.parse(params.get("buildFinal"));
CloseoutDetails cd = null;
if(cd==null)
{
cd = new CloseoutDetails();
System.out.println("CloseoutDetails was empty in edit");
}
//Closeout fields
cd.setPunchList(fpunchList);
cd.setAsBuilts(fasBuilts);
cd.setAirGas(fairGas);
cd.setAlarmHvacForm(falarmHvac);
cd.setCloseoutBook(fcloseoutBook);
cd.setCloseoutNotes(fcloseoutNotes);
cd.setPermitsClosed(fpermits);
cd.setPunchList(fpunchList);
cd.setVerisaeShutdownReport(fverisae);
//need to add salvage amount and date
Inspections inspections = null;
//create inspections Object.
if(inspections==null)
{
inspections = new Inspections();
System.out.println("Inpsections was empty in edit");
}
//set inspection fields
inspections.setTicketNumber(inspectionTN);
inspections.setFraming(fframing);
inspections.setCeiling(fceiling);
inspections.setRoughin_Mechanical(froughMech);
inspections.setRoughin_Electric(froughElec);
inspections.setRoughin_Plumbing(froughPlumb);
inspections.setMechanicalLightSmoke(fmechLightSmoke);
inspections.setMechanical_Final(fmechFinal);
inspections.setElectrical_Final(felecFinal);
inspections.setPlumbing_Final(fplumbFinal);
inspections.setFire_Marshal(ffireMarshal);
inspections.setHealth(fhealth);
inspections.setBuilding_Final(fbuildFinal);
/*try{
inspections.setId(iID);
ProjectObjectService.editObject("Inspections",iID,inspections);
}catch (NonUniqueObjectException nuoe){}*/
//Create new project to replace the old one
Project p = new Project();
p.setMcsNumber(mcsNum);
p.setProjectClass(projectClass);
p.addProjectManager(manager);
p.addSupervisor(supervisor);
p.setStatus(status);
p.setWarehouse(warehouse);
p.setScope(scope);
p.setProjectItem(item);
p.setStage(stage);
p.setProjectInitiatedDate(finitiatedDate);
p.setSiteSurvey(fsurvey);
p.setCostcoDueDate(fcostco);
p.setProposalSubmitted(fproposal);
p.setScheduledStartDate(fstart);
p.setScheduledTurnover(fscheduled);
p.setActualTurnover(factual);
p.setShouldInvoice(shouldInvoice);
p.setInvoiced(actualInvoice);
p.setProjectNotes(notes);
p.setChangeOrders(changeOrders);
p.setProjectType(pType);
p.setZachUpdates(zachNotes);
p.setCost(cost);
p.setCustomerNumber(customerNumber);
p.setPermitApplication(permitApp);
p.setCloseoutDetails(cd);
p.setInspections(inspections);
//Replace the old project with the new project.
Long id = Long.parseLong(params.get("projectID"));
//ProjectObjectService.editObject("Project", id,p);
long[] iDs = {iID,/*closeoutID,*/id} ;
String[] domains = {"Inspections",/*"CloseoutDetails",*/"Project" };
ProjectObject[] objects ={inspections, /*cd,*/ p};
inspections.setId(iID);
ProjectObjectService.editObject("Project",id,p);
}
public static Object get(Long id, String domain) throws ClassNotFoundException
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
//Get the Class from parsing the "domain" string.
Class c = Class.forName("projectObjects."+domain);
//Get object from database that matches the id
Object o = session.get(c, id);
tx.commit();
return o;
}

How to repeat recurring invoice by x amount of days and then it stops

I am trying to update my ( Recurring Invoice ) setup but i am running into a little bit of trouble.
I am trying to make it where i do this...
enter date ( which is the starting date of the recurrence )
enter how it will recur ( weekly.bi-weekly and so on..)
this is where the issue starts for me.... ( enter how many times it will recur for and then stop the invoice recurring)
.. thanks in advance
<?php require 'initapp.php'; $self='invoice-recurring.php'; $rself='all-recurring-invoice.php'; if (isset($_POST['submit'])){
$cid = _post('client');
if ($cid=='' OR $cid=='0'){
conf($self,'e','Client Name is Required.');
}
$idate = _post('date');
$date=date("Y-m-d", strtotime($idate));
if ($date==''){
conf($self,'e','Date is Required.');
}
$item = _post('item');
if ($item==''){
conf($self,'e','Item Name is Required.');
}
$note = _post('note');
$note=html_entity_decode($note);
$recurring = _post('frequency');
if ($recurring==''){
conf($self,'e','Frequency is Required.');
} //starts added on 3-7-2015 //$occurance = _post('occurance'); // if ($occurance==''){ // conf($self,'e','Occurance is Required.'); // } //stops
$price= _post('price');
if ($price==''){
conf($self,'e','Price is Required.');
}
$discount=_post('discount');
$disc_calculate=($discount*$price/100);
$tax=_post('tax'); if ($tax!='0'){ $tax = ORM::for_table('taxes')->find_one($tax); $trate = $tax['rate']; $tname = $tax['name']; $ttype = $tax['type']; if ($ttype=='Excluded'){ $tval = ($price*$trate)/100; $intotal = $price+$tval;
}
else {
$tval = ($price*$trate)/100;
$intotal = $price-$tval;
}
}
else{
$intotal=$price;
$tval='0';
$tname='None';
}
$created = $date;
$add_days =$recurring;
$paiddate = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //add or delete * $occurance added on 3-7-2015 //$emailnotify='Yes'; $emailnotify = $aclient->emailnotify;//added on 2-25-2015
$intotal=$intotal-$disc_calculate; $paymentmethod=_post('paymentmethod');
$d = ORM::for_table('invoices')->create();
$d->userid = $cid;
$d->iteam = $item;
$d->created = $date;
$d->duedate = $date;
$d->nextduedate=$paiddate;
$d->datepaid=$date;
$d->subtotal = $price;
$d->total = $intotal;
$d->discount = $discount;
$d->paymentmethod=$paymentmethod;
$d->note = $note;
$d->tax=$tval;
$d->taxname=$tname;
$d->status = 'Unpaid';
$d->recurring = $recurring;
//$d->occurance = $occurance;//added on 3-7-2015
$d->save();
$invoiceid= $d->id();
if ($emailnotify=='Yes'){
$sysEmail=appconfig('Email');
$sysCompany=appconfig('CompanyName');
$sysUrl= appconfig('sysUrl');
$d= ORM::for_table('email_templates')->where('tplname', 'Customer Invoice Created')->find_one();
$cl = ORM::for_table('accounts')->find_one($cid);
$name = $cl['name'];
$email = $cl['email'];
$template = $d['message'];
$subject = $d['subject'];
$send = $d['send'];
$data = array('name' => $name,
'logo'=> '<img width="61" height="76" border="0" src="'.$sysUrl.'/assets/uploads/logo.jpg">',
'business_name'=> $sysCompany,
'invoice_id'=> $invoiceid,
'invoice_item'=> $item,
'invoice_amount'=> $intotal,
'sys_url' => $sysUrl
);
$message = _render($template,$data);
$mail_subject = _render($subject,$data);
$body = $message;
if ($send=='1'){
$smtp=ORM::for_table('smtp_setting')->find_one('1');
$smtp_status=$smtp['status'];
if($smtp_status!='1'){
require ('../lib/pnp/email/class.phpmailer.php') ;
$mail = new PHPMailer();
$mail->SetFrom($sysEmail, $sysCompany);
$mail->AddReplyTo($sysEmail, $sysCompany);
$mail->AddAddress($email, $name);
$mail->Subject = $mail_subject;
$mail->MsgHTML($body);
$mail->Send();
}else{
require ('../lib/plugin/PHPMailer/PHPMailerAutoload.php');
$host_name=$smtp['host_name'];
$username=$smtp['username'];
$password=$smtp['password'];
$port=$smtp['port'];
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = "$host_name"; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = "$username"; // SMTP username
$mail->Password ="$password"; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = "$port";
$mail->SetFrom($sysEmail, $sysCompany);
$mail->AddReplyTo($sysEmail, $sysCompany);
$mail->AddAddress($email, $name);
$mail->Subject = $mail_subject;
$mail->MsgHTML($body);
$mail->Send();
}
}
}
conf("invoice-manage.php?_inid=$invoiceid",'s','Recurring Invoice Add Successfully'); } conf($self,'e','Invoice does not Create Successfully'); ?>
Most likely you need the time and/or lenght/duration of the event. You can use cron for it or send me a PM I have written a php script.

How to get "supportedControl" from LDAP with com.novell.ldap

I want to get value from control oid from LDAP: For example when I use Linux ldapsearch:
ldapsearch -H ldap://host:port -x -wsecret -D "cn=manager,managedElementId=HSS1"
-b "dn" "objectClass=ConfigOAM" -E"1.3.6.1.4.1.637.81.2.10.10"
I get results:
...
**control: 1.3.6.1.4.1.637.81.2.10.10 false AgEB**
objectClass: top
objectClass: ConfigOAM
confOAMId: 1
...
My java code looks:
LDAPConnection connection = new LDAPConnection();
connection.connect(hostName, port);
connection.bind(LDAPConnection.LDAP_V3, userDN, password);
String returnedAttributes[] = {"+", "*"};
boolean attributeOnly = false;
String oid;
LDAPSearchResults results = connection.search("", LDAPConnection.SCOPE_BASE, "(objectClass=*)", returnedAttributes, attributeOnly);
LDAPEntry entry = results.next();
System.out.println("\n" + entry.getDN());
System.out.println(" Attributes: ");
LDAPAttributeSet attributeSet = entry.getAttributeSet();
Iterator allAttributes = attributeSet.iterator();
while(allAttributes.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute)allAttributes.next();
String attrName = attribute.getName();
System.out.println(" " + attrName);
Enumeration allValues = attribute.getStringValues();
while(allValues.hasMoreElements()) {
oid = (String) allValues.nextElement();
if ( (attrName.equalsIgnoreCase("supportedExtension")) || (attrName.equalsIgnoreCase("supportedControl"))) {
System.out.println(" " + oid);
}
}
}
and the result is:
...
supportedControl
2.16.840.1.113730.3.4.2
1.2.840.113556.1.4.319
1.2.826.0.1.3344810.2.3
1.3.6.1.1.12
1.3.6.1.4.1.637.81.2.10.11
**1.3.6.1.4.1.637.81.2.10.10**
1.3.6.1.4.1.637.81.2.10.9
1.3.6.1.4.1.637.81.2.10.6
...
Please suggest me or advice how can I get the additional value "false AgEB" in java as I get it in ldapsearch?
You would need to add the control to the search request and be able to interpret the response.
There are soem examples available:
http://www.novell.com/documentation/developer/samplecode/jldap_sample/
-jim
Thank you for your answer :)
I made something like this from samples available on this site and from others soruces:
lc.connect( ldapHost, ldapPort );
lc.bind( ldapVersion, loginDN, password.getBytes("UTF8"));
LDAPControl ldapCtrl = new LDAPControl("1.3.6.1.4.1.637.81.2.10.10", false, null);
LDAPSearchConstraints cons = lc.getSearchConstraints();
cons.setControls( ldapCtrl );
lc.setConstraints(cons);
LDAPSearchResults searchResults = lc.search("",LDAPConnection.SCOPE_BASE, "(objectclass=*)", returnedAttributes,attributeOnly , cons);
LDAPControl[] controls = searchResults.getResponseControls();
but my "controls" varaible is always null, even if supportedControls are listed
LDAPEntry entry1 = searchResults.next();
System.out.println("\n" + entry1.getDN());
System.out.println(" Attributes: ");
LDAPAttributeSet attributeSet1 = entry1.getAttributeSet();
Iterator allAttributes1 = attributeSet1.iterator();
while(allAttributes1.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute)allAttributes1.next();
String attrName = attribute.getName();
System.out.println(" " + attrName);
Enumeration allValues1 = attribute.getStringValues();
while(allValues1.hasMoreElements()) {
oid = (String) allValues1.nextElement();
if ( (attrName.equalsIgnoreCase("supportedExtension")) || (attrName.equalsIgnoreCase("supportedControl"))) {
System.out.println(" " + oid);
}
}
}
Maybe the searchResults options are wrong?

Is there a way to save session keys into mysql 5.5?

A company that I'm working now is going to use DB sessions to organize their servers. I have no choice to refuse it :(
The sample php code they were gonna use was
sessioninit.php
<?
/* ------------------------------------------------------------------------
* Create a new database in MySQL called "sessions" like so:
*
* CREATE TABLE ucnovel_session (
* sesskey char(32) not null,
* expiry int(11) unsigned not null,
* value text not null,
* PRIMARY KEY (sesskey)
* );
*/
$SESS_DBH = "";
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime");
function sess_open($save_path, $session_name)
{
global $SESS_DBH;
$sv = "192.168.0.3";
$SESS_DBH = mysql_pconnect($sv, "ucnovel", "비번") or die("Can't connect to SQL Server");
mysql_select_db("hotdog", $SESS_DBH) or die("Can't connect to SQL Server");
return true;
}
function sess_close()
{
return true;
}
function sess_read($key)
{
global $SESS_DBH, $SESS_LIFE;
//echo $key;
$qry = "SELECT value FROM ucnovel_session WHERE sesskey = '$key' AND expiry > " . time();
$qid = mysql_query($qry, $SESS_DBH);
if (list($value) = mysql_fetch_row($qid)) {
return $value;
}
return false;
}
function sess_write($key, $val)
{
global $SESS_DBH, $SESS_LIFE;
$expiry = time() + $SESS_LIFE;
$value = addslashes($val);
$qry = "SELECT COUNT(*) FROM ucnovel_session WHERE sesskey='$key'";
$qid = mysql_fetch_array(mysql_query($qry, $SESS_DBH));
if($qid[0]>0) {
$qry = "UPDATE ucnovel_session SET expiry = $expiry, value = '$value' WHERE sesskey = '$key'"; // AND expiry > " . time();
$qid = mysql_query($qry, $SESS_DBH);
} else {
$qry = "INSERT INTO ucnovel_session SET expiry = $expiry, value = '$value', sesskey = '$key'";
$qid = mysql_query($qry, $SESS_DBH);
}
return $qid;
}
function sess_destroy($key)
{
global $SESS_DBH;
$qry = "DELETE FROM ucnovel_session WHERE sesskey = '$key'";
$qid = mysql_query($qry, $SESS_DBH);
return $qid;
}
function sess_gc($maxlifetime)
{
global $SESS_DBH;
$qry = "DELETE FROM ucnovel_session WHERE expiry < " . time();
$qid = mysql_query($qry, $SESS_DBH);
return mysql_affected_rows($SESS_DBH);
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_set_cookie_params(0, "/", "ucnovel.com", false, false);
session_start();
?>
sessiontest.php
<?
include "sessioninit.php";
$old = $_COOKIE[test_sess2];
$new = rand()%10000;
$_COOKIE[test_sess2] = $new;
setcookie("test_sess2", $new);
echo "OLD ".$old."<br>"."NEW ".$new;
$old = $_SESSION[test_sess];
$new = rand()%10000;
$_SESSION[test_sess] = $new;
$_SESSION[test_ip] = $REMOTE_ADDR;
echo "<br><br>OLD ".$old."<br>"."NEW ".$new;
?>
I understand that they override the session handler and customized it. But I can't find any references on how to do it in Java.
Some people says that overriding HttpSession is a way. But I still can't understand how to do this. Also, I don't know if DTOs will save in the DB :S
I'm using Spring 3.1 right now, and the server is MySQL 5.5
Is there any samples that I can understand how to do it? or maybe a plugin that helps it?

Categories

Resources