I am trying to change image inside Image view.
I know that getTestImageField().setImageId(Icons.Logo); would not work, because it would not refresh renderer.
Because I need to use setImage(), I need a way to get Image from Icons class.
As Patrick suggested I try
final IconProviderService provider = SERVICES.getService(IconProviderService.class);
final IconSpec ic = provider.getIconSpec(AbstractIcons.StatusError);
final byte[] content = ic.getContent();
but my problem is that ic is always null.
While I debug this I notice that inside IconProviderService.class in line 57 :
#Override
protected URL findResource(String fullPath) {
URL[] entries = FileLocator.findEntries(m_hostBundle, new Path(fullPath));
if (entries != null && entries.length > 0) {
URL url = entries[entries.length - 1];
if (LOG.isDebugEnabled()) {
LOG.debug("find image " + fullPath + " in bundle " + m_hostBundle.getSymbolicName() + "->" + url);
}
return url;
}
return null;
}
URL[] entries is always empty no matter witch icon I try to present.
After further debugging I found out that FileLocator tries to find fragments from bundle, and then look for the path inside this fragments. (line 242)
Bundle[] fragments = activator.getFragments(b);
but Bundle[] fragments is always null.
Normally my bundle b is (Bundle) EquinoxBundle : org.eclipse.scout.rt.ui.rap.mobile_4.0.100.20140829-1424.
I want to try with different bundle so I do :
final BundleContext context = Activator.getDefault().getBundle().getBundleContext();
for (final Bundle b : context.getBundles()) {
final IconProviderService provider = SERVICES.getService(IconProviderService.class);
provider.setHostBundle(b);
final IconSpec ic = provider.getIconSpec(AbstractIcons.StatusError);
if (ic != null) {
final byte[] content = ic.getContent();
imageField().setImage(content);
}
}
but fragments (from above code) is always null.
You can obtain the image content (byte[]) that you can set on the image field as follows:
IconProviderService provider = SERVICES.getService(IconProviderService.class);
byte[] content = provider.getIconSpec(Icons.YourIconName).getContent();
getImageField().setImage(content);
I quickly checked it and it works for me.
Please ensure that the icon is available and you set up the icon provider service as explained in this Wiki Article
Related
I have found some plugin code on the web that enables me to get the entity ID and the object type code for an entity in a plugin. The plugin is fired on RetrieveMultiple on activitypointer. The code lets me get the id and object code of the entity that is currently being viewed (which is displaying the activities grid which is firing the plugin).
This code works fine when using the web interface. However I need it to also work in the Outlook preview pane and currently it does not. The activities grid in the Outlook preview pane just says "an error has occurred". Below is the code that the plugin is using to get the details from the web header.
internal static Dictionary<string, string> GetHeaderFields(HttpContext webcontext, string objectTypeCode, string objectId)
{
Dictionary<string, string> fields = new Dictionary<string, string>();
string callerentitytype = null;
string callerentityidstring = null;
try
{
// Activities Navigation Pane
if (new List<string>(webcontext.Request.Params.AllKeys).Contains("oType"))
{
callerentitytype = webcontext.Request.Params["oType"];
callerentityidstring = webcontext.Request.Params["oId"];
}
// Activities Sub Grid
else
{
string requeststring = webcontext.Request.UrlReferrer.Query;
requeststring = requeststring.Substring(1);
string[] parts = requeststring.Split(new string[] { "=", "&" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length - 1; i++)
if (parts[i].ToLower() == "otype" || parts[i].ToLower() == "etc")
callerentitytype = parts[i + 1];
else if (parts[i].ToLower() == "oid" || parts[i].ToLower() == "id")
callerentityidstring = parts[i + 1];
}
fields.Add(objectTypeCode, callerentitytype);
fields.Add(objectId, callerentityidstring);
}
catch (Exception ex)
{
throw new Plugin.LoggableException(string.Format("Failed to obtain header information; {0}", ex.Message), ex.InnerException);
}
return fields;
}
The reason is that webcontext.Request.UrlReferrer is NULL. Is there anywhere else I can get this info of the 'calling' entity? (Not the activity sub grid that is triggering the plugin, but the actual parent entity that the sub grid is on).
Thanks for any help or direction with this.
This might work. Each of the activitypointers that are returned should all be "regarding" the same record (if in a sub grid). If you take say the 1st one and examine the regardingobjectid property, that should be an entity reference which will give you the logical name of the parent and it's guid. If that works, it will work across all clients (in theory anyway).
I'm trying to query for some files in Alfresco using SearchService; my idea is:
1) get folder's noderef where I want to search in for files
2) then get noderef's path via NodeService
3) finally query Solar via SearchService to find files in that specific path
The problem raises when querying to Solr, I get the following exception:
ERROR [solr.core.SolrCore] [http-bio-8443-exec-1] org.apache.solr.common.SolrException: org.apache.lucene.queryParser.ParseException: **Cannot parse** 'PATH:"/{http\://www.alfresco.org/model/application/1.0}company_home/{http\://www.alfresco.org/model/application/1.0}user_homes/{http\://www.alfresco.org/model/content/1.0}abeecher/{http\://www.alfresco.org/model/content/1.0}nominas//*"': **Failed to parse XPath**...
Unexpected '{http://www.alfresco.org/model/application/1.0}company_home/{http://www.alfresco.org/model/application/1.0}user_homes/{http://www.alfresco.org/model/content/1.0}abeecher/{http://www.alfresco.org/model/content/1.0}nominas//*'
If I replace the full prefixes by prefixes of type cm: etc... the query works well.
Is there any "Alfresco Way" to do this instead of transforming the string with a regex? Or am I doing something wrong?
Code I'm using is:
Path path3 = nodeService.getPath(folder);
SearchParameters sp = new SearchParameters();
sp.addStore(Repository.getStoreRef());
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
sp.setQuery("PATH:\"/{http://www.alfresco.org/model/application/1.0}company_home/{http://www.alfresco.org/model/application/1.0}user_homes/{http://www.alfresco.org/model/content/1.0}abeecher/{http://www.alfresco.org/model/content/1.0}nominas//*\"");
//sp.setQuery(path3);
//sp.setQuery(path3.toString());
ResultSet results = null;
results = searchService.query(sp);
afaik PATH-Queries using full namespace syntax is not supported. Take a look here: http://wiki.alfresco.com/wiki/Search#Path_Queries
You'll have to use the prefix version. But, please don't use a regex to get the prefix. There is an org.alfresco.service.namespace.NamespacePrefixResolver (bean NamespaceService) taht defines a method Collection<String> getPrefixes(String namespaceURI).
your dummy code to get the QNamePath of a node:
Path path = nodeService.getPath(folder);
final Map<String, String> cache = new HashMap<String, String>();
final StringBuilder buf = new StringBuilder(128);
for (final Path.Element e : path)
{
if (e instanceof Path.ChildAssocElement)
{
final QName qname = ((Path.ChildAssocElement)e).getRef().getQName();
if (qname != null)
{
String prefix = cache.get(qname.getNamespaceURI());
if (prefix == null)
{
// first request for this namespace prefix, get and cache result
Collection<String> prefixes = ns.getPrefixes(qname.getNamespaceURI());
prefix = prefixes.size() != 0 ? prefixes.iterator().next() : "";
cache.put(qname.getNamespaceURI(), prefix);
}
buf.append('/').append(prefix).append(':').append(ISO9075.encode(qname.getLocalName()));
}
}
else
{
buf.append('/').append(e.toString());
}
}
String searchPath = buf.toString();
I am doing a portlet to create banners. I preferences I made the form with: input type="file" and the form nctype='multipart/form-data'
In the processAction I get the image, but I don't know how save it in the server, because I only get save in temporal instance portlet, but if I restart the server I lose the image.
This is my code to save the image:
private boolean uploadFile( ActionRequest request, ActionResponse response) throws ValidatorException, IOException, ReadOnlyException {
try {
// Si la request es del tipo multipart ...
if (PortletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
PortletFileUpload servletFileUpload = new PortletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(81920); // bytes
List fileItemsList = servletFileUpload.parseRequest(request);
Iterator it = fileItemsList.iterator();
while (it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if (fileItem.isFormField()){
}
else{
String nombreCampo = fileItem.getFieldName();
String nombreArchivo = fileItem.getName();
String extension = nombreArchivo.substring(nombreArchivo.indexOf("."));
PortletContext context = request.getPortletSession().getPortletContext();
String path = context.getRealPath("/images");
File archivo = new File(path + "/" + nombreArchivo);
PortletContext pc = request.getPortletSession().getPortletContext();
fileItem.write(archivo);
}
}
}
} catch (Exception e) {}
return true;
}
I don't know if I am doing something wrong or this isn't the correct way.
Any idea?
Thanks in advance
EDIT:
Finally I tried do it with DLFolderLocalServiceUtil and DLFileEntryLocalServiceUtil, but it doesn't work correctly. When I load the page you can see the image, but after, when the page is load completely, the image disappears.
I don't know if it is because I don't create fine the fileEntry or the url is wrong.
This is my code:
long folderId = CounterLocalServiceUtil.increment(DLFolder.class.getName());
DLFolder folder = DLFolderLocalServiceUtil.createDLFolder(folderId);
long userId = themeDisplay.getUserId();
long groupId = themeDisplay.getScopeGroupId();
folder.setUserId(userId);
folder.setGroupId(groupId);
folder.setName("Banner image " + nombreArchivo+String.valueOf(folderId));
DLFolderLocalServiceUtil.updateDLFolder(folder);
ServiceContext serviceContext= ServiceContextFactory.getInstance(DLFileEntry.class.getName(), request);
File myfile = new File(nombreArchivo);
fileItem.write(myfile);
List<DLFileEntryType> tip = DLFileEntryTypeLocalServiceUtil.getFileEntryTypes(DLUtil.getGroupIds(themeDisplay));
DLFileEntry DLfileEntry = DLFileEntryLocalServiceUtil.addFileEntry(userId, groupId, 0, folderId, null, MimeTypesUtil.getContentType(myfile), nombreArchivo, "Image banner_"+nombreArchivo, "", tip.get(0).getFileEntryTypeId(), null, myfile, fileItem.getInputStream(), myfile.getTotalSpace(), serviceContext);
FileVersion fileVersion = null;
//FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, nombreArchivo);
//String path = DLUtil.getPreviewURL(fileEntry, fileVersion, themeDisplay, "&imagePreview=1");
String path1 = themeDisplay.getPortalURL()+"/c/document_library/get_file?uuid="+DLfileEntry.getUuid()+"&groupId="+themeDisplay.getScopeGroupId();
String path = "/documents/" + DLfileEntry.getGroupId() + "/" + DLfileEntry.getFolderId() + "/" + DLfileEntry.getTitle()+"/"+DLfileEntry.getUuid();
System.out.println("path " + path);
System.out.println("path " + path1);
prefs.setValue(nombreCampo, path);
And this is the output:
path /documents/10180/0/cinesa888.png/f24e6da2-0be8-47ad-a3b5-a4ab0d41d17f
path http://localhost:8080/c/document_library/get_file?uuid=f24e6da2-0be8-47ad-a3b5-a4ab0d41d17f&groupId=10180
I tried to get the url like lpratlong said (DLUtil) but when I tried to get the FileEntry with DLAppServiceUtil.getFileEntry(..) I have an error that says no exist FileEntry.
I don't know what I am doing wrong.. Any idea?
Thanks.
You can use Liferay API to store the file in the Document Library : take a look in DLFolder and DLFileEntry API (for exemple, DLFileEntryLocalServiceUtil will show you allowed local operations).
These API will allowed you to store your file in your file system (in the "data" folder of your Liferay installation) and to store reference of your file in Liferay database.
When I have an app.net url like https://photos.app.net/5269262/1 - how can I retrieve the image thumbnail of the post?
Running a curl on above url shows a redirect
bash-3.2$ curl -i https://photos.app.net/5269262/1
HTTP/1.1 301 MOVED PERMANENTLY
Location: https://alpha.app.net/pfleidi/post/5269262/photo/1
Following this gives a html page that contains the image in a form of
img src='https://files.app.net/1/60621/aWBTKTYxzYZTqnkESkwx475u_ShTwEOiezzBjM3-ZzVBjq_6rzno42oMw9LxS5VH0WQEgoxWegIDKJo0eRDAc-uwTcOTaGYobfqx19vMOOMiyh2M3IMe6sDNkcQWPZPeE0PjIve4Vy0YFCM8MsHWbYYA2DFNKMdyNUnwmB2KuECjHqe0-Y9_ODD1pnFSOsOjH' data-full-width='2048' data-full-height='1536'
Inside a larger block of <div>tags.
The files api in app.net allows to retrieve thumbnails but I somehow don't get the link between those endpoints and above urls.
The photos.app.net is just a simple redirecter. It is not part of the API proper. In order to get the thumbnail, you will need to fetch the file directly using the file fetch endpoint and the file id (http://developers.app.net/docs/resources/file/lookup/#retrieve-a-file) or fetch the post that the file is included in and examine the oembed annotation.
In this case, you are talking about post id 5269262 and the URL to fetch that post with the annotation is https://alpha-api.app.net/stream/0/posts/5269262?include_annotations=1 and if you examine the resulting json document you will see the thumbnail_url.
For completeness sake I want to post the final solution for me here (in Java) -- it builds on the good and accepted answer of Jonathon Duerig :
private static String getAppNetPreviewUrl(String url) {
Pattern photosPattern = Pattern.compile(".*photos.app.net/([0-9]+)/.*");
Matcher m = photosPattern.matcher(url);
if (!m.matches()) {
return null;
}
String id = m.group(1);
String streamUrl = "https://alpha-api.app.net/stream/0/posts/"
+ id + "?include_annotations=1";
// Now that we have the posting url, we can get it and parse
// for the thumbnail
BufferedReader br = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(streamUrl).openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(false);
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.connect();
StringBuilder builder = new StringBuilder();
br = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line=br.readLine())!=null) {
builder.append(line);
}
urlConnection.disconnect();
// Parse the obtained json
JSONObject post = new JSONObject(builder.toString());
JSONObject data = post.getJSONObject("data");
JSONArray annotations = data.getJSONArray("annotations");
JSONObject annotationValue = annotations.getJSONObject(0);
JSONObject value = annotationValue.getJSONObject("value");
String finalUrl = value.getString("thumbnail_large_url");
return finalUrl;
} .......
I am developing a sample Twitter app for Windows phone 7. In my code to display some details of user, used the following code.
void ShowProfile()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Profile_DownloadCompleted);
client.DownloadStringAsync(new Uri("http://api.twitter.com/1/users/show.xml?user_id=" + this.id));
}
void Profile_DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{ return; }
if (e.Result == null) MessageBox.Show("NUlllllllllll");
XElement Profile = XElement.Parse(e.Result);
var ProfileDetails = (from profile in Profile.Descendants("user")
select new UserProfile
{
UserName = profile.Element("screen_name").Value,
ImageSource = profile.Element("profile_image_url").Value,
Location = profile.Element("location").Value,
TweetsCount = profile.Element("statuses_count").Value,
}).FirstOrDefault();
LayoutRoot.DataContext = ProfileDetails;
}
Here, LayoutRoot is the Grid name. But the data binding doesn't work.
Infact, when kept a Break point it seems there is no data in the ProfileDetails object. But I could observe that e.Result contains the required data in the XML format.
Can any body figureout where I am going wrong??
Thanks in advance.
You have used XElement.Parse so Profile represents the single root <user> that API request would have returned. You are then trying to look for user elements inside it which of course makes no sense.
Try XDocument.Parse instead. Also does it really make any sense assigning a IEnumerable<UserProfile> to the data context when that list can only ever contain 1 entry?