@org.junit.Test
public void testArgh() {
String adresse = "http://localhost:8080/alfresco/service/api/upload";
try {
String urlBase = "http://localhost:8080/alfresco/service/api/login?";
Map<String, String> mapArguments = new HashMap<String, String>();
mapArguments.put("u", "admin");
mapArguments.put("pw", "admin");
String retour = "";
URL url = UtilsWS.buildURL(urlBase, mapArguments);
retour = (String) UtilsWS.extractLocation(url, null);
String ticket = "";
int index = retour.indexOf("<ticket>");
if (index != -1) {
ticket = retour.substring(index + 8, retour.length() - 9);
}
System.out.println("Valeur du ticket: " + ticket);
//———————————————————————————————————-
mapArguments = new HashMap<String, String>();
mapArguments.put("filename", "test");
mapArguments.put("username", "toto");
//mapArguments.put("ticket", ticket);
mapArguments.put("mimetype", "text/plain");
mapArguments.put("title", "titre");
mapArguments.put("author", "auteur");
mapArguments.put("encoding", "UTF-8");
mapArguments.put("description", "description");
mapArguments.put("nodeid", "8d7f3af2-9ec7-41f3-9881-0e75e0d232eb");
mapArguments.put("content", "contenu de mon pseudo fichier");
java.net.Authenticator.setDefault(new MyAuthenticator("admin", "admin"));
url = UtilsWS.buildURL(adresse+"?ticket="+ticket, null);
URL donneesURL = UtilsWS.buildURL(adresse+"?", mapArguments);
String donnees = donneesURL.toString().substring(donneesURL.toString().indexOf('?')+1);
System.out.println("arguments: " + donnees);
// création de la connection
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
//conn.setDoInput(true);
// envoi de la requête
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(donnees.toString());
/* File file = new File("D:\\derby.log");
InputStreamReader fileReader = new InputStreamReader(new FileInputStream(file));
BufferedReader fileBuffer = new BufferedReader(fileReader);
String ligne;
StringBuffer sb = new StringBuffer();
while ((ligne = fileBuffer.readLine()) != null) {
System.out.println(URLEncoder.encode(ligne, "UTF-8"));
sb.append(URLEncoder.encode(ligne, "UTF-8"));
}
writer.write(sb.toString());*/
writer.flush();
// lecture de la réponse
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String result;
while ((result = reader.readLine()) != null) {
System.out.println(result);
}
} catch (UnsupportedEncodingException e) {
System.err.println(e.getMessage());
return;
} catch (MalformedURLException e) {
System.err.println(e.getMessage());
return;
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
content=contenu+de+mon+pseudo+fichier&author=auteur&storeid=8d7f3af2-9ec7-41f3-9881-0e75e0d232eb&title=titre&mimetype=text%2Fplain&username=toto&description=description&encoding=UTF-8&filename=test&
Server returned HTTP response code: 500 for URL: http://localhost:8080/alfresco/service/api/upload?ticket=TICKET_d9a76d5df6bb3324c553477121a2c701eeb4...
package org.alfresco.doc;
import java.net.URLEncoder;
import org.alfresco.service.cmr.repository.NodeRef;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import junit.framework.TestCase;
/**
*
* @author Philippe Dubois
*
*/
public class WebscriptTest extends TestCase {
private String host = "localhost";
private int port = 8080;
private String user1 = "admin";
private String pass1 = "admin";
private String user2 = "phil";
private String pass2 = "phil";
private String site = "test2";
static private String uploadedFileName = "";
static private String createdFolderName = "";
static private JSONObject theMetaData = null;
static private NodeRef ref = null;
static private NodeRef workingCopyRef = null;
public WebscriptTest() {
super();
}
public void setUp() throws Exception {
}
public JSONObject parseJSON(String resultString)
{
// parse the result using JSON libray
JSONObject obj = null;
try {
obj = new JSONObject(resultString);
System.out.println(obj.toString());
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
}
return obj;
}
public void checkResult(String resultString )
{
// parse the result using JSON libray
JSONObject obj = parseJSON(resultString);
int failureCount = 0;
boolean overallSuccess = false;
int successCount = 0;
// check the number of succes and failure
try {
failureCount = obj.getInt("failureCount");
overallSuccess = obj.getBoolean("overallSuccess");
successCount = obj.getInt("successCount");
System.out.println("failureCount=" + obj.getInt("failureCount"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.assertEquals(failureCount, 0);
this.assertEquals(overallSuccess, true);
this.assertEquals(successCount, 1);
}
public void testCreateFolder() {
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
PostMethod method = new PostMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/slingshot/doclib/action/folder/site/test2/documentLibrary/test");
method.setDoAuthentication(true);
int status = 0;
String resultString = "";
try {
// Shows UTF-8 Meta data
// Metadata are send in JSON format
createdFolderName = "éléphant" + System.currentTimeMillis();
//+ "ελέφαντας\"";
// create the JSON parameter using the JSON library
JSONStringer myStringr = new JSONStringer();
myStringr.object().key("description").value(
"Ceci est un test UTF-8").key("name").value(
createdFolderName).key("title").value("ελέφαντας")
.endObject();
method.setRequestEntity(new StringRequestEntity(myStringr
.toString(), "application/json", "UTF-8"));
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
checkResult(resultString);
}
public void testCreateFolderRunAs() {
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
PostMethod method = new PostMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/slingshot/doclib/action/folder/site/test2/documentLibrary/test?runAs=testuser");
method.setDoAuthentication(true);
int status = 0;
String resultString = "";
try {
// Shows UTF-8 Meta data
// Metadata are send in JSON format
String createdFolderName = "éléphant" + System.currentTimeMillis();
//+ "ελέφαντας\"";
// create the JSON parameter using the JSON library
JSONStringer myStringr = new JSONStringer();
myStringr.object().key("description").value(
"Ceci est un test UTF-8").key("name").value(
createdFolderName).key("title").value("ελέφαντας")
.endObject();
method.setRequestEntity(new StringRequestEntity(myStringr
.toString(), "application/json", "UTF-8"));
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
checkResult(resultString);
}
public void testCreateFolderNok() {
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
PostMethod method = new PostMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/slingshot/doclib/action/folder/site/test2/documentLibrary/test?runAs=TEST2");
method.setDoAuthentication(true);
int status = 0;
String resultString = "";
try {
// Shows UTF-8 Meta data
// Metadata are send in JSON format
String createdFolderName = "éléphant" + System.currentTimeMillis();
//+ "ελέφαντας\"";
// create the JSON parameter using the JSON library
JSONStringer myStringr = new JSONStringer();
myStringr.object().key("description").value(
"Ceci est un test UTF-8").key("name").value(
createdFolderName).key("title").value("ελέφαντας")
.endObject();
method.setRequestEntity(new StringRequestEntity(myStringr
.toString(), "application/json", "UTF-8"));
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertFalse(HttpStatus.SC_OK == status);
// checkResult(resultString);
}
public void testDeleteFolder() {
// construct HttpClient so that we issue HTTP DELETE request
HttpClient client = new HttpClient();
// set the credential using OmniFind API password
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
// construct a DeleteMethod and set necessary request headers
DeleteMethod method = null;
try {
method = new DeleteMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/slingshot/doclib/action/folder/site/test2/documentLibrary/test/"
+ URLEncoder
.encode(createdFolderName, "UTF-8"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
this.assertFalse(true);
}
method.setDoAuthentication(true);
int status = 0;
String resultString = "";
try {
// execute the delete method
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
checkResult(resultString);
}
public void testUploadDocument()
{
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
PostMethod method = new PostMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/api/upload");
method.setDoAuthentication(true);
//method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
// true);
uploadedFileName = "data" + System.currentTimeMillis() +".txt";
ByteArrayPartSource targetFile = new ByteArrayPartSource(uploadedFileName, "The quick brown fox jumps over the lazy dog".getBytes());
Part[] parts = {
new FilePart("filedata", targetFile),
new StringPart("siteid", "test2"),
new StringPart("containerid", "documentLibrary"),
new StringPart("uploaddirectory", "/test"),
new StringPart("contenttype","text/plain"),
new StringPart("description", "description du document")
};
//Create the multi-part request
method.setRequestEntity(
new MultipartRequestEntity(parts, method.getParams())
);
int status = 0;
String resultString = "";
try {
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
System.out.println("Res:" + resultString);
// parse the result using JSON libray
JSONObject obj = this.parseJSON(resultString);
System.out.println(obj.toString());
try {
//get nodeRef of the created document
ref = new NodeRef(obj.getString("nodeRef"));
} catch (Exception e) {
this.assertFalse(true);
}
}
public void testDownloadDocument()
{
HttpClient client = new HttpClient();
// set the credential using OmniFind API password
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
// construct a DeleteMethod and set necessary request headers
GetMethod method = null;
try {
method = new GetMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/api/node/content/" + ref.getStoreRef().getProtocol()
+ "/" + ref.getStoreRef().getIdentifier() + "/" + ref.getId() + "/"
+ URLEncoder
.encode(uploadedFileName, "UTF-8"));
// /alfresco/s/api/node/content/workspace/SpacesStore/472b17b5-a588-4cc1-acbc-8e166a9a71bf/Web_Studio_Configuration.htm
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
this.assertFalse(true);
}
method.setDoAuthentication(true);
int status = 0;
String resultString = "";
try {
// execute the delete method
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
System.out.println(resultString);
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
}
public void testGetMetaData()
{
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
// construct a DeleteMethod and set necessary request headers
GetMethod method = null;
try {
method = new GetMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/api/metadata");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
this.assertFalse(true);
}
method.setDoAuthentication(true);
//Define name-value pairs to set into the QueryString
System.out.println(ref.toString());
int status = 0;
String resultString = "";
try {
NameValuePair nvp1= new NameValuePair("nodeRef",ref.toString());
method.setQueryString(new NameValuePair[]{nvp1});
// execute the delete method
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
System.out.println(resultString);
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
System.out.println(status);
this.assertTrue(HttpStatus.SC_OK == status);
//parse the returned meta data
theMetaData = this.parseJSON(resultString);
System.out.print(theMetaData);
}
public void testUpdateMetaData()
{
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
PostMethod method = new PostMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/api/metadata/node/" + ref.getStoreRef().getProtocol() + "/"
+ ref.getStoreRef().getIdentifier() + "/"
+ ref.getId());
method.setDoAuthentication(true);
int status = 0;
String resultString = "";
try {
// create the meta data parameters
//Example:
// {"mimetype":"text/plain",
// "properties":
// {"description":"description du document",
// "name":"data1235739100859.txt",
// "title":"Ceci est un titre"},
// "tags":"Tag1"}
JSONStringer myStringr = new JSONStringer();
//change description and title
myStringr.object().key("mimetype").value("text/plain")
.key("properties").object()
.key("description").value("Description changed")
.key("title").value("Title changed")
.endObject()
.key("tags").value("Tag 1,Tag2,Tag3")
.endObject();
method.setRequestEntity(new StringRequestEntity(myStringr
.toString(), "application/json", "UTF-8"));
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
}
public void testCheckOut()
{
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
PostMethod method = new PostMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/slingshot/doclib/action/checkout/site/test2/documentLibrary/test/"
+ uploadedFileName);
method.setDoAuthentication(true);
int status = 0;
String resultString = "";
try {
JSONStringer myStringr = new JSONStringer();
//change description and title
myStringr.object()
.endObject();
method.setRequestEntity(new StringRequestEntity(myStringr
.toString(), "application/json", "UTF-8"));
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
//check returned parameters
checkResult(resultString );
// recuperate the node ref of the working copy
//parse the returned meta data
JSONObject jsonResult = this.parseJSON(resultString);
//{
// "totalResults": 1,
// "overallSuccess": true,
// "successCount": 1,
// "failureCount": 0,
// "results":
// [
// {
// "action": "checkoutAsset",
// "nodeRef": "workspace:\/\/SpacesStore\/affa077d-063e-4deb-8965-df7ce8a255cc",
// "downloadUrl": "api\/node\/content\/workspace\/SpacesStore\/affa077d-063e-4deb-8965-df7ce8a255cc\/data1235984765781 (Working Copy).txt?a=true",
// "success": true,
// "id": "data1235984765781.txt"
// }
// ]
// }
JSONArray results = null;
JSONArray resultsArray = null;
JSONObject resObject = null;
String checkOutNodeRef = null;
try {
resultsArray = (JSONArray)jsonResult.get("results");
resObject = (JSONObject)resultsArray.get(0);
//get the nodeRef
checkOutNodeRef = resObject.getString("nodeRef");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
workingCopyRef = new NodeRef(checkOutNodeRef);
}
public void testCheckIn()
{
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
PostMethod method = new PostMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/api/upload");
method.setDoAuthentication(true);
//method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
// true);
uploadedFileName = "data" + System.currentTimeMillis() +".txt";
ByteArrayPartSource targetFile = new ByteArrayPartSource(uploadedFileName, "The quick brown fox jumps over the lazy dog After the checkout".getBytes());
Part[] parts = {
new FilePart("filedata", targetFile),
new StringPart("siteid", "test2"),
new StringPart("containerid", "documentLibrary"),
new StringPart("updateNodeRef",workingCopyRef.toString()),
new StringPart("description", "description du document")
};
//Create the multi-part request
method.setRequestEntity(
new MultipartRequestEntity(parts, method.getParams())
);
int status = 0;
String resultString = "";
try {
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
System.out.println("Res:" + resultString);
// parse the result using JSON libray
JSONObject obj = this.parseJSON(resultString);
System.out.println(obj.toString());
try {
//get nodeRef of the created document
ref = new NodeRef(obj.getString("nodeRef"));
} catch (Exception e) {
this.assertFalse(true);
}
}
public void testSearch()
{
HttpClient client = new HttpClient();
// set the credential using OmniFind API password
client.getState().setCredentials(new AuthScope(host, port, "Alfresco"),
new UsernamePasswordCredentials(user1, pass1));
// construct a DeleteMethod and set necessary request headers
GetMethod method = null;
try {
method = new GetMethod(
"http://"
+ host
+ ":"
+ port
+ "/alfresco/s/slingshot/search?site=test2&container=documentLibrary&term=fox&maxResults=101"
);
// /alfresco/s/api/node/content/workspace/SpacesStore/472b17b5-a588-4cc1-acbc-8e166a9a71bf/Web_Studio_Configuration.htm
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
this.assertFalse(true);
}
method.setDoAuthentication(true);
int status = 0;
String resultString = "";
try {
// execute the delete method
status = client.executeMethod(method);
resultString = method.getResponseBodyAsString();
System.out.println(resultString);
} catch (Exception e) {
e.printStackTrace();
this.assertFalse(true);
} finally {
method.releaseConnection();
}
this.assertTrue(HttpStatus.SC_OK == status);
//parse search result
JSONObject res = parseJSON(resultString);
}
}
@org.junit.Test
public void testUpload(){
String ticket = generationTicket();
String urlBase = "http://localhost:8080/alfresco/service/api/upload?alf_ticket='+ticket;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlBase);
httppost.addHeader("filename", "test");
httppost.addHeader("username", "toto");
httppost.addHeader("mimetype", "text/plain");
httppost.addHeader("title", "titre");
httppost.addHeader("author", "auteur");
httppost.addHeader("encoding", "UTF-8");
httppost.addHeader("description", "description");
httppost.addHeader("nodeid", "8d7f3af2-9ec7-41f3-9881-0e75e0d232eb");
httppost.addHeader("content", "contenu de mon pseudo fichier");
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("—————————————-");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
if (resEntity != null) {
resEntity.consumeContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
}
HTTP/1.1 500 Erreur Interne de Servlet
Content from pre 2016 and from language groups that have been closed.
Content is read-only.
By using this site, you are agreeing to allow us to collect and use cookies as outlined in Alfresco’s Cookie Statement and Terms of Use (and you have a legitimate interest in Alfresco and our products, authorizing us to contact you in such methods). If you are not ok with these terms, please do not use this website.