Alfresco: Stream is already closed - alfresco

I am trying to create text document using apache-chemistry in alfresco. My code is for creating document is
Document document = FileUtils.createTextDocument("/", "test.txt", "test document", BaseTypeId.CMIS_DOCUMENT.value(), VersioningState.MAJOR, session);
when I execute my code I am getting following exception
org.apache.chemistry.opencmis.commons.exceptions.CmisConnectionException: Cannot access "http://localhost:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom/children?id=5717e8a0-61b2-4bcb-8a91-2f4b61ebfefa&versioningState=major": Stream is already closed!
at org.apache.chemistry.opencmis.client.bindings.spi.http.DefaultHttpInvoker.invoke(DefaultHttpInvoker.java:233)
at org.apache.chemistry.opencmis.client.bindings.spi.http.DefaultHttpInvoker.invokePOST(DefaultHttpInvoker.java:68)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.post(AbstractAtomPubService.java:713)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.ObjectServiceImpl.createDocument(ObjectServiceImpl.java:122)
at org.apache.chemistry.opencmis.client.runtime.SessionImpl.createDocument(SessionImpl.java:1165)
at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImpl.java:77)
at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImpl.java:460)
at org.apache.chemistry.opencmis.client.util.FileUtils.createTextDocument(FileUtils.java:168)

Try this worked fine for me
public static void main(String args[]) {
String serverUrl = args[0];
String username = args[1];
String password = args[2];
Session session = getSession(serverUrl, username, password);
Folder root = session.getRootFolder();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_
DOCUMENT.value());
String name = "New Document (" + System.currentTimeMillis() +
").txt";
properties.put(PropertyIds.NAME, name);
List<Ace> addAces = new LinkedList<Ace>();
List<Ace> removeAces = new LinkedList<Ace>();
List<Policy> policies = new LinkedList<Policy>();
String content = "The quick brown fox jumps over the lazy dog.";
ContentStream contentStream = new ContentStreamImpl("text.txt",
BigInteger.valueOf(content.length()),
"text/plain", new ByteArrayInputStream(content.
getBytes()));
Document newDocument = root.createDocument(properties,
contentStream, VersioningState.MAJOR, policies, addAces, removeAces,
session.getDefaultContext());
System.out.println(newDocument.getId());
}

Related

How to change "to-reply" property of email in alfresco

I am able to send emails in alfresco using Java API but I am not able to change the "Reply-to: " property like this in alfresco :
Message replyMessage = new MimeMessage(session);
replyMessage = (MimeMessage) message.reply(false);
replyMessage.setFrom(new InternetAddress(to));
replyMessage.setText("Thanks");
replyMessage.setReplyTo(message.getReplyTo());
replyMessage.setReplyTo(message.getReplyTo());
This is my code to send emails
NodeRef companyHome = repository.getCompanyHome();
List<String> pathElements = new ArrayList<>();
pathElements.add("Data Dictionary");
pathElements.add("Email Templates");
pathElements.add("Trams Email Templates");
pathElements.add("CONTENT_NOTIFICATION.html.ftl");
FileInfo templateFile;
try {
templateFile = serviceRegistry.getFileFolderService()
.resolveNamePath(companyHome, pathElements);
NodeRef template = templateFile.getNodeRef();
List<String> users = new ArrayList<String>();
users.add(userName);
ActionService actionService = serviceRegistry.getActionService();
Action mailAction = actionService.createAction(MailActionExecuter.NAME);
mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, template);
Map<String, Serializable> templateArgs = new HashMap<String, Serializable>();
templateArgs.put("userName", userName);
Map<String, Serializable> templateModel = new HashMap<String, Serializable>();
templateModel.put("args",(Serializable)templateArgs);
mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL,(Serializable)templateModel);
mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Content Notification");
mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, (Serializable) users);
actionService.executeAction(mailAction, null);
} catch (org.alfresco.service.cmr.model.FileNotFoundException e) {
e.printStackTrace();
}
Is there any way to enable this replyTo parameter in alfresco ?
Please help.
I have override the OOTB MailActionExecuter class.
added my code to set the replyTo parameter
I fixed parameter from java class mailAction.setParameterValue(MailActionExecuter.PARAM_REPLY_TO,"myEmail#gmail.com");
and access using
public static final String PARAM_REPLY_TO = "reply_to";
message.setReplyTo(replyTo);

