Can´t render upload images in Magnolia CMS - image

i have a content app in Magnolia CMS, now i need to redner a image of the class DamUploadFieldDefinition from a content app
jcr node
I have tried this in my .ftl:
<img src = "${cmsfn.link(news.jcrPhoto)}" />
But only return a path of the photo and can´t render my photo
Searching i found this solution but doesn´t render:
<img src="${damfn.getRendition(news.jcrPhoto, "myAssetVariante").link}" />
I was looking in another content app named "contacts" of MAgnolia, and they make it through a model class:
public class NewsModel<RD extends TemplateDefinition> extends AbstractSTKTemplateModel<TemplateDefinition> {
private Node news;
#Inject
public NewsModel(Node content, TemplateDefinition definition, RenderingModel<?> parent,
STKTemplatingFunctions stkFunctions, TemplatingFunctions templatingFunctions) {
super(content, definition, parent, stkFunctions, templatingFunctions);
System.out.println("Entramos en el constructor");
}
/**
* FIXME: should be done better (binaryHandling): SCRUM-525.
*/
public String getPhoto() {
System.out.println("BOB inicio en el getPhoto");
if (news == null) {
System.out.println("news == null");
return null;
}
Property binaryData = null;
try {
if (news.hasNode("photo")) {
System.out.println("Tenemos contenido");
Node binaryNode = news.getNode("photo");
binaryData = binaryNode.getProperty("jcr:data");
}
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
if (binaryData != null) {
System.out.println("retornamos desde templatingFunctions");
return templatingFunctions.link(binaryData);
} else {
System.out.println("retornamos null");
return null;
}
}
public ContentMap getNews() {
System.out.println("Inicio getNews");
ContentMap cm = templatingFunctions.asContentMap(news);
System.out.println("ContentMap=\n"+cm);
return cm;
}
public void setNews(Node news) {
this.news = news;
}
#Override
public String execute() {
System.out.println("En el execute");
try {
NodeIterator ni = content.getNodes();
System.out.println("size:"+ni.getSize());
while(ni.hasNext()){
System.out.println(ni.toString());
Node n = ni.nextNode();
System.out.println(n.getIdentifier());
}
} catch (RepositoryException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//String id = PropertyUtil.getString(content, "news");
String id = "651c7140-b681-45b4-8814-ae26bfa0ba0d";
news = null;
System.out.println("id="+id);
if (StringUtils.isNotEmpty(id)) {
System.out.println("En el if del execute");
try {
news = new HTMLEscapingContentDecorator(true).wrapNode(NodeUtil.getNodeByIdentifier("news",id));
}
catch (RepositoryException e) {
System.out.println("Can't get uuid: '" + id + "' of contact.");
}
}
return super.execute();
}
}
And my FTL is:
[#assign news = model.news!]
7
[#if news?has_content]
8
[#assign hasPhoto = model.photo?has_content]
[/#if]
[#if contact?has_content]
9
[#if hasPhoto]
10
<dl class="media photo pos-2">
<dt><img src="${model.photo}"/></dt>
</dl>
[/#if]
[/#if]
When i put String id = PropertyUtil.getString(content, "news"); ID is null so don´t pass in if (StringUtils.isNotEmpty(id)) {
So i hardcode putting
String id = "651c7140-b681-45b4-8814-ae26bfa0ba0d";
and run all code but id doesn´t show the img
Result
Showing Google´s console i can see the image path:
/mgnl-prosegur-intra-webapp/01/photo
But even putting the src like Contacts content app with my image name, dont shows anything
<img src="/mgnl-prosegur-intra-webapp/demo-project/contacts/ldavinci/photo/vitruviano.jpeg" alt="">
Changed to should be:
<img src="/mgnl-prosegur-intra-webapp/demo-project/contacts/ldavinci/photo/vitruviano.jpeg" alt="">
But not function
Please

if image is in DAM (Assets app), try this:
<img src="${damfn.getAssetLink(news.jcrPhoto)}">

Related

pull images from twitter API on processing 3

I am quite new to this so please bear with me. I am trying to use a keyword search to pull images from twitter using twitter4j. I want it to show the images positioned randomly on the screen in a loop.
This code I have below is a combination of different ones I have found online. Its currently finding tweets using these keywords and showing them in the console, however, it is not displaying them on the screen and I’m not sure why…
Another thing is that I think it is doing a live stream from twitter so pulling tweets immediately at the time the code is run, so I am not getting lots of results when I put in an obscure keyword, I want it to search for the last 100 tweets with images using the keyword so that I get more results
I’d really appreciate all the help I can get! thank you
///////////////////////////// Config your setup here! ////////////////////////////
// { site, parse token }
String imageService[][] = {
{
"http://twitpic.com",
"<img class=\"photo\" id=\"photo-display\" src=\""
},
{
"http://twitpic.com",
"<img class=\"photo\" id=\"photo-display\" src=\""
},
{
"http://img.ly",
"<img alt=\"\" id=\"the-image\" src=\""
},
{
"http://lockerz.com/",
"<img id=\"photo\" src=\""
},
{
"http://instagr.am/",
"<meta property=\"og:image\" content=\""
} {
"http://pic.twitter.com",
"<img id
};
// This is where you enter your Oauth info
static String OAuthConsumerKey = KEY_HERE;
static String OAuthConsumerSecret = SECRET_HERE;
static String AccessToken = TOKEN_HERE;
static String AccessTokenSecret = TOKEN_SECRET_HERE;
cb.setIncludeEntitiesEnabled(true);
Twitter twitterInstance = new TwitterFactory(cb.build()).getInstance();
// if you enter keywords here it will filter, otherwise it will sample
String keywords[] = {
"#hashtag" //sample keyword!!!!!!!!
};
///////////////////////////// End Variable Config ////////////////////////////
TwitterStream twitter = new TwitterStreamFactory().getInstance();
PImage img;
boolean imageLoaded;
void setup() {
frameRate(10);
size(800, 600);
noStroke();
imageMode(CENTER);
connectTwitter();
twitter.addListener(listener);
if (keywords.length == 0) twitter.sample();
else twitter.filter(new FilterQuery().track(keywords));
}
void draw() {
background(0);
if (imageLoaded) image(img, width / 5, height / 5);
//image(loadImage((status.getUser().getImage())), (int)random(width*.45), height-(int)random(height*.4));
}
// Initial connection
void connectTwitter() {
twitter.setOAuthConsumer(OAuthConsumerKey, OAuthConsumerSecret);
AccessToken accessToken = loadAccessToken();
twitter.setOAuthAccessToken(accessToken);
}
// Loading up the access token
private static AccessToken loadAccessToken() {
return new AccessToken(AccessToken, AccessTokenSecret);
}
// This listens for new tweet
StatusListener listener = new StatusListener() {
//#Override
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
//#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
//#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
//#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
//#Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
//#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
public void onStatus(Status status) {
String imgUrl = null;
String imgPage = null;
// Checks for images posted using twitter API
if (status.getMediaEntities() != null) {
imgUrl = status.getMediaEntities()[0].getMediaURL().toString();
}
// Checks for images posted using other APIs
else {
if (status.getURLEntities().length > 0) {
if (status.getURLEntities()[0].getExpandedURL() != null) {
imgPage = status.getURLEntities()[0].getExpandedURL().toString();
} else {
if (status.getURLEntities()[0].getDisplayURL() != null) {
imgPage = status.getURLEntities()[0].getDisplayURL().toString();
}
}
}
if (imgPage != null) imgUrl = parseTwitterImg(imgPage);
}
if (imgUrl != null) {
println("found image: " + imgUrl);
// hacks to make image load correctly
if (imgUrl.startsWith("//")) {
println("s3 weirdness");
imgUrl = "http:" + imgUrl;
}
if (!imgUrl.endsWith(".jpg")) {
byte[] imgBytes = loadBytes(imgUrl);
saveBytes("tempImage.jpg", imgBytes);
imgUrl = "tempImage.jpg";
}
println("loading " + imgUrl);
img = loadImage(imgUrl);
imageLoaded = true;
}
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
public void onException(Exception ex) {
ex.printStackTrace();
}
// Twitter doesn't recognize images from other sites as media, so must be parsed manually
// You can add more services at the top if something is missing
String parseTwitterImg(String pageUrl) {
for (int i = 0; i < imageService.length; i++) {
if (pageUrl.startsWith(imageService[i][0])) {
String fullPage = ""; // container for html
String lines[] = loadStrings(pageUrl); // load html into an array, then move to container
for (int j = 0; j < lines.length; j++) {
fullPage += lines[j] + "\n";
}
String[] pieces = split(fullPage, imageService[i][1]);
pieces = split(pieces[1], "\"");
return (pieces[0]);
}
}
return (null);
}

Acumatica PXDefault Drop List

I'm trying to change the default value to Debit Memo when adding a new row in the Payments and Applications screen of the Accounts Receivable module. I've tried setting PXDefault(ARDocType.DebitMemo), but it doesn't appear to be working. Can anyone point me in the right direction?
The payments and applications page uses some interesting logic to determine the default value used, they define it in a call during the rowselected event for the header document.
protected virtual void ARPayment_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{
.....
SetDocTypeList(e.Row);
.....
}
public static void SetDocTypeList(PXCache cache, string docType)
{
string defValue = ARDocType.Invoice;
List<string> values = new List<string>();
List<string> labels = new List<string>();
if (docType == ARDocType.Refund)
{
defValue = ARDocType.CreditMemo;
values.AddRange(new string[] { ARDocType.CreditMemo, ARDocType.Payment, ARDocType.Prepayment });
labels.AddRange(new string[] { Messages.CreditMemo, Messages.Payment, Messages.Prepayment });
}
else if (docType == ARDocType.Payment || docType == ARDocType.VoidPayment)
{
values.AddRange(new string[] { ARDocType.Invoice, ARDocType.DebitMemo, ARDocType.CreditMemo, ARDocType.FinCharge });
labels.AddRange(new string[] { Messages.Invoice, Messages.DebitMemo, Messages.CreditMemo, Messages.FinCharge });
}
else
{
values.AddRange(new string[] { ARDocType.Invoice, ARDocType.DebitMemo, ARDocType.FinCharge });
labels.AddRange(new string[] { Messages.Invoice, Messages.DebitMemo, Messages.FinCharge });
}
if (!PXAccess.FeatureInstalled<FeaturesSet.overdueFinCharges>() && values.Contains(ARDocType.FinCharge) && labels.Contains(Messages.FinCharge))
{
values.Remove(ARDocType.FinCharge);
labels.Remove(Messages.FinCharge);
}
PXDefaultAttribute.SetDefault<ARAdjust.adjdDocType>(cache, defValue);
PXStringListAttribute.SetList<ARAdjust.adjdDocType>(cache, null, values.ToArray(), labels.ToArray());
}
private void SetDocTypeList(object Row)
{
ARPayment row = Row as ARPayment;
if (row != null)
{
SetDocTypeList(Adjustments.Cache, row.DocType);
}
}
To obtain the default you require you may implement the following code :
public class ARPaymentEntryExtension : PXGraphExtension<ARPaymentEntry>
{
protected virtual void ARPayment_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{
PXDefaultAttribute.SetDefault<ARAdjust.adjdDocType>(Base.Adjustments.Cache, ARDocType.DebitMemo);
}
}

Spring mvc When using enctype="multipart/form-data" modelAttribute values equal null in the controller

I use spring mvc I want to uplaod image to jsp form so I add enctype="multipart/form-data" to the form tag but when i add this, modelAttribute values equals null in the controller
This is my form in jsp page:
<form:form action="saveContact" method="post" modelAttribute="Contacting" id="container" enctype="multipart/form-data">
This is the header of the function in controller:
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute ("Contacting") Contacting Contacting,ModelAndView modelndView,HttpServletRequest request ,HttpServletResponse response
) throws Exception {............}
#ModelAttribute ("Contacting") Contacting Contacting all values are null. and When I erease the enctype="multipart/form-data" from form tag its work well but I cant upload the image
this is the uplaud function:
public void uplaodImages(String url,HttpServletRequest request) {
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uuidValue = "";
FileItem itemFile = null;
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields to get UUID Value
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase(UUID_STRING)) {
uuidValue = item.getString();
}
}
// processes only fields that are not form fields
if (!item.isFormField()) {
itemFile = item;
}
}
if (itemFile != null) {
// get item inputstream to upload file into s3 aws
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);
AmazonS3 s3client = new AmazonS3Client(awsCredentials);
try {
ObjectMetadata om = new ObjectMetadata();
om.setContentLength(itemFile.getSize());
om.setContentType("image/png");
String ext = FilenameUtils.getExtension(itemFile.getName());
String keyName = uuidValue + '.' + ext;
// s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME,"99/after/img", itemFile,st om));
// s3client.setObjectAcl(S3_BUCKET_NAME, "99/after/img", CannedAccessControlList.PublicRead);
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
System.out.println("Hello");
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload1 = tm.upload(
S3_BUCKET_NAME, url, itemFile.getInputStream(),om);
System.out.println("Hello2");
try {
// Or you can block and wait for the upload to finish
upload1.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload was aborted.");
amazonClientException.printStackTrace();
}
} catch (AmazonServiceException ase) {
// LOGGER.error(uuidValue + ":error:" + ase.getMessage());
} catch (AmazonClientException ace) {
//LOGGER.error(uuidValue + ":error:" + ace.getMessage());
}
} else {
//LOGGER.error(uuidValue + ":error:" + "No Upload file");
System.out.println("No Upload file");
}
} catch (Exception ex) {
//LOGGER.error(uuidValue + ":" + ":error: " + ex.getMessage());
System.out.println(ex.getMessage());
}
//LOGGER.info(uuidValue + ":Upload done");
System.out.println("Upload done");
}
#RequestMapping(value = "/form.html", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) throws Exception {
}

Primefaces Print Dynamic Images

I tried to load an image dynamically, and everything works.
The image I is loaded and displayed correctly in a dynamic,
I added the tag for printing.
Now if I ask to print the image created dynamically I can not print.
<pou:commandButton value="Print" type="button" icon="ui-icon-print">
<pou:printer target="image" />
</pou:commandButton>
<pou:graphicImage id="image" value="#{printDynamicBean.graphicIMG}" />
My bean does like this:
public StreamedContent getGraphicIMG() {
//Graphic
BufferedImage bufferedImg;
try {
bufferedImg = ImageIO.read(baseImage);
} catch (IOException e) {
}
try {
Graphics2D g2 = bufferedImg.createGraphics();
g2.setColor(Color.black);
int style = Font.BOLD | Font.ITALIC;
Font f1 = new Font("TimesNewRoman", style , 60);
g2.setFont(f1);
g2.drawString("Hello Print", 80, 580);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImg, "png", os);
graphicIMG = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
} catch (IOException ex) {
Logger.getLogger(PrintCartelliniBean.class.getName()).log(Level.SEVERE, null, ex);
}
return graphicIMG;
}
it is as if she had forgotten the image created.
Thanks.
using CDI bean you can do this :
#Model
public class ImageBean {
private StreamedContent image;
#Produces
#Named
public StreamedContent getImage() {
if (FacesContext.getCurrentInstance().getRenderResponse()) {
// rendering the view, return a stub StreamedContent to generate right URL.
image = new DefaultStreamedContent();
} else {
// requesting the image
image = your dynamic image;
}
return image;
}
}
in your view : <pou:graphicImage id="image" value="#{image}" />

ICEfaces multiple selectInputText widgets inside datatable behave erratically

I have multiple selectInputText controls inside a datatable, something like this:
<ice:dataTable id="attributesList" value="#{myForm.myAttributes}" var="entry" cellpadding="0" rows="9999" columnClasses="myColumn,myColumn">
<ice:column>
<!-- auto-complete -->
<ice:panelGroup>
<ice:selectInputText rows="15" width="120" maxlength="255" value="#{entry.attribute.stringValue}" valueChangeListener="#{myFieldAutocomplete.updateList}" immediate="true">
<f:selectItems value="#{myFieldAutocomplete.list}" />
<f:attribute name="fieldName" value="#{entry.name}" />
</ice:selectInputText>
</ice:panelGroup>
</ice:column>
</ice:dataTable>
My backing bean code is this:
public class myFieldAutocomplete {
// default value, empty string
private String currentFieldValue = "";
// list of possible matches.
private List<SelectItem> matchesSIList = new ArrayList<SelectItem>();
public void updateList(ValueChangeEvent event) {
currentFieldValue = "";
// get a new list of matches.
setMatches(event);
if (event.getComponent() instanceof SelectInputText) {
SelectInputText autoComplete = (SelectInputText) event.getComponent();
if (autoComplete.getSelectedItem() != null) {
currentFieldValue = (String) autoComplete.getSelectedItem().getValue();
}
else {
String tempValue = getMatch(autoComplete.getValue().toString());
if(tempValue != null) {
currentFieldValue = tempValue;
}
}
}
}
public String getCurrentFieldValue() {
return currentFieldValue;
}
public List<SelectItem> getList() {
return matchesSIList;
}
private String getMatch(String value) {
String result = null;
if (matchesSIList != null) {
String str;
Iterator<SelectItem> itr = matchesSIList.iterator();
while (itr.hasNext()) {
SelectItem si = (SelectItem) itr.next();
str = (String) si.getValue();
if (str.startsWith(value)) {
result = str;
break;
}
}
}
return result;
}
public void setMatches(ValueChangeEvent event) {
List<String> newMatchesStrList = new ArrayList<String>();
if (event.getComponent() instanceof SelectInputText) {
SelectInputText autoComplete = (SelectInputText) event.getComponent();
myClassDAO myDao = (myClassDAO) Context.getInstance().getBean(myClassDAO.class);
String fieldName = (String) autoComplete.getAttributes().get("fieldName");
newMatchesStrList = myDao.findTemplateFieldValues((String)autoComplete.getValue(), fieldName);
}
// assign new matchList
if (this.matchesSIList != null) {
this.matchesSIList.clear();
}
Iterator<String> itr = newMatchesStrList.iterator();
while(itr.hasNext()) {
String str = (String) itr.next();
matchesSIList.add(new SelectItem(str, str));
}
}
}
The bean is in request scope (although I also tried with session scope). I am using ICEfaces community edition 1.8.2.
The problem is, these auto-complete controls are created dynamically based on certain attributes of each entry in the datatable. So, you can have, for example 2 or more such auto-complete controls in the same panelGroup. When this is the case, when you start typing something the first control, it seems to be triggering the event for all sibling auto-complete controls, and in the end returns the list for the last in order.
In general, I noticed erratic behavior caused by the fact that the event is triggered for all auto-complete controls at once, and values/lists get confused.
What am I doing wrong?
Thanks in advance!

Resources