I work with alfresco 4.0
I have a problem to save document in special space in alfresco named in arabic language.
for this example I didn't have problem :
/app:company_home/cm:تجربة
but I have problem when the space witch is created in alfresco is named in arabic language and have blank character . like this :
/app:company_home/cm:تجربة ثانية
in this case I can't save document in alfresco
updated :
also I have the same problem when I have a folder named in english and have escape character like this :
His Excellency the Secretary
Reporter Secretariat
this is the document to save document in alfresco
public String saveDocument(File file, String name, String folderName, String userName, String pwd, String code)
throws Exception {
File file_BC = file;
try {
BarCodeEngine barCodeEngine = new BarCodeEngine(file, code);
file_BC = barCodeEngine.setBarCode();
} catch (Exception e) {
e.printStackTrace();
}
byte[] contentByte = IOUtils.toByteArray(new FileInputStream(file_BC));
// Start the session
AuthenticationUtils.startSession(userName, pwd);
try {
// Create a reference to the parent where we want to create content
Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
ParentReference companyHomeParent = new ParentReference(storeRef, null, folderName, Constants.ASSOC_CONTAINS, null);
// Assign name
companyHomeParent.setChildName("cm:" + name);
// Construct CML statement to create content node
// Note: Assign "1" as a local id, so we can refer to it in subsequent
// CML statements within the same CML block
NamedValue[] contentProps = new NamedValue[1];
contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, name);
CMLCreate create = new CMLCreate("1", companyHomeParent, null, null, null, Constants.TYPE_CONTENT, contentProps);
// Construct CML statement to add titled aspect
NamedValue[] titledProps = new NamedValue[2];
titledProps[0] = Utils.createNamedValue(Constants.PROP_TITLE, name);
titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, name);
CMLAddAspect addAspect = new CMLAddAspect(Constants.ASPECT_TITLED, titledProps, null, "1");
// Construct CML Block
CML cml = new CML();
cml.setCreate(new CMLCreate[] { create });
cml.setAddAspect(new CMLAddAspect[] { addAspect });
// Issue CML statement via Repository Web Service and retrieve result
// Note: Batching of multiple statements into a single web call
UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
Reference content = result[0].getDestination();
// Write some content
ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
//String text = "The quick brown fox jumps over the lazy dog";
ContentFormat contentFormat = new ContentFormat("text/plain", "UTF-8");
Content contentRef = contentService.write(content, Constants.PROP_CONTENT, contentByte, contentFormat);
System.out.println("Document are created successfully. UID:= " + content.getUuid());
return content.getUuid();
} catch (Throwable e) {
System.out.println(e.toString());
} finally {
// End the session
AuthenticationUtils.endSession();
//System.exit(0);
}
return null;
}
I try to replace espace with this character : + without success
saveAttachement(file,
fileName +
System.currentTimeMillis(), container.replace(" ","+"),
USER_NAME, PASSWORD,
code);
this is the old container with espace
/app:company_home/cm:His Excellency the Secretary/cm:Reporter Secretariat
and this is the container with +
/app:company_home/cm:His+Excellency+the Secretary/cm:Reporter+Secretariat
in alfresco's log I didn't find any error
Try encoding your folderName with ISO9075.encode(folderName).
Lucene search syntax needs encoding of spaces using ISO9075. I thik this is what happens somewhere behind the scenes of your ParentReference usage.
Related
My goal is to modify a .txt file in azure file storage using WindowsAzure.Storage API. I would like to know if there is any method to add some text in the file.
Is it easier to use the System.IO API?
I've already tried the cloudFileStream.Write() but it didn't work.
Thank you
The sample on https://github.com/Azure/azure-storage-net/blob/master/Test/WindowsRuntime/File/FileStreamTests.cs shows you how to do this.
public async Task FileOpenWriteTestAsync()
{
byte[] buffer = GetRandomBuffer(2 * 1024);
CloudFileShare share = GetRandomShareReference();
try
{
await share.CreateAsync();
CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
using (CloudFileStream fileStream = await file.OpenWriteAsync(2048))
{
Stream fileStreamForWrite = fileStream;
await fileStreamForWrite.WriteAsync(buffer, 0, 2048);
await fileStreamForWrite.FlushAsync();
byte[] testBuffer = new byte[2048];
MemoryStream dstStream = new MemoryStream(testBuffer);
await file.DownloadRangeToStreamAsync(dstStream, null, null);
MemoryStream memStream = new MemoryStream(buffer);
TestHelper.AssertStreamsAreEqual(memStream, dstStream);
}
}
finally
{
share.DeleteIfExistsAsync().Wait();
}
}
If you want to add some text(append to the existing data) to the file on azure file storage, there is no direct method. You need to download it and then upload with the text you want to append.
string accountName = "xxx";
string key = "xxx";
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var share = storageAccount.CreateCloudFileClient().GetShareReference("testfolder");
CloudFile file1 = share.GetRootDirectoryReference().GetFileReference("a.txt");
//if you want to append some text from local file
var stream1 = File.OpenRead("your file path in local, like d:\hello.txt");
string from_local_file = (new StreamReader(stream1)).ReadToEnd();
//if you just want to add some text from string, directly use the string
//string from_local_file ="the text I want to append to azure file";
//download the content of the azure file
string from_azure_file = file1.DownloadText();
//this does the trick like appending text to azure file, not overwrite
file1.UploadText(from_azure_file + from_local_file);
If you want to directly upload text to file stored on azure file storage, you should use one of the following methods: UploadText() / UploadFromFile() / UploadFromStream().
Note that this will overwrite the existing data in the azure file.
If you want to update the context of azure file, you can use WriteRange() method. But it has some limitations, if you're interesting about it, I can provide you some code.
I am using extent reports in appium with testng and its working fine for me.whenver my tests run is completed then extent report generates html file in my project folder and that is what expected.
Issue is that when I again run my tests then extent report generate new html report file by overwrting the name of previously created html file.
I want extent report to generate html file with unique names or name with date in in, each time when I run my tests
You can create your file name to be the current timestamp. This way, it will be easy to have a unique name for your report file -
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
extent = new ExtentReports (userDir +"\\test-output\\" + timeStamp + ".html", true);
You can do it by setting unique name:
String reportFile = resultDirectory + fileName + ".html";
than method for saving report to certain folder:
public void saveReportFolder() throws IOException {
File srcDir = new
File(System.getProperty("user.home")+"/Automation/target");
File destDir = new File(System.getProperty("user.home") + "/reports/"+ System.getProperty("user.name")+"/"+dateTimeGenerator());
FileUtils.copyDirectory(srcDir, destDir);
}
...and utility for setting dateTime:
public static String dateTimeGenerate(){
Format formatter = new SimpleDateFormat("YYYYMMdd_HHmmssSSS");
Date date = new Date(System.currentTimeMillis());
return formatter.format(date);
}
Or simply use klov reports start server and have everything in database (MongoDb), it is more elegant way to go.
Hope this helps,
I use:
private static String timestamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()).replaceAll(":", "-");
public static String reportFullPath = getReportsPath() + "\\AutomationReport_" + timestamp + ".html";
I have done it like this, simple and crisp.
String Outputfilename= ExecutionConfig.FileOutname;
System.err.close(); // written to remove JAVA 9 incompatibility.. continued below
System.setErr(System.out); // continue.. and remove the warnings
extent = new ExtentReports(System.getProperty("user.dir") + "/test-output/"+Outputfilename+".html", true);
So here ExecutionConfig.FileOutname is called from the class ExecutionConfig where i am reading the values from the config.properties file. and then here assigning it to the output-file.
Also it worked for me.
I also faced a similar issue. As in the real-world, we need old reports as well. Below is the solution in Java for Extent PDF report
I added an event listener method. Event used- TestRunStarted. We further need to register for this event too. The solution can be done for HTML report too.
public void setCustomReportName(TestRunStarted event)
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String currenttimestamp =sdf.format(timestamp);
Properties prop=new Properties();
//extent.reporter.pdf.out is the name of property which tell the report path
prop.setProperty("extent.reporter.pdf.out", "test output/PdfReport/ExtentPdf_"+currenttimestamp+".pdf");
ExtentService e1 =new ExtentService();
//ExtentReportsLoader is the inner class of ExtentService and initPdf is its private method which takes the path for report
Class<?>[] a=e1.getClass().getDeclaredClasses();
Method met;
//Even there is exception test run wont fail and report will also be generated (ExtentPdf.pdf)
try {
met = a[0].getDeclaredMethod("initPdf", Properties.class);
met.setAccessible(true);
met.invoke(a[0], prop);
} catch (NoSuchMethodException e) {
System.out.println("There is no method with name initPdf");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
System.out.println("Argument passed to method initPdf are not correct");
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
I am trying to save picture in folder and store path in database using entity framework in asp.net mvc 5.
I did it but I have some problems .
image path in DB saved like this :
C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\2.jpg
How can I change it to: ~/Images/SubGoods/2.jpg ??
and I want to change image name to it's primary key id and I used pic =Convert.ToString( subgood.SubGoodID); to do it, but it saves Zero :
C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\0
It saves always 0 .I know that's because Primary key in that line not generated yet . where of my codes primary Key id generated ?
public ActionResult AddSubGood(SubGood subgood, HttpPostedFileBase UploadImage)
{
var MainGoodId = subgood.FKMainGoodID;
SubGoodRepositories blSubGood = new SubGoodRepositories();
string path="";
if (UploadImage != null)
{
string pic = System.IO.Path.GetFileName(UploadImage.FileName);
pic =Convert.ToString( subgood.SubGoodID);
path = System.IO.Path.Combine(
Server.MapPath("~/Images/SubGoods"), pic);
}
if (ModelState.IsValid)
{
subgood.FKMainGoodID = MainGoodId;
UploadImage.SaveAs(path);
subgood.SubGoodImage = path;
if (blSubGood.Add(subgood))
{
return JavaScript("alert('saved');");
}
else
{
return JavaScript("alert('didn't saved');");
}
}
else
{
return JavaScript("alert('error');");
}
}
You should save only the file name:
var fileName = Path.GetFileName(UploadImage.FileName);
Then when you want to fetch the file for user you can simply address the file name with specific path:
<img src="~/Content/Uploaded/#item.fileName" .../>
You can also generate a random file name using Guid:
var rondom = Guid.NewGuid() + fileName;
Server.MapPath will return you Virtual path(which you don't needed) , you can create another variable and concatenate like this :
string DbPath = "~/Images/SubGoods/"; // better to store in web.config file
DbPath = DbPath + ""//here you can query in table and find the last inserted primary key and increment it with '1'
I have set up a web shop with Magento version 1.7 and my next task is to import products by using the v2 Soap api. So far, everything seems to work except for one thing: All the custom attributes of the created products remain empty. Everything else works fine - the name, sku, price, description and so on.
My script runs with asp.net so I don't have any PHP code but I think it looks more or less similar. Here is a snippet that I use where the attributes are assigned to a product:
dim create as new catalogProductCreateEntity
create.name = "Test"
create.price = "11.1100"
create.description = "test description"
dim additional(0) as associativeEntity
dim attribute as new associativeEntity
attribute.key = "manufacturer"
attribute.key = "xyz"
additional(0) = attribute
create.additional_attributes = additional
In this case, a simple text field should receive the value "xyz".
I use the very same procedure in other Magento stores that I have set up in the past and it works just fine. The only difference is that these shops use Magento version 1.5.
Could this be a bug in the api?
"xyz" needs to go into .value of the associativeEntity:
dim additional(0) as associativeEntity
dim attribute as new associativeEntity
attribute.key = "manufacturer"
attribute.value = "xyz"
additional(0) = attribute
Hope this helps.
i have successfully done this in C#, below is the code
private void getAdditionalAttributes()
{
string skuNumber="S00001";
MagentoService mservice = new MagentoService();
string sessionkey = "";
try
{
sessionkey = mservice.login("apiuser", "apipassword");
}
catch (Exception exp)
{
//Error
}
try
{
catalogProductRequestAttributes fetchattrib = new catalogProductRequestAttributes();
// it will only populate the attributes that you ask for
fetchattrib.attributes = new string[] { "name", "description", "short_description" };
// Additional Attribute
fetchattrib.additional_attributes = new string[] { "ismemo","color" };
catalogProductReturnEntity prod = MagentoConnectivity.magService.catalogProductInfo(sessionkey, skuNumber, "", fetchattrib, "sku");
foreach (var item in prod.additional_attributes)
{
MessageBox.Show("=> Key: " + item.key + "\t Attribute Value=" + item.value + "\n");
}
}
catch (Exception exp)
{
MessageBox.Show("=> Exception in getting Additional Attributes \n" + exp.Message + "\n");
return;
}
}
I am beginner in JavaME. I'd like to make simple dicitionary. The source data is placed on "data.txt" file in "res" directory. The structure is like this:
#apple=kind of fruit;
#spinach=kind of vegetable;
The flow is so simple. User enters word that he want to search in a text field, e.g "apple", system take the user input, read the "data.txt", search the matched word in it, take corresponding word, and display it to another textfield/textbox.
I've managed to read whole "data.txt" using this code..
private String readDataText() {
InputStream is = getClass().getResourceAsStream("data.txt");
try {
StringBuffer sb = new StringBuffer();
int chr, i=0;
while ((chr = is.read()) != -1)
sb.append((char) chr);
return sb.toString();
}
catch (Exception e) {
}
return null;
}
but I still dont know how to split it, find the matched word with the user input and take corresponding word. Hope somebody willing to share his/her knowledge to help me..
Basically you want something like this:
private String readDataText() {
InputStream is = getClass().getResourceAsStream("data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
try {
while ((line = br.readLine()) != null)
{
String[] split = line.split("=");
if (split[0].equals("#someFruit"))
return split[1];
}
}
catch (Exception e) {}
return null;
}
Read the line using a BufferedReader, no need to handle single chars.
Split the line by the = token
Check if the key in the dictionary is the wanted key, if so, return the value.