Saving/Accesing Internal Storage, Sony Android TV

I'm trying to save a xml document programmatically inside the Internal Storage of my Sony Android TV. I will also later on will need to accecss this file. Is it even possible to do and how should I approach this? Any suggestions or solutions?
Code:
public class xmlCreateFile {
Boolean finished = false;
String TAG = "xmlCreateFile";
public Boolean xmlCreate(){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
StreamResult result = new StreamResult(path +"/file.xml");
Log.d(TAG,"Env: " + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS));
//Output to console for testing
StreamResult result2 = new StreamResult(System.out);
// transformer.transform(source, result);
transformer.transform(source, result2);
finished = true;
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
return finished;
}
}
There are a number of ways to store data on a device. It seems like you only need this information to be visible to your app, so you can use the private Internal Storage APIs.
These APIs make it relatively easy to store and retrieve a file. Here's a short example.
// Save a file
String FILENAME = "textfile.txt";
String writeString = "hello world!";
FileOutputStream fos = getActivity().openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(writeString.getBytes());
fos.close();
// Read file
FileInputStream fis = getActivity().openFileInput(FILENAME);
StringBuilder builder = new StringBuilder();
int inputChar;
while((inputChar = fis.read()) != -1) {
builder.append((char) inputChar);
}
fis.close();
String readString = builder.toString();

Object Reference Not Set to Instance of an Object in Google Cloud Loadobject

