List of usage examples for java.io Serializable getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.alfresco.repo.action.executer.MailActionExecuter.java
public MimeMessageHelper prepareEmail(final Action ruleAction, final NodeRef actionedUponNodeRef, final Pair<String, Locale> recipient, final Pair<InternetAddress, Locale> sender) { // Create the mime mail message. // Hack: using an array here to get around the fact that inner classes aren't closures. // The MimeMessagePreparator.prepare() signature does not allow us to return a value and yet // we can't set a result on a bare, non-final object reference due to Java language restrictions. final MimeMessageHelper[] messageRef = new MimeMessageHelper[1]; MimeMessagePreparator mailPreparer = new MimeMessagePreparator() { @SuppressWarnings("unchecked") public void prepare(MimeMessage mimeMessage) throws MessagingException { if (logger.isDebugEnabled()) { logger.debug(ruleAction.getParameterValues()); }/*from w w w. ja va 2s . c o m*/ messageRef[0] = new MimeMessageHelper(mimeMessage); // set header encoding if one has been supplied if (headerEncoding != null && headerEncoding.length() != 0) { mimeMessage.setHeader("Content-Transfer-Encoding", headerEncoding); } // set recipient String to = (String) ruleAction.getParameterValue(PARAM_TO); if (to != null && to.length() != 0) { messageRef[0].setTo(to); // Note: there is no validation on the username to check that it actually is an email address. // TODO Fix this. Serializable ccValue = (String) ruleAction.getParameterValue(PARAM_CC); if (ccValue != null) { if (ccValue instanceof String) { String cc = (String) ccValue; if (cc.length() > 0) { messageRef[0].setCc(cc); } } else if (ccValue instanceof List<?>) { List<String> s = (List<String>) ccValue; messageRef[0].setCc((String[]) s.toArray()); } else if (ccValue.getClass().isArray()) { messageRef[0].setCc((String[]) ccValue); } } Serializable bccValue = (String) ruleAction.getParameterValue(PARAM_BCC); if (bccValue != null) { if (bccValue instanceof String) { String bcc = (String) bccValue; if (bcc.length() > 0) { messageRef[0].setBcc(bcc); } } else if (bccValue instanceof List<?>) { List<String> s = (List<String>) bccValue; messageRef[0].setBcc((String[]) s.toArray()); } else if (bccValue.getClass().isArray()) { messageRef[0].setCc((String[]) bccValue); } } } else { // see if multiple recipients have been supplied - as a list of authorities Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY); List<String> authorities = null; if (authoritiesValue != null) { if (authoritiesValue instanceof String) { authorities = new ArrayList<String>(1); authorities.add((String) authoritiesValue); } else { authorities = (List<String>) authoritiesValue; } } if (authorities != null && authorities.size() != 0) { List<String> recipients = new ArrayList<String>(authorities.size()); if (logger.isTraceEnabled()) { logger.trace(authorities.size() + " recipient(s) for mail"); } for (String authority : authorities) { final AuthorityType authType = AuthorityType.getAuthorityType(authority); if (logger.isTraceEnabled()) { logger.trace(" authority type: " + authType); } if (authType.equals(AuthorityType.USER)) { if (personService.personExists(authority) == true) { NodeRef person = personService.getPerson(authority); if (!personService.isEnabled(authority) && !nodeService.hasAspect(person, ContentModel.ASPECT_ANULLABLE)) { continue; } String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0 && validateAddress(address)) { if (logger.isTraceEnabled()) { logger.trace("Recipient (person) exists in Alfresco with known email."); } recipients.add(address); } else { if (logger.isTraceEnabled()) { logger.trace( "Recipient (person) exists in Alfresco without known email."); } // If the username looks like an email address, we'll use that. if (validateAddress(authority)) { recipients.add(authority); } } } else { if (logger.isTraceEnabled()) { logger.trace("Recipient does not exist in Alfresco."); } if (validateAddress(authority)) { recipients.add(authority); } } } else if (authType.equals(AuthorityType.GROUP) || authType.equals(AuthorityType.EVERYONE)) { if (logger.isTraceEnabled()) { logger.trace("Recipient is a group..."); } // Notify all members of the group Set<String> users; if (authType.equals(AuthorityType.GROUP)) { users = authorityService.getContainedAuthorities(AuthorityType.USER, authority, false); } else { users = authorityService.getAllAuthorities(AuthorityType.USER); } for (String userAuth : users) { if (personService.personExists(userAuth) == true) { if (!personService.isEnabled(userAuth)) { continue; } NodeRef person = personService.getPerson(userAuth); String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0) { recipients.add(address); if (logger.isTraceEnabled()) { logger.trace(" Group member email is known."); } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member email not known."); } if (validateAddress(authority)) { recipients.add(userAuth); } } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member person not found"); } if (validateAddress(authority)) { recipients.add(userAuth); } } } } } if (logger.isTraceEnabled()) { logger.trace(recipients.size() + " valid recipient(s)."); } if (recipients.size() > 0) { messageRef[0].setTo(recipients.toArray(new String[recipients.size()])); } else { // All recipients were invalid throw new MailPreparationException("All recipients for the mail action were invalid"); } } else { // No recipients have been specified throw new MailPreparationException("No recipient has been specified for the mail action"); } } // from person - not to be performed for the "admin" or "system" users NodeRef fromPerson = null; final String currentUserName = authService.getCurrentUserName(); final List<String> usersNotToBeUsedInFromField = Arrays.asList(new String[] { AuthenticationUtil.getSystemUserName(), AuthenticationUtil.getGuestUserName() }); if (!usersNotToBeUsedInFromField.contains(currentUserName)) { fromPerson = personService.getPerson(currentUserName); } if (isFromEnabled()) { // Use the FROM parameter in preference to calculating values. String from = (String) ruleAction.getParameterValue(PARAM_FROM); if (from != null && from.length() > 0) { if (logger.isDebugEnabled()) { logger.debug("from specified as a parameter, from:" + from); } // Check whether or not to use a personal name for the email (will be RFC 2047 encoded) String fromPersonalName = (String) ruleAction.getParameterValue(PARAM_FROM_PERSONAL_NAME); if (fromPersonalName != null && fromPersonalName.length() > 0) { try { messageRef[0].setFrom(from, fromPersonalName); } catch (UnsupportedEncodingException error) { // Uses the JVM's default encoding, can never be unsupported. Just in case, revert to simple email messageRef[0].setFrom(from); } } else { messageRef[0].setFrom(from); } } else { // set the from address from the current user String fromActualUser = null; if (fromPerson != null) { fromActualUser = (String) nodeService.getProperty(fromPerson, ContentModel.PROP_EMAIL); } if (fromActualUser != null && fromActualUser.length() != 0) { if (logger.isDebugEnabled()) { logger.debug("looked up email address for :" + fromPerson + " email from " + fromActualUser); } messageRef[0].setFrom(fromActualUser); } else { // from system or user does not have email address messageRef[0].setFrom(fromDefaultAddress); } } } else { if (logger.isDebugEnabled()) { logger.debug("from not enabled - sending from default address:" + fromDefaultAddress); } // from is not enabled. messageRef[0].setFrom(fromDefaultAddress); } // set subject line messageRef[0].setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT)); if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll send the email to that address instead. // We'll prefix the subject with the original recipient, but leave the email message unchanged in every other way. messageRef[0].setTo(testModeRecipient); String emailRecipient = (String) ruleAction.getParameterValue(PARAM_TO); if (emailRecipient == null) { Object obj = ruleAction.getParameterValue(PARAM_TO_MANY); if (obj != null) { emailRecipient = obj.toString(); } } String recipientPrefixedSubject = "(" + emailRecipient + ") " + (String) ruleAction.getParameterValue(PARAM_SUBJECT); messageRef[0].setSubject(recipientPrefixedSubject); } // See if an email template has been specified String text = null; // templateRef: either a nodeRef or classpath (see ClasspathRepoTemplateLoader) Serializable ref = ruleAction.getParameterValue(PARAM_TEMPLATE); String templateRef = (ref instanceof NodeRef ? ((NodeRef) ref).toString() : (String) ref); if (templateRef != null) { Map<String, Object> suppliedModel = null; if (ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null) { Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL); if (m instanceof Map) { suppliedModel = (Map<String, Object>) m; } else { logger.warn("Skipping unsupported email template model parameters of type " + m.getClass().getName() + " : " + m.toString()); } } // build the email template model Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, suppliedModel, fromPerson); // Determine the locale to use to send the email. Locale locale = recipient.getSecond(); if (locale == null) { locale = (Locale) ruleAction.getParameterValue(PARAM_LOCALE); } if (locale == null) { locale = sender.getSecond(); } // set subject line String subject = (String) ruleAction.getParameterValue(PARAM_SUBJECT); Object subjectParamsObject = ruleAction.getParameterValue(PARAM_SUBJECT_PARAMS); Object[] subjectParams = null; //Javasctipt pass SubjectParams as ArrayList. see MNT-12534 if (subjectParamsObject instanceof List) { subjectParams = ((List<Object>) subjectParamsObject).toArray(); } else if (subjectParamsObject instanceof Object[]) { subjectParams = (Object[]) subjectParamsObject; } else { if (subjectParamsObject != null) { subjectParams = new Object[] { subjectParamsObject.toString() }; } } String localizedSubject = getLocalizedSubject(subject, subjectParams, locale); if (locale == null) { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model); } else { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model, locale); } if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll send the email to that address instead. // We'll prefix the subject with the original recipient, but leave the email message unchanged in every other way. messageRef[0].setTo(testModeRecipient); String emailRecipient = recipient.getFirst(); String recipientPrefixedSubject = "(" + emailRecipient + ") " + localizedSubject; messageRef[0].setSubject(recipientPrefixedSubject); } else { messageRef[0].setTo(recipient.getFirst()); messageRef[0].setSubject(localizedSubject); } } // set the text body of the message boolean isHTML = false; if (text == null) { text = (String) ruleAction.getParameterValue(PARAM_TEXT); } if (text != null) { if (isHTML(text)) { isHTML = true; } } else { text = (String) ruleAction.getParameterValue(PARAM_HTML); if (text != null) { // assume HTML isHTML = true; } } if (text != null) { messageRef[0].setText(text, isHTML); } } }; MimeMessage mimeMessage = mailService.createMimeMessage(); try { mailPreparer.prepare(mimeMessage); } catch (Exception e) { // We're forced to catch java.lang.Exception here. Urgh. if (logger.isWarnEnabled()) { logger.warn("Unable to prepare mail message. Skipping.", e); } return null; } return messageRef[0]; }
From source file:org.alfresco.repo.tagging.TaggingServiceImplTest.java
@SuppressWarnings("unchecked") public void test5TagScopeSummary() throws Exception { asyncOccurs.awaitExecution(new RetryingTransactionCallback<Void>() { @Override/*from www. j a v a 2s. c o m*/ public Void execute() throws Throwable { // TODO add some tags before the scopes are added // Add some tag scopes taggingService.addTagScope(folder); taggingService.addTagScope(subFolder); // Add some more tags after the scopes have been added taggingService.addTag(subDocument, TAG_1); // folder+subfolder return null; } }); asyncOccurs.awaitExecution(new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { taggingService.addTag(subDocument, TAG_2); // folder+subfolder return null; } }); asyncOccurs.awaitExecution(new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { taggingService.addTag(subDocument, TAG_3); // folder+subfolder return null; } }); asyncOccurs.awaitExecution(new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { taggingService.addTag(subFolder, TAG_1); // folder+subfolder return null; } }); asyncOccurs.awaitExecution(new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { taggingService.addTag(subFolder, TAG_2); // folder+subfolder return null; } }); asyncOccurs.awaitExecution(new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { taggingService.addTag(folder, TAG_2); // folder only return null; } }); this.transactionService.getRetryingTransactionHelper() .doInTransaction(new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { TagScopePropertyMethodInterceptor.setEnabled(Boolean.TRUE); Serializable summaryObj = nodeService.getProperty(folder, ContentModel.PROP_TAGSCOPE_SUMMARY); assertTrue( "TagScopeSummary value on main folder is not of correct class: " + summaryObj.getClass().getName(), List.class.isAssignableFrom(summaryObj.getClass())); assertEquals(3, ((List) summaryObj).size()); //Check that the next call for the same summary comes from the cache Serializable summaryObj2 = nodeService.getProperty(folder, ContentModel.PROP_TAGSCOPE_SUMMARY); assertTrue("TagScopeSummary value on main folder did not come from the cache", summaryObj == summaryObj2); Map<QName, Serializable> props = nodeService.getProperties(subFolder); assertTrue("Properties of subfolder do not include tagScopeSummary", props.containsKey(ContentModel.PROP_TAGSCOPE_SUMMARY)); summaryObj = props.get(ContentModel.PROP_TAGSCOPE_SUMMARY); assertTrue( "TagScopeSummary value on subfolder is not of correct class: " + summaryObj.getClass().getName(), List.class.isAssignableFrom(summaryObj.getClass())); assertEquals(3, ((List) summaryObj).size()); TagScopePropertyMethodInterceptor.setEnabled(Boolean.FALSE); summaryObj = nodeService.getProperty(folder, ContentModel.PROP_TAGSCOPE_SUMMARY); assertNull("TagScopeSummary value on main folder should be null: " + summaryObj, summaryObj); props = nodeService.getProperties(subFolder); assertFalse("Properties of subfolder should not contain tagScopeProperty", props.containsKey(ContentModel.PROP_TAGSCOPE_SUMMARY)); return null; } }); }
From source file:net.malariagen.alfresco.action.CustomMailAction.java
public MimeMessageHelper prepareEmail(final Action ruleAction, final NodeRef actionedUponNodeRef, final Pair<String, Locale> recipient, final Pair<InternetAddress, Locale> sender) { // Create the mime mail message. // Hack: using an array here to get around the fact that inner classes // aren't closures. // The MimeMessagePreparator.prepare() signature does not allow us to // return a value and yet // we can't set a result on a bare, non-final object reference due to // Java language restrictions. final MimeMessageHelper[] messageRef = new MimeMessageHelper[1]; MimeMessagePreparator mailPreparer = new MimeMessagePreparator() { @SuppressWarnings("unchecked") public void prepare(MimeMessage mimeMessage) throws MessagingException { if (logger.isDebugEnabled()) { logger.debug(ruleAction.getParameterValues()); }//from w ww . j ava 2s. c om messageRef[0] = new MimeMessageHelper(mimeMessage); // set header encoding if one has been supplied if (headerEncoding != null && headerEncoding.length() != 0) { mimeMessage.setHeader("Content-Transfer-Encoding", headerEncoding); } String listHeaders = (String) ruleAction.getParameterValue(PARAM_LIST_ID); if (listHeaders != null) { mimeMessage.setHeader("List-Id", "<" + listHeaders + "." + sysAdminParams.getAlfrescoHost() + ">"); mimeMessage.setHeader("X-Auto-Response-Suppress", "All"); mimeMessage.setHeader("Precedence", "list"); mimeMessage.setHeader("auto-submitted", "auto-generated"); } // set recipient // I don't think this is used - see getRecipients in parent String to = (String) ruleAction.getParameterValue(PARAM_TO); if (to != null && to.length() != 0) { messageRef[0].setTo(to); // Note: there is no validation on the username to check // that it actually is an email address. // TODO Fix this. Serializable ccValue = (String) ruleAction.getParameterValue(PARAM_CC); if (ccValue != null) { if (ccValue instanceof String) { String cc = (String) ccValue; if (cc.length() > 0) { messageRef[0].setCc(cc); } } else if (ccValue instanceof List<?>) { List<String> s = (List<String>) ccValue; messageRef[0].setCc((String[]) s.toArray()); } else if (ccValue.getClass().isArray()) { messageRef[0].setCc((String[]) ccValue); } } Serializable bccValue = (String) ruleAction.getParameterValue(PARAM_BCC); if (bccValue != null) { if (bccValue instanceof String) { String bcc = (String) bccValue; if (bcc.length() > 0) { messageRef[0].setBcc(bcc); } } else if (bccValue instanceof List<?>) { List<String> s = (List<String>) bccValue; messageRef[0].setBcc((String[]) s.toArray()); } else if (bccValue.getClass().isArray()) { messageRef[0].setCc((String[]) bccValue); } } } else { // see if multiple recipients have been supplied - as a list // of authorities Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY); List<String> authorities = null; if (authoritiesValue != null) { if (authoritiesValue instanceof String) { authorities = new ArrayList<String>(1); authorities.add((String) authoritiesValue); } else { authorities = (List<String>) authoritiesValue; } } if (authorities != null && authorities.size() != 0) { List<String> recipients = new ArrayList<String>(authorities.size()); if (logger.isTraceEnabled()) { logger.trace(authorities.size() + " recipient(s) for mail"); } for (String authority : authorities) { final AuthorityType authType = AuthorityType.getAuthorityType(authority); if (logger.isTraceEnabled()) { logger.trace(" authority type: " + authType); } if (authType.equals(AuthorityType.USER)) { if (personService.personExists(authority) == true) { NodeRef person = personService.getPerson(authority); if (!personService.isEnabled(authority) && !nodeService.hasAspect(person, ContentModel.ASPECT_ANULLABLE)) { continue; } String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0 && validateAddress(address)) { if (logger.isTraceEnabled()) { logger.trace("Recipient (person) exists in Alfresco with known email."); } recipients.add(address); } else { if (logger.isTraceEnabled()) { logger.trace( "Recipient (person) exists in Alfresco without known email."); } // If the username looks like an email // address, we'll use that. if (validateAddress(authority)) { recipients.add(authority); } } } else { if (logger.isTraceEnabled()) { logger.trace("Recipient does not exist in Alfresco."); } if (validateAddress(authority)) { recipients.add(authority); } } } else if (authType.equals(AuthorityType.GROUP) || authType.equals(AuthorityType.EVERYONE)) { if (logger.isTraceEnabled()) { logger.trace("Recipient is a group..."); } // Notify all members of the group Set<String> users; if (authType.equals(AuthorityType.GROUP)) { users = authorityService.getContainedAuthorities(AuthorityType.USER, authority, false); } else { users = authorityService.getAllAuthorities(AuthorityType.USER); } for (String userAuth : users) { if (personService.personExists(userAuth) == true) { NodeRef person = personService.getPerson(userAuth); String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0) { recipients.add(address); if (logger.isTraceEnabled()) { logger.trace(" Group member email is known."); } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member email not known."); } if (validateAddress(authority)) { recipients.add(userAuth); } } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member person not found"); } if (validateAddress(authority)) { recipients.add(userAuth); } } } } } if (logger.isTraceEnabled()) { logger.trace(recipients.size() + " valid recipient(s)."); } if (recipients.size() > 0) { messageRef[0].setTo(recipients.toArray(new String[recipients.size()])); } else { // All recipients were invalid throw new MailPreparationException("All recipients for the mail action were invalid"); } } else { // No recipients have been specified throw new MailPreparationException("No recipient has been specified for the mail action"); } } // from person - not to be performed for the "admin" or "system" // users NodeRef fromPerson = null; final String currentUserName = authService.getCurrentUserName(); final List<String> usersNotToBeUsedInFromField = Arrays.asList(new String[] { AuthenticationUtil.getSystemUserName(), AuthenticationUtil.getGuestUserName() }); if (!usersNotToBeUsedInFromField.contains(currentUserName)) { fromPerson = personService.getPerson(currentUserName); } if (isFromEnabled()) { // Use the FROM parameter in preference to calculating // values. String from = (String) ruleAction.getParameterValue(PARAM_FROM); if (from != null && from.length() > 0) { if (logger.isDebugEnabled()) { logger.debug("from specified as a parameter, from:" + from); } // Check whether or not to use a personal name for the // email (will be RFC 2047 encoded) String fromPersonalName = (String) ruleAction.getParameterValue(PARAM_FROM_PERSONAL_NAME); if (fromPersonalName != null && fromPersonalName.length() > 0) { try { messageRef[0].setFrom(from, fromPersonalName); } catch (UnsupportedEncodingException error) { // Uses the JVM's default encoding, can never be // unsupported. Just in case, revert to simple // email messageRef[0].setFrom(from); } } else { messageRef[0].setFrom(from); } setReplyTo(ruleAction, messageRef, from); } else { // set the from address from the current user String fromActualUser = null; if (fromPerson != null) { fromActualUser = (String) nodeService.getProperty(fromPerson, ContentModel.PROP_EMAIL); } if (fromActualUser != null && fromActualUser.length() != 0) { if (logger.isDebugEnabled()) { logger.debug("looked up email address for :" + fromPerson + " email from " + fromActualUser); } messageRef[0].setFrom(fromActualUser); setReplyTo(ruleAction, messageRef, fromDefaultAddress); } else { // from system or user does not have email address messageRef[0].setFrom(fromDefaultAddress); setReplyTo(ruleAction, messageRef, fromDefaultAddress); } } } else { if (logger.isDebugEnabled()) { logger.debug("from not enabled - sending from default address:" + fromDefaultAddress); } // from is not enabled. messageRef[0].setFrom(fromDefaultAddress); setReplyTo(ruleAction, messageRef, fromDefaultAddress); } // set subject line messageRef[0].setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT)); if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll // send the email to that address instead. // We'll prefix the subject with the original recipient, but // leave the email message unchanged in every other way. messageRef[0].setTo(testModeRecipient); String emailRecipient = (String) ruleAction.getParameterValue(PARAM_TO); if (emailRecipient == null) { Object obj = ruleAction.getParameterValue(PARAM_TO_MANY); if (obj != null) { emailRecipient = obj.toString(); } } String recipientPrefixedSubject = "(" + emailRecipient + ") " + (String) ruleAction.getParameterValue(PARAM_SUBJECT); messageRef[0].setSubject(recipientPrefixedSubject); } // See if an email template has been specified String text = null; // templateRef: either a nodeRef or classpath (see // ClasspathRepoTemplateLoader) Serializable ref = ruleAction.getParameterValue(PARAM_TEMPLATE); String templateRef = (ref instanceof NodeRef ? ((NodeRef) ref).toString() : (String) ref); if (templateRef != null) { Map<String, Object> suppliedModel = null; if (ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null) { Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL); if (m instanceof Map) { suppliedModel = (Map<String, Object>) m; } else { logger.warn("Skipping unsupported email template model parameters of type " + m.getClass().getName() + " : " + m.toString()); } } // build the email template model Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, suppliedModel, fromPerson); // Determine the locale to use to send the email. Locale locale = recipient.getSecond(); if (locale == null) { locale = (Locale) ruleAction.getParameterValue(PARAM_LOCALE); } if (locale == null) { locale = sender.getSecond(); } // set subject line String subject = (String) ruleAction.getParameterValue(PARAM_SUBJECT); Object subjectParamsObject = ruleAction.getParameterValue(PARAM_SUBJECT_PARAMS); Object[] subjectParams = null; // Javasctipt pass SubjectParams as ArrayList. see MNT-12534 if (subjectParamsObject instanceof List) { subjectParams = ((List<Object>) subjectParamsObject).toArray(); } else if (subjectParamsObject instanceof Object[]) { subjectParams = (Object[]) subjectParamsObject; } else { if (subjectParamsObject != null) { subjectParams = new Object[] { subjectParamsObject.toString() }; } } String localizedSubject = getLocalizedSubject(subject, subjectParams, locale); if (locale == null) { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model); } else { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model, locale); } if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll // send the email to that address instead. // We'll prefix the subject with the original recipient, // but leave the email message unchanged in every other // way. messageRef[0].setTo(testModeRecipient); String emailRecipient = recipient.getFirst(); String recipientPrefixedSubject = "(" + emailRecipient + ") " + localizedSubject; messageRef[0].setSubject(recipientPrefixedSubject); } else { messageRef[0].setTo(recipient.getFirst()); messageRef[0].setSubject(localizedSubject); } } // set the text body of the message boolean isHTML = false; if (text == null) { text = (String) ruleAction.getParameterValue(PARAM_TEXT); } if (text != null) { if (isHTML(text)) { isHTML = true; } } else { text = (String) ruleAction.getParameterValue(PARAM_HTML); if (text != null) { // assume HTML isHTML = true; } } if (text != null) { messageRef[0].setText(text, isHTML); } } private void setReplyTo(final Action ruleAction, final MimeMessageHelper[] messageRef, String from) throws MessagingException { // ResponseNode can be a Long as well as Text Object responseNode = ruleAction.getParameterValue(PARAM_RESPONSE_NODE); if (responseNode != null) { // Assuming address is valid... String[] parts = from.split("@"); messageRef[0].setReplyTo(parts[0] + "+" + responseNode + "@" + parts[1]); } } }; MimeMessage mimeMessage = mailService.createMimeMessage(); try { mailPreparer.prepare(mimeMessage); } catch (Exception e) { // We're forced to catch java.lang.Exception here. Urgh. if (logger.isWarnEnabled()) { logger.warn("Unable to prepare mail message. Skipping.", e); } return null; } return messageRef[0]; }
From source file:com.ebay.erl.mobius.core.model.Tuple.java
/** * For the given column named <code>name</code>, * add (if it doesn't exist) to this tuple or update (if it * exists) its value to the given <code>value</code>. * // w ww . ja va2 s .c o m * @return return this tuple * @throws IllegalArgumentException if <code>value</code> is instance * of Map but not {@link CaseInsensitiveTreeMap}. Or when <code>value</code> * doesn't implement {@link Comparable} */ public Tuple put(String name, Serializable value) { if (value == null) throw new NullPointerException("value cannot be null."); if (value instanceof Map<?, ?> && !(value instanceof CaseInsensitiveTreeMap)) { throw new IllegalArgumentException( "The supported map type is only " + CaseInsensitiveTreeMap.class.getCanonicalName()); } if (value instanceof Comparable<?>) { this.insert(name, value); // estimate only, put 512 byte here this.estimate_size_in_bytes += 512; return this; } else { throw new IllegalArgumentException(value.getClass().getCanonicalName() + " doesn't implement " + Comparable.class.getCanonicalName()); } }
From source file:org.alfresco.repo.content.metadata.AbstractMappingMetadataExtracter.java
/** * Adds a value to the map, conserving null values. Values are converted to null if: * <ul>/* w w w .j a v a 2 s . c om*/ * <li>it is an empty string value after trimming</li> * <li>it is an empty collection</li> * <li>it is an empty array</li> * </ul> * String values are trimmed before being put into the map. * Otherwise, it is up to the extracter to ensure that the value is a <tt>Serializable</tt>. * It is not appropriate to implicitly convert values in order to make them <tt>Serializable</tt> * - the best conversion method will depend on the value's specific meaning. * * @param key the destination key * @param value the serializable value * @param destination the map to put values into * @return Returns <tt>true</tt> if set, otherwise <tt>false</tt> */ protected boolean putRawValue(String key, Serializable value, Map<String, Serializable> destination) { if (value == null) { // Just keep this } else if (value instanceof String) { String valueStr = ((String) value).trim(); if (valueStr.length() == 0) { value = null; } else { if (valueStr.indexOf("\u0000") != -1) { valueStr = valueStr.replaceAll("\u0000", ""); } // Keep the trimmed value value = valueStr; } } else if (value instanceof Collection) { Collection<?> valueCollection = (Collection<?>) value; if (valueCollection.isEmpty()) { value = null; } } else if (value.getClass().isArray()) { if (Array.getLength(value) == 0) { value = null; } } // It passed all the tests destination.put(key, value); return true; }
From source file:org.sakaiproject.evaluation.dao.EvaluationDaoImpl.java
/** * This really does not work for most cases so be very careful with it * @param object//from w w w . j ava 2 s . co m */ protected void forceEvict(Serializable object) { boolean active = false; try { Session session = currentSession(); if (session.isOpen() && session.isConnected()) { if (session.contains(object)) { active = true; session.evict(object); } } else { LOG.warn("Session is not open OR not connected, cannot evict objects"); } if (!active) { LOG.info("Unable to evict object (" + object.getClass().getName() + ") from session, it is not persistent: " + object); } } catch (DataAccessResourceFailureException | IllegalStateException | HibernateException e) { LOG.warn("Failure while attempting to evict object (" + object.getClass().getName() + ") from session", e); } }
From source file:org.nuxeo.ecm.core.storage.sql.Mapper.java
/** * Returns a loggable value using pseudo-SQL syntax. *//*from ww w .j a va 2s .co m*/ @SuppressWarnings("boxing") private static String loggedValue(Serializable value) { if (value == null) { return "NULL"; } if (value instanceof String) { String v = (String) value; if (v.length() > DEBUG_MAX_STRING) { v = v.substring(0, DEBUG_MAX_STRING) + "...(" + v.length() + " chars)..."; } return "'" + v.replace("'", "''") + "'"; } if (value instanceof Calendar) { Calendar cal = (Calendar) value; char sign; int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis()) / 60000; if (offset < 0) { offset = -offset; sign = '-'; } else { sign = '+'; } return String.format("TIMESTAMP '%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d'", cal.get(Calendar.YEAR), // cal.get(Calendar.MONTH) + 1, // cal.get(Calendar.DAY_OF_MONTH), // cal.get(Calendar.HOUR_OF_DAY), // cal.get(Calendar.MINUTE), // cal.get(Calendar.SECOND), // cal.get(Calendar.MILLISECOND), // sign, offset / 60, offset % 60); } if (value instanceof Binary) { return "'" + ((Binary) value).getDigest() + "'"; } if (value.getClass().isArray()) { Serializable[] v = (Serializable[]) value; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; i < v.length; i++) { if (i > 0) { b.append(','); if (i > DEBUG_MAX_ARRAY) { b.append("...(" + v.length + " items)..."); break; } } b.append(loggedValue(v[i])); } b.append(']'); return b.toString(); } return value.toString(); }
From source file:de.dal33t.powerfolder.util.ByteSerializer.java
/** * Serialize an object. This method is non-static an re-uses the internal * byteoutputstream// ww w . jav a 2 s. c o m * * @param target * The object to be serialized * @param compress * true if serialization should compress. * @param padToSize * the size to pad the output buffer to. number below 0 means no * padding. * @return The serialized object * @throws IOException * In case the object cannot be serialized */ public byte[] serialize(Serializable target, boolean compress, int padToSize) throws IOException { long start = System.currentTimeMillis(); ByteArrayOutputStream byteOut; // Reset buffer if (outBufferRef != null && outBufferRef.get() != null) { // Reuse old buffer byteOut = outBufferRef.get(); byteOut.reset(); } else { // logFiner("Creating send buffer (512bytes)"); // Create new bytearray output, 512b buffer byteOut = new ByteArrayOutputStream(512); if (CACHE_OUT_BUFFER) { // Chache outgoing buffer outBufferRef = new SoftReference<ByteArrayOutputStream>(byteOut); } } OutputStream targetOut; // Serialize.... if (compress) { PFZIPOutputStream zipOut = new PFZIPOutputStream(byteOut); targetOut = zipOut; } else { targetOut = byteOut; } ObjectOutputStream objOut = new ObjectOutputStream(targetOut); // Write try { objOut.writeUnshared(target); } catch (StreamCorruptedException e) { LOG.log(Level.WARNING, "Problem while serializing: " + e, e); throw e; } catch (InvalidClassException e) { LOG.log(Level.WARNING, "Problem while serializing: " + target + ": " + e, e); throw e; } objOut.close(); if (padToSize > 0) { int modulo = byteOut.size() % padToSize; if (modulo != 0) { int additionalBytesRequired = padToSize - (modulo); // LOG.warn("Buffersize: " + byteOut.size() // + ", Additonal bytes required: " + additionalBytesRequired); for (int i = 0; i < additionalBytesRequired; i++) { byteOut.write(0); } } } byteOut.flush(); byteOut.close(); if (byteOut.size() >= 256 * 1024) { logWarning("Send buffer exceeds 256KB! " + Format.formatBytes(byteOut.size()) + ". Message: " + target); } byte[] buf = byteOut.toByteArray(); if (BENCHMARK) { totalObjects++; totalTime += System.currentTimeMillis() - start; int count = 0; if (CLASS_STATS.containsKey(target.getClass())) { count = CLASS_STATS.get(target.getClass()); } count++; CLASS_STATS.put(target.getClass(), count); } return buf; }
From source file:org.openbaton.sdk.api.util.RestRequest.java
/** * Executes a http put with to a given id, while serializing the object content as json and * returning the response//from ww w.j av a 2 s .c om * * @param id the id path used for the api request * @param object the object content to be serialized as json * @return a string containing the response content */ public Serializable requestPut(final String id, final Serializable object) throws SDKException { CloseableHttpResponse response = null; HttpPut httpPut = null; try { log.trace("Object is: " + object); String fileJSONNode = mapper.toJson(object); try { checkToken(); } catch (IOException e) { log.error(e.getMessage(), e); throw new SDKException("Could not get token", e); } // call the api here log.debug("Executing put on: " + this.baseUrl + "/" + id); httpPut = new HttpPut(this.baseUrl + "/" + id); httpPut.setHeader(new BasicHeader("accept", "application/json")); httpPut.setHeader(new BasicHeader("Content-Type", "application/json")); httpPut.setHeader(new BasicHeader("project-id", projectId)); if (token != null) httpPut.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", ""))); httpPut.setEntity(new StringEntity(fileJSONNode)); response = httpClient.execute(httpPut); // check response status checkStatus(response, HttpURLConnection.HTTP_ACCEPTED); // return the response of the request String result = ""; if (response.getEntity() != null) result = EntityUtils.toString(response.getEntity()); if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { response.close(); httpPut.releaseConnection(); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(result); result = mapper.toJson(jsonElement); log.trace("received: " + result); log.trace("Casting it into: " + object.getClass()); return mapper.fromJson(result, object.getClass()); } response.close(); httpPut.releaseConnection(); return null; } catch (IOException e) { // catch request exceptions here log.error(e.getMessage(), e); if (httpPut != null) httpPut.releaseConnection(); throw new SDKException("Could not http-put or the api response was wrong or open the object properly", e); } catch (SDKException e) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { token = null; if (httpPut != null) httpPut.releaseConnection(); return requestPut(id, object); } else { if (httpPut != null) httpPut.releaseConnection(); throw new SDKException( "Could not http-put or the api response was wrong or open the object properly", e); } } finally { if (httpPut != null) httpPut.releaseConnection(); } }
From source file:it.doqui.index.ecmengine.business.job.backup.MetaDataBackupJob.java
private void generaXmlMetaDati(NodeRef nodeRef, Map<QName, Serializable> propertyMap) throws JiBXException, FileNotFoundException, DictionaryRuntimeException { logger.debug("[MetaDatiManager::generaXmlMetaDati] BEGIN"); String nomeFile;/*from w w w .j av a 2 s. com*/ //String folderFileMetaDati = "/usr/prod/fs/alfresco2/metadati"; //contentDir //dir.contenstore = /usr/prod/fs/alfresco2/content/contentstore String folderContent = this.contentDir; logger.debug("[MetaDatiManager::generaXmlMetaDati] Directory Contenuti: " + folderContent); try { nomeFile = nodeRef.getId() + ".xml"; logger.debug("[MetaDatiManager::generaXmlMetaDati] Nome file xml da ricercare : " + nomeFile); String urlRelative = getContentUrl(propertyMap); if (urlRelative != null) { // Se il file xml dei metadati deve essere memorizzato nella stessa cartella dove e` memorizzato // il content ,allora bisogna individiare il path dove tale content e` memorizzato e controllare se // il file xml e` presente o no in questa cartella; urlRelative contiene il path relativo // del content; bisogna sapere il path fisico su fs di partenza che e` contenuto nel file di property // custom-data-location.properties logger.debug("[MetaDatiManager::generaXmlMetaDati] Path relativo content : " + urlRelative); // store://2007/11/14/14/5/53d84b63-92b2-11dc-bd5f-372cc7f30666.bin // /usr/prod/fs/alfresco2/content/contentstore/2007/11/14/14/5 // store:/ urlRelative = urlRelative.substring(7); logger.debug("[MetaDatiManager::generaXmlMetaDati] Url relativo senza store: " + urlRelative); // /usr/prod/fs/alfresco2/content/contentstore/2007/11/14/14/5/53d84b63-92b2-11dc-bd5f-372cc7f30666.bin folderContent = folderContent + urlRelative; logger.debug("[MetaDatiManager::generaXmlMetaDati] Url comprensivo del binario : " + folderContent); int idLength = nodeRef.getId().length() + 4; int l = folderContent.length(); l = l - idLength; folderContent = folderContent.substring(0, l); // /usr/prod/fs/alfresco2/content/contentstore/2007/11/14/14/5/ logger.debug("[MetaDatiManager::generaXmlMetaDati] Path cartella content : " + folderContent); } else { logger.debug("[MetaDatiManager::generaXmlMetaDati] Il content modificato non e' un documento"); logger.debug("[MetaDatiManager::generaXmlMetaDati] Esco dal Job di backup"); return; } boolean creato = false; final File file = new File(folderContent); if (!file.exists()) { file.mkdir(); } if (file.isDirectory()) { final File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (nomeFile.equalsIgnoreCase(files[i].getName())) { creato = true; logger.debug("[MetaDatiManager::generaXmlMetaDati] File xml gia creato."); break; } } } final IBindingFactory factory = BindingDirectory.getFactory(MetaDati.class); IMarshallingContext mctx = null; MetaDati metaDati = null; MetaDatiOggettoValore oggetto = null; MetaDatiAutoreValore autore = null; final String path = folderContent + nomeFile; if (!creato) { //file xml dei metadati per il nodo in esame deve ancora essere creato logger.debug("[MetaDatiManager::generaXmlMetaDati] File xml da generare"); mctx = factory.createMarshallingContext(); mctx.setIndent(1); metaDati = new MetaDati(); //Ciclo sulle proprieta` for (Map.Entry<QName, Serializable> entry : propertyMap.entrySet()) { final QName propName = entry.getKey(); final Serializable valore = entry.getValue(); PropertyDefinition propDef = this.dictionaryService.getProperty(propName); if (logger.isDebugEnabled()) { logger.debug( "[MetaDatiManager::generaXmlMetaDati] Nome Proprieta : " + propName.toString()); logger.debug("[MetaDatiManager::generaXmlMetaDati] Valore Proprieta : " + (valore != null ? valore.toString() : "null")); } //MetaDatiAutoreValore valoreAutore = null; //MetaDatiOggettoValore valoreOggetto = null; if (propDef.isMultiValued()) { //valore multiplo logger.debug("[MetaDatiManager::generaXmlMetaDati] Property multivalue"); String[] values = null; String value = null; if (valore instanceof Collection<?>) { final Collection<?> valuesCollection = (Collection<?>) valore; values = new String[valuesCollection.size()]; int j = 0; for (Object o : valuesCollection) { values[j] = o.toString(); j++; } } else { value = "Type not supported: " + valore.getClass().getName(); logger.debug("[MetaDatiManager::generaXmlMetaDati] " + value); } if ("side-doc:autore".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { if (values != null) { for (int i = 0; i < values.length; i++) { autore = new MetaDatiAutoreValore(); autore.setCognome(values[i]); autore.setNome(values[i]); autore.setDataInizio(new Date()); metaDati.addAutore(autore); } } else { autore = new MetaDatiAutoreValore(); autore.setCognome("Type not supported"); autore.setNome("Type not supported"); autore.setDataInizio(new Date()); metaDati.addAutore(autore); } } else if ("cm:name".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { logger.debug("[MetaDatiManager::generaXmlMetaDati] Property cm:name multivalue"); if (values != null) { for (int i = 0; i < values.length; i++) { oggetto = new MetaDatiOggettoValore(); oggetto.setCampo(values[i]); oggetto.setDataInizio(new Date()); metaDati.addOggetto(oggetto); } } else { oggetto = new MetaDatiOggettoValore(); oggetto.setCampo("Type not supported"); oggetto.setDataInizio(new Date()); metaDati.addOggetto(oggetto); } } } else { //singolo valore logger.debug("[MetaDatiManager::generaXmlMetaDati] Property single value"); if ("side-doc:oggetto".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { oggetto = new MetaDatiOggettoValore(); if (valore == null) { oggetto.setCampo("- null -"); oggetto.setDataInizio(new Date()); } else if (valore instanceof String || valore instanceof Long || valore instanceof Integer || valore instanceof Date || valore instanceof MLText || valore instanceof ContentData || valore instanceof Boolean || valore instanceof NodeRef) { oggetto.setCampo(valore.toString()); oggetto.setDataInizio(new Date()); } else { oggetto.setCampo("Type not supported: " + valore.getClass().getName()); oggetto.setDataInizio(new Date()); } metaDati.addOggetto(oggetto); } else { if ("cm:name".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { logger.debug( "[MetaDatiManager::generaXmlMetaDati] " + "Property cm:name single value"); oggetto = new MetaDatiOggettoValore(); if (valore == null) { oggetto.setCampo("- null -"); oggetto.setDataInizio(new Date()); } else if (valore instanceof String || valore instanceof Long || valore instanceof Integer || valore instanceof Date || valore instanceof MLText || valore instanceof ContentData || valore instanceof Boolean || valore instanceof NodeRef) { oggetto.setCampo(valore.toString()); logger.debug("[MetaDatiManager::generaXmlMetaDati] " + "Property cm:name --> value : " + valore.toString()); oggetto.setDataInizio(new Date()); } else { oggetto.setCampo("Type not supported: " + valore.getClass().getName()); oggetto.setDataInizio(new Date()); } metaDati.addOggetto(oggetto); } else if ("sys:node-uuid".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { logger.debug("[MetaDatiManager::generaXmlMetaDati] " + "Property sys:node-uuid single value"); oggetto = new MetaDatiOggettoValore(); if (valore == null) { oggetto.setCampo("- null -"); oggetto.setDataInizio(new Date()); } else if (valore instanceof String || valore instanceof Long || valore instanceof Integer || valore instanceof Date || valore instanceof MLText || valore instanceof ContentData || valore instanceof Boolean || valore instanceof NodeRef) { oggetto.setCampo(valore.toString()); logger.debug("[MetaDatiManager::generaXmlMetaDati] " + "Property sys:node-uuid --> valore : " + valore.toString()); oggetto.setDataInizio(new Date()); } else { oggetto.setCampo("Type not supported: " + valore.getClass().getName()); oggetto.setDataInizio(new Date()); } metaDati.addOggetto(oggetto); } } } } mctx.marshalDocument(metaDati, "UTF-8", null, new FileOutputStream(path)); logger.debug("[MetaDatiManager::generaXmlMetaDati] Marshall file xml : " + path); } else { logger.debug("[MetaDatiManager::generaXmlMetaDati] File xml gia` creato, devo prima leggerlo"); final IUnmarshallingContext uctx = factory.createUnmarshallingContext(); final Object obj = uctx.unmarshalDocument(new FileInputStream(path), null); if (obj instanceof MetaDati) { logger.debug( "[MetaDatiManager::generaXmlMetaDati] OK : obj e' un'istanza della classe MetaDati"); metaDati = (MetaDati) obj; for (Map.Entry<QName, Serializable> entry : propertyMap.entrySet()) { final QName propName = entry.getKey(); final Serializable valore = entry.getValue(); PropertyDefinition propDef = dictionaryService.getProperty(propName); if (logger.isDebugEnabled()) { logger.debug( "[MetaDatiManager::generaXmlMetaDati] Nome Proprieta`: " + propName.toString()); logger.debug("[MetaDatiManager::generaXmlMetaDati] Valore Proprieta`: " + ((valore != null) ? valore.toString() : "null")); } if (propDef.isMultiValued()) { //multi value logger.debug("[MetaDatiManager::generaXmlMetaDati] property multivalue"); String[] values = null; String value = null; if (valore instanceof Collection<?>) { Collection<?> valuesCollection = (Collection<?>) valore; values = new String[valuesCollection.size()]; int j = 0; for (Object o : valuesCollection) { values[j] = o.toString(); j++; } } else { value = "Type not supported: " + valore.getClass().getName(); logger.debug("[MetaDatiManager::generaXmlMetaDati] " + value); } if ("side-doc:autore".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { if (values != null) { for (int i = 0; i < values.length; i++) { autore = new MetaDatiAutoreValore(); autore.setCognome(values[i]); autore.setNome(values[i]); autore.setDataInizio(new Date()); metaDati.addAutore(autore); } } else { autore = new MetaDatiAutoreValore(); autore.setCognome("Type not supported"); autore.setNome("Type not supported"); autore.setDataInizio(new Date()); metaDati.addAutore(autore); } } else if ("cm:name".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { logger.debug("[MetaDatiManager::generaXmlMetaDati] Property cm:name multivalue"); if (values != null) { for (int i = 0; i < values.length; i++) { oggetto = new MetaDatiOggettoValore(); oggetto.setCampo(values[i]); oggetto.setDataInizio(new Date()); metaDati.addOggetto(oggetto); } } else { oggetto = new MetaDatiOggettoValore(); oggetto.setCampo("Type not supported"); oggetto.setDataInizio(new Date()); metaDati.addOggetto(oggetto); } } } else { //single value logger.debug("[MetaDatiManager::generaXmlMetaDati] property single value"); if ("side-doc:oggetto".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { oggetto = new MetaDatiOggettoValore(); if (valore == null) { oggetto.setCampo("- null -"); oggetto.setDataInizio(new Date()); } else if (valore instanceof String || valore instanceof Long || valore instanceof Integer || valore instanceof Date || valore instanceof MLText || valore instanceof ContentData || valore instanceof Boolean || valore instanceof NodeRef) { oggetto.setCampo(valore.toString()); oggetto.setDataInizio(new Date()); } else { oggetto.setCampo("Type not supported: " + valore.getClass().getName()); oggetto.setDataInizio(new Date()); } metaDati.addOggetto(oggetto); } else { if ("cm:name".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { logger.debug("[MetaDatiManager::generaXmlMetaDati] Property cm:name " + "single value"); oggetto = new MetaDatiOggettoValore(); if (valore == null) { oggetto.setCampo("- null -"); oggetto.setDataInizio(new Date()); } else if (valore instanceof String || valore instanceof Long || valore instanceof Integer || valore instanceof Date || valore instanceof MLText || valore instanceof ContentData || valore instanceof Boolean || valore instanceof NodeRef) { oggetto.setCampo(valore.toString()); oggetto.setDataInizio(new Date()); logger.debug("[MetaDatiManager::generaXmlMetaDati] " + "Property cm:name --> value : " + valore.toString()); } else { oggetto.setCampo("Type not supported: " + valore.getClass().getName()); oggetto.setDataInizio(new Date()); } metaDati.addOggetto(oggetto); } else if ("sys:node-uuid".equalsIgnoreCase(resolveQNameToPrefixName(propName))) { logger.debug("[MetaDatiManager::generaXmlMetaDati] Property sys:node-uuid"); oggetto = new MetaDatiOggettoValore(); if (valore == null) { oggetto.setCampo("- null -"); oggetto.setDataInizio(new Date()); } else if (valore instanceof String || valore instanceof Long || valore instanceof Integer || valore instanceof Date || valore instanceof MLText || valore instanceof ContentData || valore instanceof Boolean || valore instanceof NodeRef) { oggetto.setCampo(valore.toString()); logger.debug("[MetaDatiManager::generaXmlMetaDati] " + "Property sys:node-uuid --> valore : " + valore.toString()); oggetto.setDataInizio(new Date()); } else { oggetto.setCampo("Type not supported: " + valore.getClass().getName()); oggetto.setDataInizio(new Date()); } metaDati.addOggetto(oggetto); } } } } mctx = factory.createMarshallingContext(); mctx.setIndent(1); mctx.marshalDocument(metaDati, "UTF-8", null, new FileOutputStream(path)); logger.debug("[MetaDatiManager::generaXmlMetaDati] Marshall file xml : " + path); } else { logger.error("[MetaDatiManager::generaXmlMetaDati] Errore :" + " obj non e` una istanza della classe Metadati"); throw new JiBXException( "UnmarshalDocument Errato: " + "obj non e' una istanza della classe Metadati"); } } } finally { logger.debug("[MetaDatiManager::generaXmlMetaDati] END"); } }