Download file with apache chemistry php client - alfresco

I need to know what I've to do if I want to download a cmis:documento that I've in my repositorio with Apache Chemistry Php client.
I've one file, "Test.txt" in Sitios space...
I want download Test.txt with browser...
My code:
$client = new CMISService('http://localhost:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom', 'admin', 'admin');
$path = '/Sitios';
$directorio = $client->getObjectByPath($path);
$objs = $client->getChildren($directorio->id);
foreach ($objs->objectList as $obj)
{
var_dump ($obj);
}
In $obj I've:
array (size=32)
'alfcmis:nodeRef' => string 'workspace://SpacesStore/c3c903fe-86b6-4db0-8cb2-d5c5dbe913c7' (length=60)
'cmis:isImmutable' => string 'false' (length=5)
'cmis:versionLabel' => string '1.0' (length=3)
'cmis:objectTypeId' => string 'cmis:document' (length=13)
'cmis:description' => string 'descripcion del fichero' (length=23)
'cmis:createdBy' => string 'admin' (length=5)
'cmis:checkinComment' => null
'cmis:creationDate' => string '2016-02-15T01:25:12.76+01:00' (length=28)
'cmis:isMajorVersion' => string 'true' (length=4)
'cmis:contentStreamFileName' => string 'Fichero de texto plano' (length=22)
'cmis:name' => string 'Fichero de texto plano' (length=22)
'cmis:isLatestVersion' => string 'true' (length=4)
'cmis:lastModificationDate' => string '2016-02-15T01:25:12.76+01:00' (length=28)
'cmis:contentStreamLength' => string '21' (length=2)
'cmis:objectId' => string 'c3c903fe-86b6-4db0-8cb2-d5c5dbe913c7;1.0' (length=40)
'cmis:lastModifiedBy' => string 'admin' (length=5)
'cmis:secondaryObjectTypeIds' => string 'P:rn:renditioned' (length=16)
'cmis:contentStreamId' => string 'store://2016/2/15/1/25/c36a749d-43f1-4e31-b46a-de66b4f5634d.bin' (length=63)
'cmis:contentStreamMimeType' => string 'text/plain' (length=10)
'cmis:baseTypeId' => string 'cmis:document' (length=13)
'cmis:changeToken' => null
'cmis:isPrivateWorkingCopy' => string 'false' (length=5)
'cmis:versionSeriesCheckedOutBy' => null
'cmis:isVersionSeriesCheckedOut' => string 'false' (length=5)
'cmis:versionSeriesId' => string 'c3c903fe-86b6-4db0-8cb2-d5c5dbe913c7' (length=36)
'cmis:isLatestMajorVersion' => string 'true' (length=4)
'cmis:versionSeriesCheckedOutId' => null
'cm:title' => string 'Titulo del fichero' (length=18)
'cm:description' => string 'descripcion del fichero' (length=23)
'app:editInline' => string 'true' (length=4)
'cm:lastThumbnailModification' => string 'pdf:1455495914744' (length=17)
'' => string 'Titulo del fichero' (length=18)
public 'renditions' =>
What I've to do to create a link to download the file?
I don't want to use webscript...
I think that I've to use getContentStream($obj->id) ¿really?
Thanks.

Depending on your document mime type and what you are willing to do with, it can be slightly different, but basically this is what you need to do, if you were using java:
// Get the contents of the file
Document doc = (Document) session.getObject(id);
ContentStream contentStream = doc.getContentStream(); // returns null if the document has no content
if (contentStream != null) {
String content = getContentAsString(contentStream);
System.out.println("Contents of " + filename + " are: " + content);
} else {
System.out.println("No content.");
}
...
/**
* Helper method to get the contents of a stream
*
* #param stream
* #return
* #throws IOException
*/
private static String getContentAsString(ContentStream stream) throws IOException {
StringBuilder sb = new StringBuilder();
Reader reader = new InputStreamReader(stream.getStream(), "UTF-8");
try {
final char[] buffer = new char[4 * 1024];
int b;
while (true) {
b = reader.read(buffer, 0, buffer.length);
if (b > 0) {
sb.append(buffer, 0, b);
} else if (b == -1) {
break;
}
}
} finally {
reader.close();
}
return sb.toString();
}
but since you are on PHP, I guess you should be replicating the same logic with php api fuctions, so basically $client->getContentStream($objId); should return the file content as string.