`loadconfig.SourceUris.Add(#"gs:\\planar-fulcrum-837\leadload-ip\01-
02-2013");`
Null object reference set to instance of an object
Here is the working sample for loading CSV file from cloud storage into Google Big Query.
Update variables such as "ServiceAccountEmail, KeyFileName, KeySecret, ProjectID, Dataset name and etc..
Add your table schema into this variable
TableSchema Schema = new TableSchema();
Here i am using single file loading, you can add N number of CSV file into this variable
System.Collections.Generic.IList<string> URIs = newSystem.Collections.Generic.List<string>();
URIs.Add(filePath);
Use this below code modify & work with it. Have a great day. (This solution i have found working more than 3 days).
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
using System.Security.Cryptography.X509Certificates;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
try
{
String serviceAccountEmail = "SERVICE ACCOUNT EMAIL";
var certificate = new X509Certificate2(#"KEY FILE NAME & PATH", "KEY SECRET", X509KeyStorageFlags.Exportable);
// SYNTAX: var certificate=new X509Certificate2(KEY FILE PATH+NAME (Here it resides in Bin\Debug folder so only name is enough), SECRET KEY, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { BigqueryService.Scope.Bigquery, BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.CloudPlatform, BigqueryService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
// Create and initialize the Bigquery service. Use the Project Name value
// from the New Project window for the ApplicationName variable.
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "APPLICATION NAME"
});
TableSchema Schema = new TableSchema();
TableFieldSchema F1 = new TableFieldSchema();
F1.Name = "COLUMN NAME";
F1.Type = "STRING";
F1.Mode = "REQUIRED";
TableFieldSchema F2 = new TableFieldSchema();
F1.Name = "COLUMN NAME";
F1.Type = "INTEGER";
F1.Mode = "NULLABLE";
//Add N number of fields as per your needs
System.Collections.Generic.IList<TableFieldSchema> FS = new System.Collections.Generic.List<TableFieldSchema>();
FS.Add(F1);
FS.Add(F2);
Schema.Fields = FS;
JobReference JR = JobUpload("PROJECT ID", "DATASET NAME", "TABLE NAME", #"gs://BUCKET NAME/FILENAME", Schema, "CREATE_IF_NEEDED", "WRITE_APPEND", '|', Service);
//SYNTAX JobReference JR = JobUpload(PROJECT ID, DATASET NAME, TABLE NAME, FULL PATH OF CSV FILE,FILENAME IN CLOUD STORAGE, TABLE SCHEMA, CREATE DISPOSITION, DELIMITER, BIGQUERY SERVICE);
while (true)
{
var PollJob = Service.Jobs.Get(JR.ProjectId, JR.JobId).Execute();
Console.WriteLine("Job status" + JR.JobId + ": " + PollJob.Status.State);
if (PollJob.Status.State.Equals("DONE"))
{
Console.WriteLine("JOB Completed");
Console.ReadLine();
return;
}
}
}
catch (Exception e)
{
Console.WriteLine("Error Occurred: " + e.Message);
}
Console.ReadLine();
}
public static JobReference JobUpload(string project, string dataset, string tableId, string filePath, TableSchema schema, string createDisposition, string writeDisposition, char delimiter, BigqueryService BigQueryService)
{
TableReference DestTable = new TableReference();
DestTable.ProjectId = project;
DestTable.DatasetId = dataset;
DestTable.TableId = tableId;
Job Job = new Job();
JobConfiguration Config = new JobConfiguration();
JobConfigurationLoad ConfigLoad = new JobConfigurationLoad();
ConfigLoad.Schema = schema;
ConfigLoad.DestinationTable = DestTable;
ConfigLoad.Encoding = "ISO-8859-1";
ConfigLoad.CreateDisposition = createDisposition;
ConfigLoad.WriteDisposition = writeDisposition;
ConfigLoad.FieldDelimiter = delimiter.ToString();
ConfigLoad.AllowJaggedRows = true;
ConfigLoad.SourceFormat = "CSV";
ConfigLoad.SkipLeadingRows = 1;
ConfigLoad.MaxBadRecords = 100000;
System.Collections.Generic.IList<string> URIs = new System.Collections.Generic.List<string>();
URIs.Add(filePath);
//You can add N number of CSV Files here
ConfigLoad.SourceUris = URIs;
Config.Load = ConfigLoad;
Job.Configuration = Config;
//set job reference (mainly job id)
JobReference JobRef = new JobReference();
Random r = new Random();
var JobNo = r.Next();
JobRef.JobId = "Job" + JobNo.ToString();
JobRef.ProjectId = project;
Job.JobReference = JobRef;
JobsResource.InsertRequest InsertMediaUpload = new JobsResource.InsertRequest(BigQueryService, Job, Job.JobReference.ProjectId);
var JobInfo = InsertMediaUpload.Execute();
return JobRef;
}
}
}

Problems while trying to add an xml file to Alfresco

