how to create active directory users with accountExpires attribute from java - java

I want to create an AD user with accountExpires attribute. I am doing like this
public boolean addUser(
String firstName,
String lastName,
String userName,
String password,
String organisationUnit) throws NamingException {
if (findUser(userName, firstName, lastName, organisationUnit)) {
return false;
} else {
// Create a container set of attributes
BasicAttributes container = new BasicAttributes();
// Create the objectclass to add
Attribute objClasses = new BasicAttribute("objectClass");
objClasses.add("top");
objClasses.add("person");
objClasses.add("organizationalPerson");
objClasses.add("user");
// Assign the username, first name, and last name
String cnValue = new StringBuffer(firstName).append(" ").append(lastName).toString();
Attribute cn = new BasicAttribute("cn", cnValue);
Attribute sAMAccountName = new BasicAttribute("sAMAccountName", userName);
Attribute mac = new BasicAttribute("msNPCallingStationID", "ab-ab-ab-b7-6t");
Attribute principalName = new BasicAttribute("userPrincipalName", userName + "#atamunet.com");
Attribute givenName = new BasicAttribute("givenName", firstName);
Attribute sn = new BasicAttribute("sn", lastName);
Attribute uid = new BasicAttribute("uid", userName);
Attribute fullName = new BasicAttribute("displayName", "fullName");
Attribute gender = new BasicAttribute("initials", "gender");
Attribute dob = new BasicAttribute("description", "dob");
Attribute FatherName = new BasicAttribute("physicalDeliveryOfficeName", "FatherName");
Attribute Email = new BasicAttribute("mail", "Email");
Attribute mobile = new BasicAttribute("mobile", "mobile");
Attribute department = new BasicAttribute("department", "department");
Attribute HallName = new BasicAttribute("streetAddress", "HallName");
Attribute FacultyName = new BasicAttribute("company", "FacultyName");
Attribute CourseName = new BasicAttribute("title", "CourseName");
Attribute accountExpires = new BasicAttribute("accountExpires", new Date());
//some useful constants from lmaccess.h
int UF_ACCOUNTENABLE = 0x0001;
//int UF_ACCOUNTDISABLE = 0x0002;
int UF_PASSWD_NOTREQD = 0x0020;
int UF_PASSWD_CANT_CHANGE = 0x0040;
int UF_NORMAL_ACCOUNT = 0x0200;
int UF_DONT_EXPIRE_PASSWD = 0x10000;
//int UF_PASSWORD_EXPIRED = 0x800000;
Attribute enabled = new BasicAttribute("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_DONT_EXPIRE_PASSWD + UF_ACCOUNTENABLE));
// Add password
Attribute userPassword = new BasicAttribute("userpassword", password);
// Add these to the container
container.put(objClasses);
container.put(sAMAccountName);
container.put(principalName);
container.put(cn);
container.put(sn);
container.put(givenName);
container.put(uid);
container.put(userPassword);
container.put(mac);
container.put(gender);
container.put(dob);
container.put(FatherName);
container.put(Email);
container.put(mobile);
container.put(department);
container.put(HallName);
container.put(FacultyName);
container.put(CourseName);
container.put(fullName);
container.put(enabled);
container.put(accountExpires);
// Create the entry
try {
ctx.createSubcontext(getUserDN(cnValue, organisationUnit), container);
return true;
} catch (Exception e) {
System.out.println(e.getMessage() + "add");
return false;
}
}
}
How can I add user with accountExpires attribute. Is there anybody can help me. Without this line
Attribute accountExpires = new BasicAttribute("accountExpires", new Date());
Everything goes fine but I want the expiry date as well.

You are setting the attribute to the current date, but this is not correct.
First of all because the attribute is an interval of 100-nanoseconds, according to the Microsoft documentation and this.
What you have to do is set your desired expiration date, then convert to the value of 100-nanoseconds, that in Java are represented by long.
Here is a trivial code example that show you how to do it with Java 8:
UPDATED:
Calendar cal = Calendar.getInstance();
// First you need to get the start date
// according to the documentation it is
// the 1th January of 1601
cal.set(1601, Calendar.JANUARY, 1);
// print the current date
System.out.println(String.format("Start date: %tc", cal));
Date startDate = cal.getTime();
// Reset the calendar to today
cal.set(Calendar.MILLISECOND, System.currentTimeMillis());
// Set the desired expiration date
// here is 1 year in the future
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
// print the current date
System.out.println(String.format("Expire date: %tc", cal));
// Get the date from Calendar
Date expireDate = cal.getTime();
// Create an interval from the startDate to the expireDate
// and convert it to nanoseconds interval
long expirationInterval = TimeUnit.NANOSECONDS.toNanos(expireDate.getTime()-startDate.getTime());
// set the attribute value
Attribute accountExpires = new BasicAttribute("accountExpires", expirationInterval);

Thanks for your help what gave me the idea and this code worked for me
/**
* Difference between Filetime epoch and Unix epoch (in ms).
*/
private static final long FILETIME_EPOCH_DIFF = 11644473600000L;
/**
* One millisecond expressed in units of 100s of nanoseconds.
*/
private static final long FILETIME_ONE_MILLISECOND = 10 * 1000;
public static long filetimeToMillis(final long filetime) {
return (filetime / FILETIME_ONE_MILLISECOND) - FILETIME_EPOCH_DIFF;
}
public static long millisToFiletime(final long millis) {
return (millis + FILETIME_EPOCH_DIFF) * FILETIME_ONE_MILLISECOND;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "01-07-2017 10:20:56";
Date date = sdf.parse(dateInString);
final long dd = date.getTime();
Attribute accountExpires = new BasicAttribute("accountExpires", Long.toString(millisToFiletime(dd)));

Related

Divide Subject, From, and To values from headers

I'm fetching the messages from authorized email but the problem is the separation of Subject, From, and To values from headers in java, I succeed in that below code is working fine but it is taking more time for separation, I have gone through so much Gmail API documentation but I didn't get the solution.
ListMessagesResponse listResponse = service.users().messages().list(user).setMaxResults(10L)
.setLabelIds(labelidlist).setQ(query).execute();
List<Message> listofmesssages = listResponse.getMessages();
HashMap<String, Object> msgsMap;
List messageslist = new ArrayList();
for (Message message : listofmesssages) {
Message fullmessage = service.users().messages().get("me", message.getId()).setFormat("full").execute();
msgsMap = new LinkedHashMap<String, Object>();
/*Adding threadid for threadid is required when delete operation has happen*/
msgsMap.put("threadid", message.getThreadId());
List<MessagePartHeader> headers = fullmessage.getPayload().getHeaders();
if (!headers.isEmpty()) {
for (MessagePartHeader header : headers) {
String name = header.getName();
msgsMap.put("msgid", message.getId());
if (name.equalsIgnoreCase("Subject")) {
subject = header.getValue();
msgsMap.put("subject", subject);
} else if (name.equalsIgnoreCase("From")) {
from = header.getValue().split("<")[0];
msgsMap.put("from", from);
} else if (name.equalsIgnoreCase("To")) {
to = header.getValue().split(" ")[0];
msgsMap.put("to", to);
} else if (name.equalsIgnoreCase("Date")) {
String date = header.getValue();
java.util.Date fecha = new java.util.Date(date);
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date1;
date1 = (Date) formatter.parse(fecha.toString());
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/"
+ cal.get(Calendar.YEAR);
msgsMap.put("date", formatedDate);
}
}
}
messageslist.add(msgsMap);
}
return messageslist;
If you look at the message resource JSON, you can see that headers is an array of objects that contain properties name and value. There is no property key called To, or Subject. That's the reason the library you're using has no methods called getTo, or getSubject.
This makes sense, since headers might not always be the same ones.
Because of this, you cannot specifically fetch a certain header name.
Reference:
Users.messages
getHeaders()

Biweekly/google-rfc-2445 RRule different behaviour based on start date

Different behaviour of RRULE based on start time :
Hi, I am currently trying to write a cron to rrule convertor and encountered some issues with some particular rules.
For the following rule :
"FREQ=YEARLY;BYMONTH=1,2,3,4,5,6,7,8,9,10,11,12;BYMONTHDAY=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYHOUR=0,10,20;BYMINUTE=0"
The behaviour of the dates iterator iss different depending on what the start time specified is :
final String rule2 = "FREQ=YEARLY;BYMONTH=1,2,3,4,5,6,7,8,9,10,11,12;BYMONTHDAY=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYHOUR=0,10,20;BYMINUTE=0";
final Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse("2019-10-01");
final Date startDate2 = new SimpleDateFormat("yyyy-MM-dd").parse("2019-12-01");
System.out.println("Biweekly Rule Date 1");
final List<Date> biweeklyStartDate1 = biweeklyDates(rule2, startDate, 100);
System.out.println("Biweekly Rule Date 1 Result Count " + biweeklyStartDate1.size());
System.out.println("Biweekly Rule Date 2");
final List<Date> biweeklyStartDate2 = biweeklyDates(rule2, startDate2, 100);
System.out.println("Biweekly Rule Date 2 Result Count " + biweeklyStartDate2.size());
private static List<Date> biweeklyDates(final String rule, final Date date, final int limit) {
final RecurrenceRuleScribe scribe = new RecurrenceRuleScribe();
final ParseContext context = new ParseContext();
context.setVersion(ICalVersion.V2_0);
final RecurrenceRule recurrenceRule = scribe.parseText("RRULE:" + rule,null, new ICalParameters(), context);
final DateIterator iterator = recurrenceRule.getDateIterator(date, TimeZone.getTimeZone("GMT"));
final List<Date> values = new ArrayList<>();
while (iterator.hasNext()) {
final Date next = iterator.next();
values.add(next);
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(next));
if (values.size() >= limit) {
break;
}
}
return values;
}
In this example I try to retrieve a 100 occurences using the same rule. The occurences returned differ based on start time specified.
The first date would return the expected 100 results, the second one would return a single invalid occurence, which seem to be the start date.
It seems to be caused by last month of the year, whn specifying another date with December, the same return seems to be returned.
Google-rfc-2445 has the same behaviour but ical4j and some other rrule evaluators from other languages were able to produce the expected results.

How add LocalDate list to myList in Java

How add Local date list to myList in java
Please find the below code and check where I made a mistake to add dates to myList
I declare List as Local date now need to convert to myModel
error occurs in // myList.addAll(employeeReportsModel.getReportFromDt());
#RequestMapping(value = "/getMusterRollDateBased", method = RequestMethod.GET)
public ModelAndView getMusterRollDateBased(EmployeeReportsModel employeeReportsModel) {
ModelAndView mv = new ModelAndView();
String tablePrefix = "at_hr_logs_";
try {
System.out.println("refort from date.."+employeeReportsModel.getReportFromDt());
System.out.println("refort to date.."+employeeReportsModel.getReportToDt());
String fromdate = employeeReportsModel.getReportFromDt();
String todate = employeeReportsModel.getReportToDt();
Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(fromdate);
Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(todate);
System.out.println(date1 + "-----" + date2);
// parse the date into another format
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
String fromdate1 = sdfDestination.format(date1);
String todate1 = sdfDestination.format(date2);
employeeReportsModel.setReportFromDt(fromdate1);
// get dates between two dates
String startString = fromdate1;
String endString = todate1;
LocalDate incrementingDate = LocalDate.parse(startString);
LocalDate endDate = LocalDate.parse(endString);
List<LocalDate> allDates = new ArrayList<>();
while (!incrementingDate.isAfter(endDate)) {
allDates.add(incrementingDate);
incrementingDate = incrementingDate.plusDays(1);
}
System.err.println(allDates);
List<EmployeeReportsModel> myList = null;
mv.addObject("allDates",allDates);
for (LocalDate date : allDates) {
//System.out.println();
System.out.println("dates is..." + date);
employeeReportsModel.setReportFromDt(date.toString());
String[] parts = date.toString().split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
System.out.println("year ....." + part1);
System.out.println("Month....." + part2);
String tableName = tablePrefix + part1 + '_' + part2;
System.out.println("hks table name is.." + tableName);
employeeReportsModel.setDynamicTableName(tableName);
myList.addAll(employeeReportsModel.getReportFromDt());
//here we get a problem to add
}
} catch (Exception e) {
e.printStackTrace();
}
mv.setViewName("/" + moduleName + "/employeeMusterRollBasedOnDateInter");
return mv;
}
First thing is that you call myList.addAll() on a null object. Your list should be initialized properly like myList = new ArrayList().
Then you are trying to store a String type in your list which expects an object of type EmployeeReportsModel.
So you either change your myList to look like List<String> or change your return type of the getReportFromDt() method.
I suggest you to rethink your current code.
Currently you are basically doing the following:
get a local date > create a String out of it > store it with setReportFromDt > call getReportFromDt > try to store LocalDate in string form into a List of type EmployeeReportsModel

SimpleDateFormat returning wrong time value ( 00:00:00) [duplicate]

This question already has answers here:
JDBC ResultSet getDate losing precision
(3 answers)
Closed 7 years ago.
I'm having an issue using the SimpleDateFormat component.
I have a date stored in my database as a DateTime, and i would like to get the value of this datetime in my application.
I'm using a SimpleDateFormat in order to do this, but the problem is that it always returns me 00:00:00 as Time. The date is well returned though.
So i'm doing as follows :
private final static SimpleDateFormat ft = new SimpleDateFormat("dd.MM - HH:mm:ss");
public Push(int idp, String titrefr, String contenufr, String titreuk, String contenuuk, String pays, String marche, String type, Date datep, int isImportant, String image) {
super();
this.idp = idp;
this.titrefr = titrefr;
this.contenufr= contenufr;
this.titreuk = titreuk;
this.contenuuk= contenuuk;
this.pays = pays;
this.marche = marche;
this.type = type;
this.datep = ft.format(datep);
this.isImportant = isImportant;
this.image = image;
System.out.println(this.datep);
}
Here is the method where I get the date :
Modele.java:
public List<Push> getPushfr() {
String queryPushfr = "SELECT idp,titrefr,contenufr,titreuk,contenuuk,pays,marche,type,datep,isImportant, image FROM push WHERE datep > DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY datep DESC;";
try {
connexion = ConnexionBDD.getConnexion();
PreparedStatement pstmt = connexion.prepareStatement(queryPushfr);
resultat = pstmt.executeQuery(queryPushfr);
while (resultat.next()) {
int idp = resultat.getInt("idp");
String titrefr = resultat.getString("titrefr");
String contenufr = resultat.getString("contenufr");
String titreuk = resultat.getString("titreuk");
String contenuuk = resultat.getString("contenuuk");
String pays = resultat.getString("pays");
String marche = resultat.getString("marche");
String type = resultat.getString("type");
Date datep = resultat.getDate("datep");
int isImportant = resultat.getInt("isImportant");
String image = resultat.getString("image");
this.pushfr.add(
new Push(idp, titrefr, contenufr, titreuk, contenuuk, pays, marche, type, datep, isImportant,image));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
return pushfr;
}
In my database the date is :
2015-09-03 16:13:09
The output i get from my System.out.println(datep) is
03.09 - 00:00:00
I've no idea why it's not returning me the time properly..
If you are using java.sql.Date you will lose information about the time.
java.sql.Date corresponds to SQL DATE which means it stores years,
months and days while hour, minute, second and millisecond are
ignored.
Change code to:
public List<Push> getPushfr() {
String queryPushfr = "SELECT idp,titrefr,contenufr,titreuk,contenuuk,pays,marche,type,datep,isImportant, image FROM push WHERE datep > DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY datep DESC;";
try {
connexion = ConnexionBDD.getConnexion();
PreparedStatement pstmt = connexion.prepareStatement(queryPushfr);
resultat = pstmt.executeQuery(queryPushfr);
while (resultat.next()) {
int idp = resultat.getInt("idp");
String titrefr = resultat.getString("titrefr");
String contenufr = resultat.getString("contenufr");
String titreuk = resultat.getString("titreuk");
String contenuuk = resultat.getString("contenuuk");
String pays = resultat.getString("pays");
String marche = resultat.getString("marche");
String type = resultat.getString("type");
Date datep = resultat.getTimestamp("datep");
int isImportant = resultat.getInt("isImportant");
String image = resultat.getString("image");
this.pushfr.add(
new Push(idp, titrefr, contenufr, titreuk, contenuuk, pays, marche, type, datep, isImportant,image));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
return pushfr;
}
PD:I recomend you to store the TimeStamt in milisecons in the database.
If you are loading results from a ResultSet, use getTimestamp method, not getDate. See JDBC ResultSet getDate losing precision

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

Categories

Resources