CustomResourceHandler -> Version number is added to resources twice - primefaces

I've written an CustomResourceHandler to add a version number to my js and css files, which works fine, but all primefaces resources get a double version number now.
Without CustomResourceHandler:
javax.faces.resource/jquery/jquery-plugins.js.xhtml?ln=primefaces&v=6.0.17
With CustomResourceHandler:
javax.faces.resource/jquery/jquery-plugins.js.xhtml?ln=primefaces&v=6.0.17&v=6.0.17
My CustomResourceHandler:
public class ExtendedResourceHandler extends PrimeResourceHandler {
public ExtendedResourceHandler(ResourceHandler wrapped) {
super(wrapped);
}
#Override
public Resource createResource(String resourceName, String libraryName) {
if (!org.primefaces.util.Constants.LIBRARY.equalsIgnoreCase(libraryName)
&& !org.primefaces.extensions.util.Constants.LIBRARY.equalsIgnoreCase(libraryName) && !"javax.faces".equalsIgnoreCase(libraryName) && resourceName != null
&& (resourceName.endsWith(".css") || resourceName.endsWith(".js"))) {
final Resource resource = super.createResource(resourceName, libraryName);
if (resource == null) {
return null;
}
return new ResourceWrapper() {
#Override
public String getRequestPath() {
String resultPath = super.getRequestPath();
resultPath += (resultPath.contains("?") ? "&" : "?") + "version=V6326";
return resultPath;
}
#Override
public Resource getWrapped() {
return resource;
}
};
} else {
return super.createResource(resourceName, libraryName);
}
}
}
faces-config.xml:
<resource-handler>de.sync4.cockpit.web.beans.resourcehandler.ExtendedResourceHandler</resource-handler>
Because of that problem I can't get the pe:ckEditor to work, because it can't find necessary resources. Any idea what's wrong with my Handler?

Found the Problem. I needed to extend the ResourceHandlerWrapper, not the PrimeResourceHandler.
I also have an ExtendedBeanELResolver. I had to return null there if the base object is an instance of my custom handler.

Related

GeoDataApi.getAutocompletePredictions not working

I am building an android application that shows autocomplete feature and fetches autocomplete predictions in google maps using - GeoDataApi.getAutocompletePredictions. I followed this tutorial - https://github.com/googlesamples/android-play-places/blob/master/PlaceComplete/Application/src/main/java/com/example/google/playservices/placecomplete/PlaceAutocompleteAdapter.java
But somehow this is not working fine for me.
My class is this -
public class GooglePlacesAutoCompleteAdapter extends ArrayAdapter implements Filterable {
private ArrayList<PlaceAutocomplete> mResultList;
GoogleApiClient mGoogleApiClient;
private LatLngBounds mBounds;
private AutocompleteFilter mPlaceFilter;
int radius = 500;
public GooglePlacesAutoCompleteAdapter(Context context, int textViewResourceId, GoogleApiClient googleApiClient,
Location lastLocation, AutocompleteFilter filter) {
super(context, textViewResourceId);
LatLng currentLatLng = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
mBounds = Utility.boundsWithCenterAndLatLngDistance(currentLatLng, 500, 500);
mGoogleApiClient = googleApiClient;
mPlaceFilter = filter;
}
#Override
public int getCount() {
return mResultList.size();
}
#Override
public PlaceAutocomplete getItem(int index) {
return mResultList.get(index);
}
#Override
public android.widget.Filter getFilter() {
Filter filter = new Filter() {
#Override
public FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null && constraint.length() > 3 && constraint.length()%3 == 1) {
// Retrieve the autocomplete results.
mResultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = mResultList;
filterResults.count = mResultList.size();
}
return filterResults;
}
#Override
public void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
public ArrayList<PlaceAutocomplete> autocomplete(String input) {
if (mGoogleApiClient.isConnected()) {
// Submit the query to the autocomplete API and retrieve a PendingResult that will
// contain the results when the query completes.
PendingResult results = Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, input.toString(),
mBounds, mPlaceFilter);
// This method should have been called off the main UI thread. Block and wait for at most 60s
// for a result from the API.
AutocompletePredictionBuffer autocompletePredictions = (AutocompletePredictionBuffer)results.await(60, TimeUnit.SECONDS);
// Confirm that the query completed successfully, otherwise return null
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
//Toast.makeText(getContext(), "Error contacting API: " + status.toString(),Toast.LENGTH_SHORT).show();
//Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
// Copy the results into our own data structure, because we can't hold onto the buffer.
// AutocompletePrediction objects encapsulate the API response (place ID and description).
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
// Get the details of this prediction and copy it into a new PlaceAutocomplete object.
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getDescription()));
}
// Release the buffer now that all data has been copied.
autocompletePredictions.release();
return resultList;
}
//Log.e(TAG, "Google API client is not connected for autocomplete query.");
return null;
}
class PlaceAutocomplete {
public CharSequence placeId;
public CharSequence description;
PlaceAutocomplete(CharSequence placeId, CharSequence description) {
this.placeId = placeId;
this.description = description;
}
#Override
public String toString() {
return description.toString();
}
}
}
The line on which GeoDataApi.getAutocompletePredictions is called, goes into an internal classes called - Filter.java, Log.java, handler.java and then Looper.java and loops there indefinetly on line 121 of Looper.java (I am sure studio sdk will show the code for Looper.java).
It is not even throwing an error, or going to the next line, it just does not work. Plus, I am not able to see the stack trace of an error.
This is the code snippet which is calling this -
if (mLastLocation != null) {
GooglePlacesAutoCompleteAdapter placesAdapter = new GooglePlacesAutoCompleteAdapter(this, R.layout.item_list, mGoogleApiClient, mLastLocation, null);
autoCompView.setAdapter(placesAdapter);
autoCompView.setOnItemClickListener(this);
}
Can someone please tell me what I am doing wrong here? Please any help will be greatly appreciated. I need to get this working as soon as I could.
PS - I am passing mPlaceFilter as null here.
Enable the Google Places API for Android in developers console