Am facing an issue with Alfresco and honestly am not expert with this type of technology:
the idea is to add an xml file under a folder
the code is like that:
//with the static values are:
public static final String SUSPENDRE_DESUSPENDRE_CONTENT_NAME = "suspendreDesuspendre";
private static final String SUSPENDRE_DESUSPENDRE_CONTENT_TYPE = "text/xml";
private static final String SUSPENDRE_DESUSPENDRE_CONTENT_ENCODING = "UTF-8";
private static final ContentFormat SUSPENDRE_DESUSPENDRE_CONTENT_FORMAT = new ContentFormat(SUSPENDRE_DESUSPENDRE_CONTENT_TYPE,SUSPENDRE_DESUSPENDRE_CONTENT_ENCODING);
private static final byte[] SUSPENDRE_DESUSPENDRE_CONTENT_INITIAL_BYTES = "<?xml //version=\"1.0\" encoding=\"UTF-8\"?><suspendreDesuspendre></suspendreDesuspendre>".getBytes();
#Override
public void createOrUpdateHisSuspendre(ContractBean contractbean,SuspendreDesuspendreEntree suspendreDesuspendreEntree) throws Exception
{
String parentUuid=contractbean.getUuid();
contractDAO.createAlfrescoContent(parentUuid, SUSPENDRE_DESUSPENDRE_CONTENT_NAME, SUSPENDRE_DESUSPENDRE_CONTENT_INITIAL_BYTES, SUSPENDRE_DESUSPENDRE_CONTENT_FORMAT);
}
public Reference createAlfrescoContent(String folderUuid, String contentName,byte[] contentBytes,ContentFormat contentFormat)throws RepositoryFault, RemoteException {
ParentReference parentReference = new ParentReference(new Store(Constants.WORKSPACE_STORE, "SpacesStore"), folderUuid, null, Constants.ASSOC_CONTAINS, "{" + Constants.NAMESPACE_CONTENT_MODEL + "}" + contentName);
NamedValue[] properties = new NamedValue[]{Utils.createNamedValue(Constants.PROP_NAME, contentName)};
CMLCreate create = new CMLCreate("1", parentReference, null, null, null,
Constants.TYPE_CONTENT, properties);
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
Reference newContentNode = result[0].getDestination();
Content content = WebServiceFactory.getContentService().write(newContentNode, Constants.PROP_CONTENT, contentBytes, contentFormat);
return content.getNode();
}
the error is:
The association source type is incorrect:
Source Node: workspace://SpacesStore/d4ffbff4-6bd6-4945-948e-2c16c1990cb9
Association: Association[ class=ClassDef[name={http://www.alfresco.org/model/content/1.0}folder], name={http://www.alfresco.org/model/content/1.0}contains, target class={http://www.alfresco.org/model/system/1.0}base, source role=null, target role=null]
Required Source Type: {http://www.alfresco.org/model/content/1.0}folder
Actual Source Type: {com.genia.cnas.alfresco.model}contratDefenseur

Java mail getInputStream left recipient

i'm writing a mail send method with javamail.
I can not understand why I get and error as: Recipient not set.
This is my code:
public static void sendMail(String to, String subj, String body, String attachmentName, byte[] attachment, String mime) throws Exception {
Properties p = System.getProperties();
Session session = Session.getInstance(p);
MimeMessage dummyMessage = new MimeMessage(session);
dummyMessage.setFrom(new InternetAddress(LovProvider.getOpzioni().get("mail.address")));
dummyMessage.setSubject(subj);
String[] tos = to.split(";");
Address[] tosAddr = new InternetAddress[tos.length];
for (int i = 0; i < tos.length; i++) {
tosAddr[i] = new InternetAddress(tos[i]);
}
dummyMessage.setRecipients(Message.RecipientType.TO, tosAddr);
Multipart mp = new MimeMultipart();
MimeBodyPart bp = new MimeBodyPart();
bp.setText(body);
mp.addBodyPart(bp);
if (attachmentName != null && attachment != null) {
DataSource dataSource = new ByteArrayDataSource(attachment, mime);
MimeBodyPart attachBodyPart = new MimeBodyPart();
attachBodyPart.setDataHandler(new DataHandler(dataSource));
attachBodyPart.setFileName(attachmentName);
mp.addBodyPart(attachBodyPart);
}
dummyMessage.setContent(mp);
//***** DEBUGGING here I find the recipient
sendMail(dummyMessage.getInputStream());
}
public static void sendMail(InputStream emlFile) throws Exception {
Properties props = System.getProperties();
props.put("mail.host", LovProvider.getOpzioni().get("mail.out.host"));
props.put("mail.transport.protocol", LovProvider.getOpzioni().get("mail.out.protocol"));
props.put("mail." + LovProvider.getOpzioni().get("mail.out.protocol") + ".port", LovProvider.getOpzioni().get("mail.out.port"));
Session mailSession = Session.getDefaultInstance(props, PasswordAuthentication.getAuth(LovProvider.getOpzioni().get("mail.out.user"), LovProvider.getOpzioni().get("mail.out.password")));
MimeMessage message = new MimeMessage(mailSession, emlFile);
//***** DEBUGGING here I CAN NOT find the recipient
Transport.send(message);
}
As I wrote in comments in debug mode i can see the recipient correctly set in the first part, whant i convert it to InputStream to the second method I can not find recipient anymore.
I can't debugging your code, but maybe this examples can help you:
Examples about sending/receiving mail via/from gmail
http://famulatus.com/component/search/?searchword=gmail&searchphrase=all&Itemid=9999

Resources