Related

Complex LINQ query - multiple table relationships

I have a books database, which has an ICollection of authors. I want to return the author object based on the AuthorId using LINQ.
Book db
int BookId
string Name { get; set; }
public ICollection<Author> Authors { get; set; }
Author db
int AuthorId
string Name
ICollection<Quote> Quotes { get; set; }
ICollection<Penname> Pennames { get; set; } - Edit: Added for clarity
I have tried:
var test = _context.Book.Include(x => x.Authors).Include("Authors.Quotes")
.Select(y => y.Authors)
Which gave me:
EntityQueryable<ICollection<Authors>>
[0] {HashSet<Author>} [0]{Author} [1]{Author} [3]{Author}
[1] {HashSet<Author>} [0]{Author} [1]{Author}
[2] {HashSet<Author>} [0]{Author} [1]{Author}
I just can't figure out how to iterate though the Authors in the Authors list. Something like the below:
var id = 2
var test = _context.Book.Include(x => x.Authors).Include("Authors.Quotes")
.Select(y => y.Authors.Select(x => x.Author).Where(x => x.AuthorId == id))
If I ever do a major update I might use elastic...
Update #Marko Papic:
Thanks. Weirdly if I use the below to get a list of books with authors, I get the quotes and pennames lists populated as I expect
var test = _context.Book.Include(x => x.Authors)
.ThenInclude(x => x.Quotes)
.Include(x => x.Authors)
.ThenInclude(x => x.Pennames)
However if I use SelectMany, then the quotes and pennames end up as null
var test = _context.Book.Include(x => x.Authors)
.ThenInclude(x => x.Quotes)
.Include(x => x.Authors)
.ThenInclude(x => x.Pennames)
.SelectMany(x => x.Authors).Where(x => x.AuthorId == id);
Author myauthor
int AuthorId = 2
string Name = "Bob"
ICollection<Quote> Quotes = null
ICollection<Penname> Pennames = null
You can use SelectMany:
var test = _context.Book.Include(x => x.Authors).ThenInclude(x => x.Quotes)
.SelectMany(x => x.Authors).Where(x => x.AuthorId == id);
I think the includes are ignored because the result type of the query is not the same of the type of your dbset with when you start, from the documentation:
If you change the query so that it no longer returns instances of the
entity type that the query began with, then the include operators are
ignored.
I assume the relationship between Books and Authors is many to many, if that is the case then this is how I would do your query:
var query=_context.Authors.Include(a=>a.Books)
.Include(a=>a.Quotes)
.Include(a=>a.Pennames)
.Where(a=> a.AuthorId == id);

PayUMoney - Android: Only getting **paymentId** from payUMoney SDK after successful payment

