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