b9906e912aaae9b4e2e5e266e73573b931851a7d
[gpl/argeo-suite.git] / org.argeo.suite.workbench.rap / src / org / argeo / suite / workbench / commands / ImportEntities.java
1 package org.argeo.suite.workbench.commands;
2
3 import static org.argeo.eclipse.ui.EclipseUiUtils.notEmpty;
4 import static org.argeo.suite.workbench.commands.JxlUtils.getStringValue;
5
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.util.Arrays;
13 import java.util.Collections;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.UUID;
18
19 import javax.jcr.Node;
20 import javax.jcr.Property;
21 import javax.jcr.Repository;
22 import javax.jcr.RepositoryException;
23 import javax.jcr.Session;
24
25 import org.apache.commons.io.IOUtils;
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28 import org.argeo.activities.ActivitiesNames;
29 import org.argeo.connect.ConnectConstants;
30 import org.argeo.connect.ConnectNames;
31 import org.argeo.connect.resources.ResourcesNames;
32 import org.argeo.connect.resources.ResourcesService;
33 import org.argeo.connect.util.ConnectJcrUtils;
34 import org.argeo.eclipse.ui.EclipseUiUtils;
35 import org.argeo.jcr.JcrUtils;
36 import org.argeo.people.ContactValueCatalogs;
37 import org.argeo.people.PeopleException;
38 import org.argeo.people.PeopleNames;
39 import org.argeo.people.PeopleService;
40 import org.argeo.people.PeopleTypes;
41 import org.argeo.people.util.PeopleJcrUtils;
42 import org.argeo.people.util.PersonJcrUtils;
43 import org.argeo.suite.workbench.SuiteWorkbenchException;
44 import org.argeo.suite.workbench.AsUiPlugin;
45 import org.eclipse.core.commands.AbstractHandler;
46 import org.eclipse.core.commands.ExecutionEvent;
47 import org.eclipse.core.commands.ExecutionException;
48 import org.eclipse.jface.wizard.Wizard;
49 import org.eclipse.jface.wizard.WizardDialog;
50 import org.eclipse.jface.wizard.WizardPage;
51 import org.eclipse.rap.fileupload.FileDetails;
52 import org.eclipse.rap.fileupload.FileUploadEvent;
53 import org.eclipse.rap.fileupload.FileUploadHandler;
54 import org.eclipse.rap.fileupload.FileUploadListener;
55 import org.eclipse.rap.fileupload.FileUploadReceiver;
56 import org.eclipse.rap.rwt.service.ServerPushSession;
57 import org.eclipse.rap.rwt.widgets.FileUpload;
58 import org.eclipse.swt.SWT;
59 import org.eclipse.swt.events.ModifyEvent;
60 import org.eclipse.swt.events.ModifyListener;
61 import org.eclipse.swt.events.SelectionAdapter;
62 import org.eclipse.swt.events.SelectionEvent;
63 import org.eclipse.swt.layout.GridData;
64 import org.eclipse.swt.layout.GridLayout;
65 import org.eclipse.swt.widgets.Combo;
66 import org.eclipse.swt.widgets.Composite;
67 import org.eclipse.swt.widgets.Control;
68 import org.eclipse.swt.widgets.Label;
69 import org.eclipse.swt.widgets.Shell;
70 import org.eclipse.ui.handlers.HandlerUtil;
71
72 import jxl.Sheet;
73 import jxl.Workbook;
74
75 /** Open a one page wizard to import an EXCEL 2003 legacy organisation file */
76 public class ImportEntities extends AbstractHandler implements PeopleNames {
77 private final static Log log = LogFactory.getLog(ImportEntities.class);
78
79 public final static String ID = AsUiPlugin.PLUGIN_ID + ".importEntities";
80
81 // public final static String PARAM_NODE_TYPE = "param.nodeType";
82
83 private static final Map<String, String> KNOWN_TEMPLATES;
84 static {
85 Map<String, String> tmpMap = new HashMap<String, String>();
86 tmpMap.put("Organisations", PeopleTypes.PEOPLE_ORG);
87 tmpMap.put("Persons", PeopleTypes.PEOPLE_PERSON);
88 KNOWN_TEMPLATES = Collections.unmodifiableMap(tmpMap);
89 }
90
91 // TODO make this configurable
92 private final static String IMPORT_ENCODING = "ISO-8859-1";// "UTF-8";
93
94 /* DEPENDENCY INJECTION */
95 private Repository repository;
96 private ResourcesService resourcesService;
97 private PeopleService peopleService;
98
99 public Object execute(final ExecutionEvent event) throws ExecutionException {
100 // String jcrId = event.getParameter(PARAM_NODE_TYPE);
101
102 Wizard wizard = new ImportMappingFileWizard(HandlerUtil.getActiveShell(event),
103 "Upload legacy contact via Excel file import");
104 WizardDialog dialog = new WizardDialog(HandlerUtil.getActiveShell(event), wizard);
105 dialog.open();
106 return null;
107 }
108
109 /** One page wizard to import a EXCEL 2003 Mapping files */
110 private class ImportMappingFileWizard extends Wizard {
111
112 // Various UI Objects
113 private UserInputPage userInputPage;
114 private Combo resourceTypeCombo;
115
116 // File upload
117 private FileUpload fileUpload;
118 private Label fileNameLabel;
119 private ServerPushSession pushSession;
120 private File file;
121
122 public ImportMappingFileWizard(Shell parentShell, String title) {
123 setWindowTitle(title);
124 }
125
126 @Override
127 public void addPages() {
128 try {
129 userInputPage = new UserInputPage("User input page");
130 addPage(userInputPage);
131 } catch (Exception e) {
132 throw new SuiteWorkbenchException("Cannot add page to wizard", e);
133 }
134 }
135
136 /** Performs the real import. */
137 @Override
138 public boolean performFinish() {
139 String templateName = resourceTypeCombo.getItem(resourceTypeCombo.getSelectionIndex());
140 String type = KNOWN_TEMPLATES.get(templateName);
141 InputStream in = null;
142 try {
143 in = new FileInputStream(file);
144 if (PeopleTypes.PEOPLE_ORG.equals(type))
145 importDefaultOrgFile(in);
146 else if (PeopleTypes.PEOPLE_PERSON.equals(type))
147 importDefaultPersonFile(in);
148 } catch (IOException e) {
149 throw new SuiteWorkbenchException("Cannot import mapping file", e);
150 } finally {
151 IOUtils.closeQuietly(in);
152 }
153 return true;
154 }
155
156 @Override
157 public boolean performCancel() {
158 return true;
159 }
160
161 @Override
162 public boolean canFinish() {
163 if (resourceTypeCombo.getSelectionIndex() < 0) {
164 userInputPage.setErrorMessage("Please choose an entity type");
165 return false;
166 } else if (file == null) {
167 userInputPage.setErrorMessage("Please upload a file");
168 return false;
169 } else {
170 userInputPage.setErrorMessage(null);
171 return true;
172 }
173 }
174
175 private class UserInputPage extends WizardPage {
176 private static final long serialVersionUID = 1L;
177
178 public UserInputPage(String pageName) {
179 super(pageName);
180 setTitle("Upload an Excel 2003 file (.xls)");
181 }
182
183 public void createControl(Composite parent) {
184 parent.setLayout(new GridLayout(1, false));
185 Composite composite = new Composite(parent, SWT.NONE);
186 composite.setLayout(new GridLayout(2, false));
187 composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
188
189 // Import type
190 resourceTypeCombo = createLC(composite, "Type");
191 resourceTypeCombo.addModifyListener(new ModifyListener() {
192 private static final long serialVersionUID = 1L;
193
194 @Override
195 public void modifyText(ModifyEvent event) {
196 getWizard().getContainer().updateButtons();
197 }
198 });
199 resourceTypeCombo.setItems(KNOWN_TEMPLATES.keySet().toArray(new String[0]));
200 resourceTypeCombo.select(0);
201
202 // File upload
203 Label lbl = new Label(composite, SWT.NONE);
204 lbl.setText("Chosen file");
205 lbl.setFont(EclipseUiUtils.getBoldFont(composite));
206 Composite uploadCmp = new Composite(composite, SWT.NONE);
207 uploadCmp.setLayoutData(EclipseUiUtils.fillWidth());
208 createFileUploadArea(uploadCmp);
209 setControl(composite);
210 }
211 }
212
213 private Control createFileUploadArea(Composite parent) {
214 GridLayout gl = EclipseUiUtils.noSpaceGridLayout(new GridLayout(2, false));
215 gl.horizontalSpacing = 5;
216 parent.setLayout(gl);
217
218 fileNameLabel = new Label(parent, SWT.NONE | SWT.BEGINNING);
219 fileNameLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
220
221 fileUpload = new FileUpload(parent, SWT.NONE);
222 fileUpload.setText("Browse...");
223 fileUpload.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
224
225 final String url = startUploadReceiver();
226 pushSession = new ServerPushSession();
227
228 fileUpload.addSelectionListener(new SelectionAdapter() {
229 private static final long serialVersionUID = 1L;
230
231 @Override
232 public void widgetSelected(SelectionEvent e) {
233 String fileName = fileUpload.getFileName();
234 fileNameLabel.setText(fileName == null ? "" : fileName);
235 pushSession.start();
236 fileUpload.submit(url);
237 }
238 });
239 return parent;
240 }
241
242 private String startUploadReceiver() {
243 MyFileUploadReceiver receiver = new MyFileUploadReceiver();
244 FileUploadHandler uploadHandler = new FileUploadHandler(receiver);
245 uploadHandler.addUploadListener(new FileUploadListener() {
246
247 public void uploadProgress(FileUploadEvent event) {
248 // handle upload progress
249 }
250
251 public void uploadFailed(FileUploadEvent event) {
252 ImportMappingFileWizard.this.userInputPage
253 .setErrorMessage("upload failed: " + event.getException());
254 }
255
256 public void uploadFinished(FileUploadEvent event) {
257 fileNameLabel.getDisplay().asyncExec(new Runnable() {
258 public void run() {
259 ImportMappingFileWizard.this.getContainer().updateButtons();
260 pushSession.stop();
261 }
262 });
263 }
264 });
265 return uploadHandler.getUploadUrl();
266 }
267
268 private class MyFileUploadReceiver extends FileUploadReceiver {
269
270 private static final String TEMP_FILE_PREFIX = "fileupload_";
271
272 @Override
273 public void receive(InputStream dataStream, FileDetails details) throws IOException {
274 File result = File.createTempFile(TEMP_FILE_PREFIX, "");
275 FileOutputStream outputStream = new FileOutputStream(result);
276 try {
277 copy(dataStream, outputStream);
278 } finally {
279 dataStream.close();
280 outputStream.close();
281 }
282 if (file != null)
283 file.delete();
284 file = result;
285 }
286 }
287
288 private void copy(InputStream inputStream, OutputStream outputStream) throws IOException {
289 byte[] buffer = new byte[8192];
290 boolean finished = false;
291 while (!finished) {
292 int bytesRead = inputStream.read(buffer);
293 if (bytesRead != -1) {
294 outputStream.write(buffer, 0, bytesRead);
295 } else {
296 finished = true;
297 }
298 }
299 }
300
301 /** Creates label and Combo. */
302 protected Combo createLC(Composite parent, String label) {
303 Label lbl = new Label(parent, SWT.RIGHT);
304 lbl.setText(label);
305 lbl.setFont(EclipseUiUtils.getBoldFont(parent));
306 lbl.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
307 Combo combo = new Combo(parent, SWT.READ_ONLY);
308 combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
309 return combo;
310 }
311 }
312
313 private Node importDefaultOrgFile(InputStream in) throws IOException {
314 // TODO make this configurable
315 int displayNameIndex = 0;
316 int legalNameIndex = 1;
317 int legalFormIndex = 2;
318 int urlsIndex = 3;
319 int streetIndex = 4;
320 int postalCodeIndex = 5;
321 int lIndex = 6;
322 int stIndex = 7;
323 int cIndex = 8;
324 int mobileIndex = 9;
325 int telephoneNumberIndex = 10;
326 int mailIndex = 11;
327 int contactsIndex = 12;
328 int descriptionIndex = 13;
329 int tagsIndex = 14;
330
331 Session session = null;
332 int i = 0;
333 try {
334 Workbook wb = JxlUtils.toWorkbook(in, IMPORT_ENCODING);
335 session = repository.login();
336 String basePath = "/" + peopleService.getBaseRelPath(PeopleTypes.PEOPLE_ORG);
337 Node targetParent = session.getNode(basePath);
338 Sheet sheet = wb.getSheet(0);
339
340 Node tmpParent = peopleService.getDraftParent(session);
341
342 int rowNb = sheet.getRows();
343 for (i = 1; i < rowNb - 1; i++) {
344
345 Node tmpOrg = createDraftNode(tmpParent, PeopleTypes.PEOPLE_ORG);
346
347 String dName = JxlUtils.getStringValue(sheet, displayNameIndex, i);
348 if (notEmpty(dName))
349 tmpOrg.setProperty(PeopleNames.PEOPLE_DISPLAY_NAME, dName);
350 String lName = getStringValue(sheet, legalNameIndex, i);
351 if (notEmpty(lName))
352 tmpOrg.setProperty(PeopleNames.PEOPLE_LEGAL_NAME, lName);
353 String lForm = getStringValue(sheet, legalFormIndex, i);
354 if (notEmpty(lForm))
355 tmpOrg.setProperty(PeopleNames.PEOPLE_LEGAL_FORM, lForm);
356 String urlStr = getStringValue(sheet, urlsIndex, i);
357 if (notEmpty(urlStr))
358 importUrls(tmpOrg, urlStr);
359 String mailStr = getStringValue(sheet, mailIndex, i);
360 if (notEmpty(mailStr))
361 importMails(tmpOrg, mailStr);
362 String streetStr = getStringValue(sheet, streetIndex, i);
363 String pcStr = getStringValue(sheet, postalCodeIndex, i);
364 String lStr = getStringValue(sheet, lIndex, i);
365 String stStr = getStringValue(sheet, stIndex, i);
366 String cStr = getStringValue(sheet, cIndex, i);
367 if (notEmpty(streetStr) || notEmpty(pcStr) || notEmpty(lStr) || notEmpty(stStr) || notEmpty(cStr))
368 PeopleJcrUtils.createAddress(resourcesService, peopleService, tmpOrg, streetStr, null, pcStr, lStr,
369 stStr, cStr, true, ContactValueCatalogs.CONTACT_CAT_MAIN, null);
370 String mobileStr = getStringValue(sheet, mobileIndex, i);
371 if (notEmpty(mobileStr))
372 PeopleJcrUtils.createPhone(resourcesService, peopleService, tmpOrg, mobileStr, true, null, null);
373 String phoneStr = getStringValue(sheet, telephoneNumberIndex, i);
374 if (notEmpty(phoneStr))
375 PeopleJcrUtils.createPhone(resourcesService, peopleService, tmpOrg, phoneStr, true,
376 ContactValueCatalogs.CONTACT_CAT_DIRECT, null);
377 String descStr = getStringValue(sheet, descriptionIndex, i);
378 if (notEmpty(descStr))
379 tmpOrg.setProperty(Property.JCR_DESCRIPTION, descStr);
380 String tagsStr = getStringValue(sheet, tagsIndex, i);
381 if (notEmpty(tagsStr))
382 tmpOrg.setProperty(ResourcesNames.CONNECT_TAGS, ConnectJcrUtils.parseAndClean(tagsStr, ",", true));
383
384 Node newOrgNode = peopleService.publishEntity(targetParent, PeopleTypes.PEOPLE_ORG, tmpOrg);
385 // Save the newly created entity without creating a base version
386 newOrgNode = peopleService.saveEntity(newOrgNode, false);
387
388 String contactsStr = getStringValue(sheet, contactsIndex, i);
389 if (notEmpty(contactsStr))
390 importOrgEmployees(tmpParent, targetParent, newOrgNode, contactsStr);
391 }
392
393 // Refresh tags and mailing list
394 Node tagParent = resourcesService.getTagLikeResourceParent(session, ConnectConstants.RESOURCE_TAG);
395 resourcesService.refreshKnownTags(tagParent);
396
397 // Create Mailing lists
398 Node mlParent = resourcesService.getTagLikeResourceParent(session, PeopleTypes.PEOPLE_MAILING_LIST);
399 resourcesService.refreshKnownTags(mlParent);
400
401 } catch (PeopleException | RepositoryException e) {
402 throw new SuiteWorkbenchException("Cannot import mapping file, error at line: " + (i + 1), e);
403 } finally {
404 JcrUtils.logoutQuietly(session);
405 }
406
407 return null;
408 }
409
410 private Map<String, Integer> initialiseHeaders(Sheet sheet, List<String> validHeaders) {
411 Map<String, Integer> headers = new HashMap<>();
412 int length = sheet.getColumns();
413 for (int i = 0; i < length; i++) {
414 String value = JxlUtils.getStringValue(sheet, i, 0);
415 if (validHeaders.contains(value))
416 headers.put(value, i);
417 else
418 log.warn(value + " (column [" + i + "]) is not a valid header");
419 }
420 return headers;
421 }
422
423 private Node importDefaultPersonFile(InputStream in) throws IOException {
424 // Local shortcut
425 String JCR_DESC = ConnectJcrUtils.getLocalJcrItemName(Property.JCR_DESCRIPTION);
426
427 // Map<String, Integer> headers = new HashMap<>();
428 // headers.put(PeopleNames.PEOPLE_FIRST_NAME, 0);
429 // headers.put(PEOPLE_LAST_NAME, 1);
430 // headers.put(PEOPLE_SALUTATION, 2);
431 // headers.put(PEOPLE_HONORIFIC_TITLE, 3);
432 // headers.put(PEOPLE_NICKNAME, 4);
433 // headers.put(PEOPLE_NAME_SUFFIX, 5);
434 // headers.put(PEOPLE_MAIDEN_NAME, 6);
435 // headers.put(PEOPLE_PMOBILE, 7);
436 // headers.put(PEOPLE_PTELEPHONE_NUMBER, 8);
437 // headers.put(PEOPLE_SPOKEN_LANGUAGES, 9);
438 // headers.put(ResourcesNames.CONNECT_TAGS, 10);
439 // headers.put(PEOPLE_MAILING_LISTS, 11);
440 // headers.put(PEOPLE_BIRTH_DATE, 12);
441 // headers.put(PEOPLE_PMAIL, 13);
442 // headers.put("people:emailAddressOther", 14);
443 // headers.put("people:org", 15);
444 // headers.put(PEOPLE_ROLE, 16);
445 // headers.put(PEOPLE_DEPARTMENT, 17);
446 // headers.put("people:facebook", 18);
447 // headers.put(JCR_DESC, 19);
448 // headers.put(ActivitiesNames.ACTIVITIES_FROM_IP, 20);
449
450 List<String> validHeaders = Arrays.asList(PeopleNames.PEOPLE_FIRST_NAME, PEOPLE_LAST_NAME, PEOPLE_SALUTATION,
451 PEOPLE_HONORIFIC_TITLE, PEOPLE_NICKNAME, PEOPLE_NAME_SUFFIX, PEOPLE_MAIDEN_NAME, PEOPLE_PMOBILE,
452 PEOPLE_PTELEPHONE_NUMBER, PEOPLE_SPOKEN_LANGUAGES, ResourcesNames.CONNECT_TAGS, PEOPLE_MAILING_LISTS,
453 PEOPLE_BIRTH_DATE, PEOPLE_PMAIL, "people:emailAddressOther", "people:org", PEOPLE_ROLE,
454 PEOPLE_DEPARTMENT, "people:facebook", JCR_DESC, ActivitiesNames.ACTIVITIES_FROM_IP, PEOPLE_STREET,
455 PEOPLE_ZIP_CODE, PEOPLE_CITY, PEOPLE_STATE, PEOPLE_COUNTRY);
456
457 String[] basicInfo = { PEOPLE_FIRST_NAME, PEOPLE_LAST_NAME, PEOPLE_SALUTATION, PEOPLE_HONORIFIC_TITLE,
458 PEOPLE_NICKNAME, PEOPLE_NAME_SUFFIX, PEOPLE_MAIDEN_NAME, PEOPLE_BIRTH_DATE, JCR_DESC };
459
460 Map<String, String> primaryContacts = new HashMap<>();
461 primaryContacts.put(PEOPLE_PMOBILE, PeopleTypes.PEOPLE_MOBILE);
462 primaryContacts.put(PEOPLE_PTELEPHONE_NUMBER, PeopleTypes.PEOPLE_TELEPHONE_NUMBER);
463 primaryContacts.put(PEOPLE_PURL, PeopleTypes.PEOPLE_URL);
464 primaryContacts.put(PEOPLE_PMAIL, PeopleTypes.PEOPLE_MAIL);
465
466 String[] multiProps = { PEOPLE_SPOKEN_LANGUAGES, ResourcesNames.CONNECT_TAGS, PEOPLE_MAILING_LISTS, };
467
468 Session session = null;
469 int i = 0;
470 try {
471 Workbook wb = JxlUtils.toWorkbook(in, IMPORT_ENCODING);
472 session = repository.login();
473 String basePath = "/" + peopleService.getBaseRelPath(PeopleTypes.PEOPLE_PERSON);
474 Node targetParent = session.getNode(basePath);
475 Sheet sheet = wb.getSheet(0);
476
477 Map<String, Integer> headers = initialiseHeaders(sheet, validHeaders);
478
479 Node tmpParent = peopleService.getDraftParent(session);
480
481 int rowNb = sheet.getRows();
482 for (i = 1; i < rowNb; i++) {
483 Node tmpPerson = createDraftNode(tmpParent, PeopleTypes.PEOPLE_PERSON);
484
485 for (String propName : basicInfo) {
486 if (headers.containsKey(propName)) {
487 String value = JxlUtils.getStringValue(sheet, headers.get(propName), i);
488 if (notEmpty(value))
489 tmpPerson.setProperty(propName, value);
490 }
491 }
492
493 for (String propName : multiProps) {
494 if (headers.containsKey(propName)) {
495 String value = JxlUtils.getStringValue(sheet, headers.get(propName), i);
496 if (notEmpty(value))
497 tmpPerson.setProperty(propName, ConnectJcrUtils.parseAndClean(value, ",", true));
498 }
499 }
500
501 for (String propName : primaryContacts.keySet()) {
502 if (headers.containsKey(propName)) {
503 String value = JxlUtils.getStringValue(sheet, headers.get(propName), i);
504 if (notEmpty(value)) {
505 PeopleJcrUtils.createContact(resourcesService, peopleService, tmpPerson,
506 primaryContacts.get(propName), value, true,
507 ContactValueCatalogs.CONTACT_CAT_MAIN, null);
508 }
509 }
510 }
511
512 // Specific values
513 String propName = "people:emailAddressOther";
514 if (headers.containsKey(propName)) {
515 String value = JxlUtils.getStringValue(sheet, headers.get(propName), i);
516 if (notEmpty(value)) {
517 PeopleJcrUtils.createContact(resourcesService, peopleService, tmpPerson,
518 PeopleTypes.PEOPLE_MAIL, value, false, ContactValueCatalogs.CONTACT_CAT_MAIN,
519 null);
520 }
521 }
522
523 propName = "people:facebook";
524 if (headers.containsKey(propName)) {
525 String value = JxlUtils.getStringValue(sheet, headers.get(propName), i);
526 if (notEmpty(value)) {
527 PeopleJcrUtils.createContact(resourcesService, peopleService, tmpPerson,
528 PeopleTypes.PEOPLE_SOCIAL_MEDIA, value, false,
529 ContactValueCatalogs.CONTACT_CAT_FACEBOOK, null);
530 }
531 }
532
533 String street = null, zip = null, city = null, state = null, country = null;
534 if (headers.containsKey(PEOPLE_STREET))
535 street = JxlUtils.getStringValue(sheet, headers.get(PEOPLE_STREET), i);
536 if (headers.containsKey(PEOPLE_ZIP_CODE))
537 zip = JxlUtils.getStringValue(sheet, headers.get(PEOPLE_ZIP_CODE), i);
538 if (headers.containsKey(PEOPLE_CITY))
539 city = JxlUtils.getStringValue(sheet, headers.get(PEOPLE_CITY), i);
540 if (headers.containsKey(PEOPLE_STATE))
541 state = JxlUtils.getStringValue(sheet, headers.get(PEOPLE_STATE), i);
542 if (headers.containsKey(PEOPLE_COUNTRY))
543 country = JxlUtils.getStringValue(sheet, headers.get(PEOPLE_COUNTRY), i);
544
545 if (notEmpty(street) || notEmpty(zip) || notEmpty(city) || notEmpty(state) || notEmpty(country)) {
546 PeopleJcrUtils.createAddress(resourcesService, peopleService, tmpPerson, street, null, zip, city,
547 state, country, true, ContactValueCatalogs.CONTACT_CAT_MAIN, null);
548 }
549
550 // TODO Experimental connection activity to store info about the
551 // IP from where a person has registered himself in the system
552 // propName = ActivitiesNames.ACTIVITIES_FROM_IP;
553
554 // TODO create a job and possibly the related organisation
555
556 Node newPersonNode = peopleService.publishEntity(targetParent, PeopleTypes.PEOPLE_PERSON, tmpPerson);
557 // Save the newly created entity without creating a base version
558 newPersonNode = peopleService.saveEntity(newPersonNode, false);
559 }
560
561 // Refresh tags and mailing list
562 Node tagParent = resourcesService.getTagLikeResourceParent(session, ConnectConstants.RESOURCE_TAG);
563 resourcesService.refreshKnownTags(tagParent);
564
565 // Create Mailing lists
566 Node mlParent = resourcesService.getTagLikeResourceParent(session, PeopleTypes.PEOPLE_MAILING_LIST);
567 resourcesService.refreshKnownTags(mlParent);
568 } catch (PeopleException | RepositoryException e) {
569 String message = "Cannot import mapping file, error at line: " + (i + 1);
570 // TODO Check why the error is swallowed.
571 log.error(message, e);
572 throw new SuiteWorkbenchException(message, e);
573 } finally {
574 JcrUtils.logoutQuietly(session);
575 }
576 return null;
577 }
578
579 private Node createDraftNode(Node parent, String mainMixin) throws RepositoryException {
580 String uuid = UUID.randomUUID().toString();
581 Node tmpNode = parent.addNode(uuid);
582 tmpNode.addMixin(mainMixin);
583 tmpNode.setProperty(ConnectNames.CONNECT_UID, uuid);
584 return tmpNode;
585 }
586
587 private void importOrgEmployees(Node tmpParent, Node targetParent, Node newOrgNode, String coworkersStr)
588 throws RepositoryException {
589 String[] coworkers = coworkersStr.split("\\n");
590 loop: for (String line : coworkers) {
591 if (EclipseUiUtils.isEmpty(line))
592 continue loop;
593 line = line.trim();
594 int index = line.indexOf(' ');
595 String firstName = null;
596 String lastName = null;
597 String position = null;
598 if (index == -1)
599 firstName = line;
600 else {
601 firstName = line.substring(0, index);
602 line = line.substring(index);
603
604 index = line.indexOf('(');
605 if (index == -1)
606 lastName = line;
607 else {
608 lastName = line.substring(0, index).trim();
609 position = line.substring(index + 1, line.length() - 1);
610 }
611 }
612 Node tmpPerson = createDraftNode(tmpParent, PeopleTypes.PEOPLE_PERSON);
613 tmpPerson.setProperty(PEOPLE_FIRST_NAME, firstName);
614 if (EclipseUiUtils.notEmpty(lastName))
615 tmpPerson.setProperty(PEOPLE_LAST_NAME, lastName);
616 Node newPersonNode = peopleService.publishEntity(targetParent, PeopleTypes.PEOPLE_PERSON, tmpPerson);
617 // if (EclipseUiUtils.notEmpty(position))
618 PersonJcrUtils.addJob(resourcesService, peopleService, newPersonNode, newOrgNode, position, true);
619 // Save the newly created entity without creating a base version
620 newPersonNode = peopleService.saveEntity(newPersonNode, false);
621
622 }
623 }
624
625 private void importUrls(Node contactable, String urlStr) throws RepositoryException {
626 String[] urls = urlStr.split("\\n");
627 boolean hasPrimary = false;
628 boolean hasPrimaryFacebook = false;
629
630 loop: for (String line : urls) {
631 if (EclipseUiUtils.isEmpty(line))
632 continue loop;
633 line = line.trim();
634
635 if (line.startsWith("https://www.facebook.com")) {
636 PeopleJcrUtils.createSocialMedia(resourcesService, peopleService, contactable, line,
637 !hasPrimaryFacebook, ContactValueCatalogs.CONTACT_CAT_FACEBOOK, null);
638 hasPrimaryFacebook = true;
639 } else {
640 PeopleJcrUtils.createWebsite(resourcesService, peopleService, contactable, line, !hasPrimary, null);
641 hasPrimary = true;
642 }
643 }
644 }
645
646 private void importMails(Node contactable, String mailStr) throws RepositoryException {
647 String[] urls = mailStr.split("\\n");
648 boolean hasPrimary = false;
649 loop: for (String line : urls) {
650 if (EclipseUiUtils.isEmpty(line))
651 continue loop;
652 line = line.trim();
653 PeopleJcrUtils.createEmail(resourcesService, peopleService, contactable, line, !hasPrimary, null, null);
654 hasPrimary = true;
655 }
656 }
657
658 /* DEPENDENCY INJECTION */
659 public void setRepository(Repository repository) {
660 this.repository = repository;
661 }
662
663 public void setResourcesService(ResourcesService resourcesService) {
664 this.resourcesService = resourcesService;
665 }
666
667 public void setPeopleService(PeopleService peopleService) {
668 this.peopleService = peopleService;
669 }
670 }