I'm integrating payUMoney in my Android application. I'm getting only paymentId after successful payment in both environment i.e Test & Production. I need Transaction Details as well from payUMoney. I have also contacted payUMoney technical team but not getting any response.
See image attached for payUMoney response which I have printed in Logcat.
What I have tried is like below.
public void makePayment() {
String phone = "8882434664";
String productName = "product_name";
String firstName = "piyush";
String txnId = "0nf7" + System.currentTimeMillis();
String email = "piyush.jain#payu.in";
String sUrl = AppConstant.BASE_URL + "/mob-payment/success";
String fUrl = AppConstant.BASE_URL + "/mob-payment/failure";
String udf1 = "";
String udf2 = "";
String udf3 = "";
String udf4 = "";
String udf5 = "";
boolean isDebug = true;
String key = "dRQuiA";
String merchantId = "4928174";
PayUmoneySdkInitilizer.PaymentParam.Builder builder = new PayUmoneySdkInitilizer.PaymentParam.Builder();
builder.setAmount(1.0)
.setTnxId(txnId)
.setPhone(phone)
.setProductName(productName)
.setFirstName(firstName)
.setEmail(email)
.setsUrl(sUrl)
.setfUrl(fUrl)
.setUdf1(udf1)
.setUdf2(udf2)
.setUdf3(udf3)
.setUdf4(udf4)
.setUdf5(udf5)
.setIsDebug(isDebug)
.setKey(key)
.setMerchantId(merchantId);
PayUmoneySdkInitilizer.PaymentParam paymentParam = builder.build();
calculateServerSideHashAndInitiatePayment(paymentParam);
}
private void calculateServerSideHashAndInitiatePayment(final PayUmoneySdkInitilizer.PaymentParam paymentParam) {
String url = "https://test.payumoney.com/payment/op/calculateHashForTest";
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has(SdkConstants.STATUS)) {
String status = jsonObject.optString(SdkConstants.STATUS);
if (status != null || status.equals("1")) {
String hash = jsonObject.getString(SdkConstants.RESULT);
paymentParam.setMerchantHash(hash);
PayUmoneySdkInitilizer.startPaymentActivityForResult(ActivityConfirmOrder.this, paymentParam);
} else {
Toast.makeText(ActivityConfirmOrder.this,
jsonObject.getString(SdkConstants.RESULT),
Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError) {
Toast.makeText(ActivityConfirmOrder.this,
ActivityConfirmOrder.this.getString(R.string.connect_to_internet),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ActivityConfirmOrder.this,
error.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return paymentParam.getParams();
}
};
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PayUmoneySdkInitilizer.PAYU_SDK_PAYMENT_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
StringBuilder str = new StringBuilder();
Bundle bundle = data.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
str.append(key);
str.append(":");
str.append(bundle.get(key));
str.append("\n\r");
}
Log.e("res: ", str.toString());
}
} else if (resultCode == RESULT_CANCELED) {
} else if (resultCode == PayUmoneySdkInitilizer.RESULT_FAILED) {
if (data != null) {
if (data.getStringExtra(SdkConstants.RESULT).equals("cancel")) {
} else {
}
}
} else if (resultCode == PayUmoneySdkInitilizer.RESULT_BACK) {
}
}
}
PayUMoney SDK-Version: versionName "6.1.0"
I was also facing the same problem, but after little bit of research, I have found that we need to generate invoice separately using different invoice api. You can find the bellow URL for the documentation for invoice api...
https://www.payumoney.com/dev-guide/products/invoicing.html
#MaulikDodia Actually you need to create success url on your own, then the payumoney will send all the data directly like this in your success url...
Array
(
[mihpayid] => 40399371551*******
[mode] => DC
[status] => success
[unmappedstatus] => captured
[key] => d****A
[txnid] => INV0****0531
[amount] => 1000.0
[addedon] => 2017-05-31 13:16:12
[productinfo] => ****
[firstname] => ****
[lastname] =>
[address1] =>
[address2] =>
[city] => null
[state] =>
[country] => null
[zipcode] =>
[email] => ***#test.xxx
[phone] =>
[udf1] =>
[udf2] =>
[udf3] =>
[udf4] =>
[udf5] =>
[udf6] =>
[udf7] =>
[udf8] =>
[udf9] =>
[udf10] =>
[hash] => ***************
[field1] => 715140****61
[field2] => 99***9
[field3] => 8523310*****511
[field4] => -1
[field5] =>
[field6] =>
[field7] =>
[field8] =>
[field9] => SUCCESS
[PG_TYPE] => HDFCPG
[encryptedPaymentId] => DB****EB8****02A****9FE4C****CB3
[bank_ref_num] => 8****016137****
[bankcode] => MAST
[error] => E000
[error_Message] => No Error
[name_on_card] => payu
[cardnum] => 512345XXXXXXXX46
[cardhash] => This field is no longer supported in postback params.
[amount_split] => {"PAYU":"1000.0"}
[payuMoneyId] => 1******0
[discount] => 0.00
[net_amount_debit] => 1000
)
Then you can generate invoice using that on the server side or do whatever you want.
Source: I have done all the code and it is working. Hope it helps... thanks

Cancel oldest raw in DB after calling findAll() method