Windows Phone 8 ImageSource cannot be serialized Error while sharing image

i am trying to share an image. I got a picture object and am getting the path from it. When I'm calling the ShareMediaTask it throw following error:
System.Windows.Media.ImageSource cannot be serialized.
I am still able to share the image, but the app crashes when returning from sharing.
Here is my code:
PictureModel picture = Singleton.Instance.BearPicture.Model.Images.Where(PictureModel => PictureModel.Bmp.UriSource == (Image_View.Source as BitmapImage).UriSource).FirstOrDefault();
var task = new ShareMediaTask();
task.FilePath = picture.Picture.GetPath();
task.Show();
My PictureModel looks like this:
public class PictureModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _uri;
public string Uri
{
get { return _uri; }
set
{
if (value != _uri)
{
_uri = value;
NotifyPropertyChanged("Uri");
}
}
}
private string _relativePath;
public string RelativePath
{
get { return _relativePath; }
set
{
if (_relativePath != value)
{
_relativePath = value;
NotifyPropertyChanged("RelativePath");
}
}
}
private BitmapImage _bmp;
public BitmapImage Bmp
{
get { return _bmp; }
set
{
if (value != _bmp)
{
_bmp = value;
NotifyPropertyChanged("Bmp");
}
}
}
private Picture _picture;
public Picture Picture
{
get { return _picture; }
set
{
if (value != _picture)
{
_picture = value;
NotifyPropertyChanged("Picture");
}
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Where does this error come from? I am only getting the Source of my image object but i am not doing anything else with it. My picture is also saved in the media library like this:
myFileStream = myStore.OpenFile(fileName, FileMode.Open, FileAccess.Read);
MediaLibrary library = new MediaLibrary();
Picture pic = library.SavePicture(fileName, myFileStream);
On Appstart im searching through my savedpicture folder, to get the picture object, which is then saved in my PictureModel.
Any help is appreciated.
Thanks in advance.
robidd
This may help: Crashes Back (WriteableBitmap cannot be serialized) windows phone 8. See the comment from KooKiz.
"Same symptoms, same cause. You've stored at some point an ImageSource in the phone state (probably PhoneApplicationService.Current.State or IsolatedStorageSettings.ApplicationSettings). You have to find where!"
Apparently we can cause this error indirectly. I'm having a similar problem and I found that answer and also your own question.
Hope it helps.
Cheers.

Google end point returns JSON for long data type in quotes

I am using Google cloud end point for my rest service. I am consuming this data in a GWT web client using RestyGWT.
I noticed that cloud end point is automatically enclosing a long datatype in double quotes which is causing an exception in RestyGWT when I try to convert JSON to POJO.
Here is my sample code.
#Api(name = "test")
public class EndpointAPI {
#ApiMethod(httpMethod = HttpMethod.GET, path = "test")
public Container test() {
Container container = new Container();
container.testLong = (long)3234345;
container.testDate = new Date();
container.testString = "sathya";
container.testDouble = 123.98;
container.testInt = 123;
return container;
}
public class Container {
public long testLong;
public Date testDate;
public String testString;
public double testDouble;
public int testInt;
}
}
This is what is returned as JSON by cloud end point. You can see that testLong is serialized as "3234345" rather than 3234345.
I have the following questions.
(1) How can I remove double quotes in long values ?
(2) How can I change the string format to "yyyy-MMM-dd hh:mm:ss" ?
Regards,
Sathya
What version of restyGWT are you using ? Did you try 1.4 snapshot ?
I think this is the code (1.4) responsible for parsing a long in restygwt, it might help you :
public static final AbstractJsonEncoderDecoder<Long> LONG = new AbstractJsonEncoderDecoder<Long>() {
public Long decode(JSONValue value) throws DecodingException {
if (value == null || value.isNull() != null) {
return null;
}
return (long) toDouble(value);
}
public JSONValue encode(Long value) throws EncodingException {
return (value == null) ? getNullType() : new JSONNumber(value);
}
};
static public double toDouble(JSONValue value) {
JSONNumber number = value.isNumber();
if (number == null) {
JSONString val = value.isString();
if (val != null){
try {
return Double.parseDouble(val.stringValue());
}
catch(NumberFormatException e){
// just through exception below
}
}
throw new DecodingException("Expected a json number, but was given: " + value);
}
return number.doubleValue();
}

app certification requirements when returning from tombstoning

I have a page where user can enter his name and attach an image.
When returning from tombstoning state, is it mandatory for my app to restore the image too?
Is it app certification requirement, something without which my app will not pass certification? Or is it a recommended pattern?
same question in the case when I have a pivot for example, is it mandatory to save the index of selected pivot item and restore the selection when activating from tombstoning?
Not necessary:
Is there a popular library \ framework to help me with tombstoning and serializing objects, images, etc?
According to the Technical certification requirements for Windows Phone , the only requirements are :
A Windows Phone app is deactivated when the user presses the Start button or if the device timeout causes the lock screen to engage. A Windows Phone app is also deactivated with it invokes a Launcher or Chooser API.
A Windows Phone OS 7.0 app is tombstoned (terminated) when it is deactivated. A Windows Phone OS 7.1 or higher app becomes Dormant when it is deactivated but can be terminated by the system when resource use policy causes it to tombstone.
When activated after termination, the app must meet the requirements in Section 5.2.1 – Launch time.
As the section 5.2.1 - "Launch time" only concerns startup performance and responsiveness, you don't have a certification requirement for your issue.
However, if the user enters data (attaches images, etc.) and let's say it answer a call, does some other stuff and get's back to the application and then the data he entered was lost... it surely won't appreciate it. That will look more like a defect/bug.
Concerning the serialization of your state, I recommend you to use binary serialization as the performance is at least 10x better than using Json, Xml or any other format.
Personally, I implement a custom interface, IBinarySerializable to my "state" related classes and use this BinaryWriter extensions class to help writing the serialization code:
using System.IO;
namespace MyCompany.Utilities
{
public interface IBinarySerializable
{
void Write(BinaryWriter writer);
void Read(BinaryReader reader);
}
}
using System;
using System.Collections.Generic;
using System.IO;
namespace MyCompany.Utilities
{
public static class BinaryWriterExtensions
{
public static void Write<T>(this BinaryWriter writer, T value) where T : IBinarySerializable
{
if (value == null)
{
writer.Write(false);
return;
}
writer.Write(true);
value.Write(writer);
}
public static T Read<T>(this BinaryReader reader) where T : IBinarySerializable, new()
{
if (reader.ReadBoolean())
{
T result = new T();
result.Read(reader);
return result;
}
return default(T);
}
public static void WriteList<T>(this BinaryWriter writer, IList<T> list) where T : IBinarySerializable
{
if (list == null)
{
writer.Write(false);
return;
}
writer.Write(true);
writer.Write(list.Count);
foreach (T item in list)
{
item.Write(writer);
}
}
public static List<T> ReadList<T>(this BinaryReader reader) where T : IBinarySerializable, new()
{
bool hasValue = reader.ReadBoolean();
if (hasValue)
{
int count = reader.ReadInt32();
List<T> list = new List<T>(count);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
T item = new T();
item.Read(reader);
list.Add(item);
}
return list;
}
}
return null;
}
public static void WriteListOfString(this BinaryWriter writer, IList<string> list)
{
if (list == null)
{
writer.Write(false);
return;
}
writer.Write(true);
writer.Write(list.Count);
foreach (string item in list)
{
writer.WriteSafeString(item);
}
}
public static List<string> ReadListOfString(this BinaryReader reader)
{
bool hasValue = reader.ReadBoolean();
if (hasValue)
{
int count = reader.ReadInt32();
List<string> list = new List<string>(count);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
list.Add(reader.ReadSafeString());
}
return list;
}
}
return null;
}
public static void WriteSafeString(this BinaryWriter writer, string value)
{
if (value == null)
{
writer.Write(false);
return;
}
writer.Write(true);
writer.Write(value);
}
public static string ReadSafeString(this BinaryReader reader)
{
bool hasValue = reader.ReadBoolean();
if (hasValue)
return reader.ReadString();
return null;
}
public static void WriteDateTime(this BinaryWriter writer, DateTime value)
{
writer.Write(value.Ticks);
}
public static DateTime ReadDateTime(this BinaryReader reader)
{
var int64 = reader.ReadInt64();
return new DateTime(int64);
}
}
}