I have a table for users password recovery requests. These are his columns:
ID
idUser
createdDate
expiryDate
token
isExpired
If a User tries to make multiple requests I want to find all the rows with his ID, and if they are > 1, set them to isExpired = true.
Doing so, I want to consider as valid only the last request.
How can I achieve this?
This is how I'm doing it now, assuming that in the table there is only one row with his ID:
if ($request->isMethod('POST')) {
$form->handleRequest($request);
$newPassword = $form->get('password')->getData();
$currentToken = $request->query->get('token');
$em = $this->getDoctrine()->getManager();
$passwRecovery = $em->getRepository('\UserBundle\Entity\PasswordRecovery')->findOneBy(array('token' => $currentToken));
if (empty($passwRecovery)) {
return new Response ("<h3>Access denied!</h3>");
}
else {
if (new \DateTime('now') > $passwRecovery->getExpireDate())
{
return new Response ("<h3>Token expired!</h3>");
}
$idUser = $passwRecovery->getIdUser();
$userRecoverPassw = $em->getRepository('\UserBundle\Entity\User')->findOneBy(array('id' => $idUser));
$userRecoverPassw->setPassword($newPassword);
$em->persist($userRecoverPassw);
$em->flush();
return new Response ("<h3>Password reset ok!</h3>"); }
Consider I have 3 rows with the same idUser, if I use:
$passwRecovery = $em->getRepository('\UserBundle\Entity\PasswordRecovery')
->findAll(array('token' => $currentToken));
I will get 3 results. How can I set the isExpired = true only for the first two?
Thanks!
This is the solution that at the end worked for me, hope this can help. If there are any better ways to do what I'm posting here, I'm open to suggestions.
public function resetPasswordAction(Request $request) {
$form = $this->createFormBuilder()
->add('password', 'password')
->add('save', 'submit', ['label' => 'Send'])
->getForm();
if ($request->isMethod('POST')) {
$form->handleRequest($request);
$newPassword = $form->get('password')->getData();
$currentToken = $request->query->get('token');
$em = $this->getDoctrine()->getManager();
$passwRecoveryObject = $em->getRepository('\UserBundle\Entity\PasswordRecovery')->findOneBy(array('token' => $currentToken));
if (empty($passwRecoveryObject)) {
return new Response ("Impossible to execute the request!");
}
else {
if (new \DateTime('now') > $passwRecoveryObject->getExpireDate())
{
return new Response ("Token expired!");
}
$idUser = $passwRecoveryObject->getIdUser()->getId();
$userRecoverPassw = $em->getRepository('\UserBundle\Entity\PasswordRecovery')->findBy(array('idUser' => $idUser));
$end = end($userRecoverPassw); //$end is the last record of the password_recovery table
$count = count($userRecoverPassw); //count of the rows in password_recovery with the id of the current User
foreach ($userRecoverPassw as $element) { //here i'm setting to 1 the isExpired column for all the rows with the same id, except for the last one
if (--$count <= 0) {
break; }
$element->setIsExpired(1);
$em->persist($element);
$em->flush();
}
$userResetPassw = $em->getRepository('\UserBundle\Entity\User')->findOneBy(array('id' => $end->getIdUser()->getId())); //User that need to reset the password
if ($end->getIsExpired()==0) {
$userResetPassw->setPassword($newPassword);
$end->setIsExpired(1);
$em->persist($userResetPassw);
$em->flush();
$em->persist($end);
$em->flush();
return new Response ("Password succesfully updated!");
}
else { return new Response ("Expired link!");}
} }
return $this->render('UserBundle:AccountUser:reset_password.html.php', array(
'form' => $form->createView(),));
}

Query String builder Error

I'm just trying to use dictionary data to build query string. i use this function.
public static string BuildQueryString(this IDictionary<string, string> source, bool withoutEmptyString)
{
return source != null ? String.Join("&", source.Keys
.Where(key => !withoutEmptyString || source.Values.Any(value => !String.IsNullOrEmpty(value)))
.SelectMany(key => source.Values
.Where(value => !withoutEmptyString || !String.IsNullOrEmpty(value))
.Select(value => String.Format("{0}={1}", HttpUtility.UrlEncode(key), value != null ? HttpUtility.UrlEncode(value) : string.Empty)))
.ToArray())
: string.Empty;
}
but when i send the data like this
var dataDictionary = new Dictionary<string, string>
{ {"one", "1"},
{"two", "2"},
{"three", "3"},
{"four", "4"},
{"five", "5"},
{"six", "6"}
};
i'm getting string like this
"one=1&one=2&one=3&one=4&one=5&one=6&two=1&two=2&two=3&two=4&two=5&two=6&three=1&three=2&three=3&three=4&three=5&three=6&four=1&four=2&four=3&four=4&four=5&four=6&five=1&five=2&five=3&five=4&five=5&five=6&six=1&six=2&six=3&six=4&six=5&six=6"
what is the wrong i did in the code
thanks
How about something simpler like:
var fromSource = source.Where(s => !string.IsNullOrEmpty(s.Value)).Select(s => s.Key + "=" + s.Value);
return string.Join("&", fromSource.ToArray());
return source != null ? string.Join("&",
source.Where(keyValuePair => withoutEmptyString && !string.IsNullOrEmpty(keyValuePair.Value))
.Select(keyValuePair => string.Format("{0}={1}", keyValuePair.Key, keyValuePair.Value)))
: string.Empty;
Please check if my where clause works for you.

How to attach files with metaWeblog to a blog post?

I'm trying to post to my blog with images.
Yes, I can upload images and I can see that images in the content of post
but it's not in a attached file list.
How can I put the images that I upload in the attached file list?
When I'm posting with MS word 2010 to my blog, images that I put on the word are always updated in a attached file list. But my php source doesn't.
Is there any way to attach files to a blog post?
$cBlog = new blog;
$title = "This is a article's title";
$desc = "IT will be the content";
$return = $cBlog->writePost($title, $desc);
class blog
{
public $g_blog_url;
public $user_id;
public $blogid;
public $password;
public $publish;
function __construct()
{
$this->g_blog_url = "https://api.blog.naver.com/xmlrpc";
$this->user_id = "globeseen";
$this->blogid = "globeseen";
$this->password = "password";
$this->publish = true;
}
function writePost($title, $description, $category="")
{
$client = new xmlrpc_client($this->g_blog_url);
$client->setSSLVerifyPeer(false);
$GLOBALS['xmlrpc_internalencoding']='UTF-8';
$img = $this->upload_image("D:\\1.jpg");
$struct = array(
'title' => new xmlrpcval($title, "string"),
'description' => new xmlrpcval($description."<img src=$img>", "string"),
'categories' => new xmlrpcval($category, "string"),
'tags' => new xmlrpcval('clothing', "string")
);
$f = new xmlrpcmsg("metaWeblog.newPost",
array(
new xmlrpcval($this->blogid, "string"),
new xmlrpcval($this->user_id, "string"),
new xmlrpcval($this->password, "string"),
new xmlrpcval($struct , "struct"),
new xmlrpcval($this->publish, "boolean")
));
$f->request_charset_encoding = 'UTF-8';
return $response = $client->send($f);
}
function upload_image($fpath) {
global $api_url, $blog_user, $blog_passwd;
$api_url = $this->g_blog_url;
$blog_user = $this->user_id;
$blog_passwd = $this->password;
$imgbit = file_get_contents($fpath, FILE_BINARY);
$img = new xmlrpcval(
array (
'bits' => new xmlrpcval($imgbit, 'base64'),
'type' => new xmlrpcval('image/jpeg', 'string'),
'name' => new xmlrpcval(basename($fpath), 'string')
), 'struct');
$c = new xmlrpc_client($api_url);
$c->setSSLVerifyPeer(false);
$x = new xmlrpcmsg("metaWeblog.newMediaObject");
$x->addParam(new xmlrpcval($blog_user, 'string'));
$x->addParam(new xmlrpcval($blog_user, 'string'));
$x->addParam(new xmlrpcval($blog_passwd, 'string'));
$x->addParam($img);
$c->return_type = 'phpvals';
$r =$c->send($x);
if ($r->errno=="0") {
return $r->val['url'];
} else {
echo "There was an error<pre>";
print_r($r);
echo "</pre>";
return null;
}
}
}

Resources