What's your most reused class?

Every programmer ends up with a set of utility classes after a while. Some of them are true programming pearls and they are reused in several of your projects. For example, in java:
class Separator {
private String separator;
private boolean called;
public Separator(String aSeparator) {
separator = aSeparator;
called = false;
}
#Override
public String toString() {
if (!called) {
called = true;
return "";
} else {
return separator;
}
}
}
and:
public class JoinHelper {
public static <T> String join(T... elements) {
return joinArray(" ", elements);
}
public static <T> String join(String separator, T... elements) {
return joinArray(separator, elements);
}
private static <T> String joinArray(String sep, T[] elements) {
StringBuilder stringBuilder = new StringBuilder();
Separator separator = new Separator(sep);
for (T element : elements) {
stringBuilder.append(separator).append(element);
}
return stringBuilder.toString();
}
}
What is your most reused class?
System.Object - almost all my types extend it.
A utility class that has logging and email functionality. An extensions class that contains extension methods. A reporting class that basically harness the reporting services web service and makes it easy to stream reports as excel, pdf, etc.
Examples...
1.) Utility Class (static)
public static void LogError(Exception ex)
{
EventLog log = new EventLog();
if (ex != null)
{
log.Source = ConfigurationManager.AppSettings["EventLog"].ToString();
StringBuilder sErrorMessage = new StringBuilder();
if (HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null)
{
sErrorMessage.Append(HttpContext.Current.Request.Url.ToString() + System.Environment.NewLine);
}
sErrorMessage.Append(ex.ToString());
log.WriteEntry(sErrorMessage.ToString(), EventLogEntryType.Error);
}
}
2.) Extensions Class
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
public static short getLastDayOfMonth(short givenMonth, short givenYear)
{
short lastDay = 31;
switch (givenMonth)
{
case 4:
case 6:
case 9:
case 11:
lastDay = 30;
break;
case 2:
if ((int)givenYear % 4 == 0)
{
lastDay = 29;
}
else
{
lastDay = 28;
}
break;
}
return lastDay;
}
Most reused but boring:
public static void handleException(Exception e) throws RuntimeException {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e); //NOPMD
}
Less boring (also methods for building lists and sets):
/**
* Builds a Map that is based on the Bean List.
*
* #param items Bean List items
* #param keyField Bean Field that will be key of Map elements (not null)
* #return a Map that is based on the Bean List
*/
#SuppressWarnings("unchecked")
public static <T, K> Map<K, T> buildMapFromCollection(final Collection<T> items,
boolean linkedMap,
final String keyField,
final Class<K> keyType) {
if (items == null) {
return Collections.emptyMap();
}
if (keyField == null) {
throw new IllegalArgumentException("KeyField is null");
}
final Map<K, T> result;
if (linkedMap) {
result = new LinkedHashMap<K, T>();
} else {
result = new HashMap<K, T>();
}
BeanMapper mapper = null;
for (final T item : items) {
if (mapper == null) {
mapper = new BeanMapper(item.getClass());
}
final K key = (K) mapper.getFieldValue(item, keyField);
result.put(key, item);
}
return result;
}
Logger class: Which logs the flow of control in a log file.
Configuration Reader/Setter: which reads the configuration from ini/xml file and sets the environment of the application
Most reused? Hmmm...
boost::shared_ptr<> with boost::weak_ptr<>
probably most reused (also probably most bang-for-buck ratio)
Globals
Just a simple class with static DBConnString, and a few other app wide settings.
Have reused the simple file in about 2 dozen projects since working with .Net
A ConcurrentDictionary I wrote, which I now seem to use everywhere (I write lots of parallel programs)