I am building a data transfer app using direct Wifi. I am getting the string value of extension from Uri in the onActivityResult method and storing it in Shared preferences.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String extension;
Uri uri = data.getData();
Context context = getActivity().getApplicationContext();
extension = "."+getMimeType(context, uri);
SharedPreferences sharedPreferences = myContext.getSharedPreferences(myName, MODE_PRIVATE);
SharedPreferences.Editor myEdit = sharedPreferences.edit();
myEdit.putString("hello", extension);
myEdit.apply();
}
It is working fine till now as the value of extension is storing in shared preferences successfully. Now, in the onConnectionInfoAvailable method (related to the broadcast receiver), I am calling an AsyncTask.
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
new FileServerAsyncTask().execute();
}
Now, I want to get the shared preference value in doInBackground method of AsyncTask. But I am not getting the value of extension from shared preferences, although my code is working fine. Please help.
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
SharedPreferences sh = myContext.getSharedPreferences(myName, MODE_PRIVATE);
String extension = sh.getString("hello", "no");
}....
Note: myContext and myName are defined as public static variables.
Related
I'm trying to rewrite some legacy code which used org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore to store the access tokens. I'm currently trying to use the RedisTokenStore instead of the previously used InMemoryTokenStore. The token gets generated and gets stored in Redis fine (Standalone redis configuration), however, deserialization of OAuth2Authentication fails with the following error:
Could not read JSON: Cannot construct instance of `org.springframework.security.oauth2.provider.OAuth2Authentication` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
Since there's no default constructor for this class, the deserialization and mapping to the actual object while looking up from Redis fails.
RedisTokenStore redisTokenStore = new RedisTokenStore(jedisConnectionFactory);
redisTokenStore.setSerializationStrategy(new StandardStringSerializationStrategy() {
#Override
protected <T> T deserializeInternal(byte[] bytes, Class<T> aClass) {
return Utilities.parse(new String(bytes, StandardCharsets.UTF_8),aClass);
}
#Override
protected byte[] serializeInternal(Object o) {
return Objects.requireNonNull(Utilities.convert(o)).getBytes();
}
});
this.tokenStore = redisTokenStore;
public static <T> T parse(String json, Class<T> clazz) {
try {
return OBJECT_MAPPER.readValue(json, clazz);
} catch (IOException e) {
log.error("Jackson2Json failed: " + e.getMessage());
} return null;}
public static String convert(Object data) {
try {
return OBJECT_MAPPER.writeValueAsString(data);
} catch (JsonProcessingException e) {
log.error("Conversion failed: " + e.getMessage());
}
return null;
}
How is OAuth2Authentication object reconstructed when the token is looked up from Redis? Since it does not define a default constructor, any Jackson based serializer and object mapper won't be able to deserialize it.
Again, the serialization works great (since OAuth2Authentication implements Serializable interface) and the token gets stored fine in Redis. It just fails when the /oauth/check_token is called.
What am I missing and how is this problem dealt with while storing access token in Redis?
I solved the issue by writing custom deserializer. It looks like this:
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.io.IOException;
public class AuthorizationGrantTypeCustomDeserializer extends JsonDeserializer<AuthorizationGrantType> {
#Override
public AuthorizationGrantType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
Root root = p.readValueAs(Root.class);
return root != null ? new AuthorizationGrantType(root.value) : new AuthorizationGrantType("");
}
private static class Root {
public String value;
}
public static SimpleModule generateModule() {
SimpleModule authGrantModule = new SimpleModule();
authGrantModule.addDeserializer(AuthorizationGrantType.class, new AuthorizationGrantTypeCustomDeserializer());
return authGrantModule;
}
}
Then I registered deserializer in objectMapper which is later used by jackson API
ObjectMapper mapper = new ObjectMapper()
.registerModule(AuthorizationGrantTypeCustomDeserializer.generateModule());
I have one List box and I would like to set code type of it.
I create new AbstractCodeType :
public class MyCodeType extends AbstractCodeType<String, String> {
private static final long serialVersionUID = 6808664924551155395L;
public static final String ID = null;
#Override
public String getId() {
return ID;
}
#Order(10.0)
public static class UnknownCode extends AbstractCode<String> {
private static final long serialVersionUID = -1307260056726644943L;
public static final String ID = "Unknown";
#Override
protected String getConfiguredText() {
return TEXTS.get("Unknown");
}
#Override
public String getId() {
return ID;
}
}
}
and I set this code type in list box :
#Override
protected Class<? extends ICodeType<?, String>> getConfiguredCodeType() {
return MyCodeType.class;
}
But doesn't work. It return empty box.
While I was debugging I noticed that in AbstractListBox.class in initConfig method it call this code type and set code type in m_lookupCall inside setCodeTypeClass. Then inside execLoadTableData, it get call but this call return empty array when called call.getDataByAll().
I suspect that converting between code type and Lookup call does not work properly.
EDIT
I try to debug where is the problem and if follow the path :
initConfig() -> CodeLookupCall.newInstanceByService(m_codeTypeClass); (line 581)
and if you look inside CodeLookupCall ;
getDataByAll() in line 221 `resolveCodes(v)` -> BEANS.opt(m_codeTypeClass) -> bean.getInstance() -> m_producer.produce(this) -> return (T) getCache().get(createCacheKey(type));
This is in class CodeService.class in line 97 :
Class<T> type is right class and createCacheKey(type) return not null object but then getCache().get(...) return null. From this point on everything is null (what is reasonable regarding that getCodeType return null.)
This is what I found out while debugging, if it helps someone to figure out what is wrong.
It looks like your codetype class is not found by the bean manager. CodeService only finds CodeTypes in its classpath (accessible in the server).
-> You might need to move your class to the shared project.
You can find examples for code types in the contacts demo application:
https://github.com/BSI-Business-Systems-Integration-AG/org.eclipse.scout.docs/tree/releases/5.2.x/code/contacts
I tested your code snippet with Eclipse Scout Neon M4 and I could reproduce your described error.
However, it seems that this bug has been fixed with Scout Neon M5. So I suggest that you upgrade to the latest milestone version, which is recommended anyway.
In my vaadin application, i need to use #Push, but since i added it, i can't read and write cookies because VaadinService.getSurrentResponse()returns null because of Push. I manager cookies using this class :
import javax.servlet.http.Cookie;
import com.vaadin.server.VaadinResponse;
import com.vaadin.server.VaadinService;
public class CookieManager {
private VaadinResponse response;
public CookieManager(VaadinResponse response){
this.response = response;
}
public Cookie getCookieByName(final String name) {
// Fetch all cookies from the request
Cookie[] cookies = VaadinService.getCurrentRequest().getCookies();
// Iterate to find cookie by its name
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
public Cookie createCookie(final String name, final String value, final int maxAge) {
// Create a new cookie
final Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge);
// Set the cookie path.
cookie.setPath(VaadinService.getCurrentRequest().getContextPath());
// Save cookie
addCookie(cookie);
return cookie;
}
private void addCookie(Cookie cookie){
response.addCookie(cookie);
}
public Cookie updateCookieValue(final String name, final String value) {
// Create a new cookie
Cookie cookie = getCookieByName(name);
cookie.setValue(value);
// Save cookie
addCookie(cookie);
return cookie;
}
public void destroyCookieByName(final String name) {
Cookie cookie = getCookieByName(name);
if (cookie != null) {
cookie.setValue(null);
// By setting the cookie maxAge to 0 it will deleted immediately
cookie.setMaxAge(0);
cookie.setPath(VaadinService.getCurrentRequest().getContextPath());
addCookie(cookie);
}
}
}
When i want to create a cookie (like at user's login), i get a nullPointerException because of the VaadinResponse being null.
So i tried to disable Push in constructor and re-enable it at the end of addCookie()method, but it disabled push for all of my application, even if i re-enable it just after the addCookiemethod.
I saw a ticket on vaadin's trac (http://dev.vaadin.com/ticket/11808) saying that will not be fixed, and someone suggested to create a regular AJAX query from server to create cookie, but i really don't know how to do.
How can i manage my cookies? i need to create AND get cookies, so javascript can't help me there, because i can't get javascript's return in vaadin, so i can't get a cookie.
Here is my solution how to store cookie when #Push is using.
First we create container to storage all instance of client UI. (
This container itself has a great potential)
public class UISession {
private List<WebAppUI> uis = new ArrayList<WebAppUI>();
public void addUI(WebAppUI webAppUI) {
uis.add(webAppUI);
}
public List<WebAppUI> getUIs() {
return uis;
}
public static UISession getInstance() {
try {
UI.getCurrent().getSession().lock();
return (UISession) UI.getCurrent().getSession().getAttribute("userUiSession");
} finally {
UI.getCurrent().getSession().unlock();
}
}
In UI.init() we add new instance to the session (e.g when user open new tab)
#Override
protected void init(VaadinRequest vaadinRequest) {
/** Set singleton uisesison for each browser*/
if(UISession.getInstance()==null){
UI.getCurrent().getSession().setAttribute("userUiSession",new UISession());
}
UISession.getInstance().addUI(this);
System.out.println("UI count fo current browser "+UISession.getInstance().getUIs().size());
...
}
Here is my helper cookie class:
class MyCookie{
private String value;
private String name;
private Date expired;
private String path="/";
public MyCookie(String name, String value) {
this.name=name;
this.value=value;
}
public void setMaxAge(int minute) {
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, minute);
expired=c.getTime();
}
public String getStringToCreateCookie(){
return "document.cookie=\""+getName()+"="+getValue()+"; expires="+expired.toString()+"; path="+path+"\"";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Date getExpired() {
return expired;
}
public void setExpired(Date expired) {
this.expired = expired;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
And on final when we need add new cookie, we just must find Ui that is active and call js function
public static void addCookie(String name, String value, int age){
MyCookie myCookie = new MyCookie(name, value);
myCookie.setMaxAge(age);
for(WebAppUI ui : UISession.getInstance().getUIs()){
if(ui.isAttached()){
ui.getPage().getJavaScript().execute(myCookie.getStringToCreateCookie());
return;
}
}
}
In my case i have access to storage cookie (when user made request). I just only have problem with add new cookie so this is my working solutions.
As mentioned in the ticket, you can use JavaScript to call client code and also request a cookie value back by that. E.g.
#Grapes([
#Grab('org.vaadin.spring:spring-boot-vaadin:0.0.3'),
#Grab('com.vaadin:vaadin-server:7.4.0.beta1'),
#Grab('com.vaadin:vaadin-client-compiled:7.4.0.beta1'),
#Grab('com.vaadin:vaadin-themes:7.4.0.beta1'),
])
import com.vaadin.ui.*
#org.vaadin.spring.VaadinUI
#groovy.transform.CompileStatic
class MyUI extends UI {
protected void init(com.vaadin.server.VaadinRequest request) {
final resultLabel = new Label()
// provide a callback for the client to tell the cookies
JavaScript.current.addFunction("tellCookie", { elemental.json.JsonArray arguments ->
resultLabel.value = arguments?.get(0)?.asString()
} as JavaScriptFunction)
setContent(new VerticalLayout().with{
addComponent(new Button("Set Cookie", {
// just simply set the cookies via JS (attn: quoting etc)
JavaScript.current.execute("document.cookie='mycookie=${System.currentTimeMillis()}'")
} as Button.ClickListener))
addComponent(new Button("Get Cookie", {
// tell the client to tell the server the cookies
JavaScript.current.execute("this.tellCookie(document.cookie)")
} as Button.ClickListener))
addComponent(resultLabel)
return it
})
}
}
This is a running example (e.g. spring run vaadin.groovy) for testing. See the comments for the important parts.
The Viritin add-on contains a helper class called BrowserCookie. It works in pretty much the way suggested by cfrick, but just hides all the cookie handling complexity into a helper class. It don't contain built in "max age" handling yet, but that could be easily added as a workaround you can manually "encode" the age into cookie value.
BTW. Don't know what you are doing, but if you happen to be using TouchKit add-on, it has a helper for html5 local storage. It has rather wide browsers support already and is in many ways better way to store e.g. settings than cookies.
I'm working on crawler4j using groovy and grails.
I have a BasicCrawler.groovy class in src/groovy and the domain class Crawler.groovy and a controller called CrawlerController.groovy.
I have few properties in BasicCrawler.groovy class like url, parentUrl, domain etc.
I want to persist these values to the database by passing these values to the domain class while crawling is happening.
I tried doing this in my BasicCrawler class under src/groovy
class BasicCrawler extends WebCrawler {
Crawler obj = new Crawler()
//crawling code
#Override
void visit(Page page) {
//crawling code
obj.url = page.getWebURL().getURL()
obj.parentUrl = page.getWebURL().getParentUrl()
}
#Override
protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) {
//crawling code
obj.httpstatus = "not found"
}
}
And my domain class is as follows:
class Crawler extends BasicCrawler {
String url
String parentUrl
String httpstatus
static constraints = {}
}
But I got the following error:
ERROR crawler.WebCrawler - Exception while running the visit method. Message: 'No such property: url for class: mypackage.BasicCrawler
Possible solutions: obj' at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
After this I tried another approach. In my src/groovy/BasicCrawler.groovy class, I declared the url and parentUrl properties on the top and then used databinding (I might be wrong since I am just a beginner):
class BasicCrawler extends WebCrawler {
String url
String parentUrl
#Override
boolean shouldVisit(WebURL url) { //code
}
#Override
void visit(Page page) { //code
}
#Override
protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) {
//code}
}
def bindingMap = [url: url , parentUrl: parentUrl]
def Crawler = new Crawler(bindingMap)
}
And my Crawler.groovy domain class is as follows:
class Crawler {
String url
String parentUrl
static constraints = {}
}
Now, it doesn't show any error but the values are not being persisted in the database. I am using mongodb for the backend.
I think this example is a bit contrived but here is a way you might solve this problem in current situation:
class BasicCrawler extends WebCrawler {
#Override
void visit(Page page) {
Crawler obj = new Crawler()
obj.url = page.getWebURL().getURL()
obj.parentUrl = page.getWebURL().getParentUrl()
obj.save()
}
#Override
protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) {
Crawler obj = Crawler.findByUrl(webUrl)
obj.httpstatus = "not found"
obj.save()
}
}
Key here is not using a member instance variable and using the URL to 'refetch' and update original site 'visited' since I'm assuming that will be a unique constraint on each row.
I want to start another apps when I click this button.
sharebtn = new Custom_ButtonField(share, shareactive, shareactive) {
protected boolean navigationClick(int status, int time) {
//I want to start another apps (Strawberry)
return true;
}
};
add(sharebtn);
Here is the Strawberry Apps
public class StrawBerry extends UiApplication implements ActionListener {
public static void main(String url) {
new StrawBerry(url).enterEventDispatcher();
}
}
I want to pass String url to Strawberry apps. How can I achieve this?
First your main method won't be never called by system. The right signature:
public static void main(String[] arguments){}
Take a look on this article to launch another app with parameters : How To - Launch a third-party application from another third-party application
To post on FB page. You need something like:
private final String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
private final String APPLICATION_ID = "your id";
private final String APPLICATION_SECRET = "your secret";
private Facebook fb;
private User user;
...
fb = Facebook.getInstance(new ApplicationSettings(NEXT_URL, APPLICATION_ID, APPLICATION_SECRET, Facebook.Permissions.PUBLISH_STREAM));
user = fb.getUser(pUserId);
user.publishPost(messageEditField.getText(), linkEditField.getText(), pictureEditField.getText(), nameEditField.getText(), captionEditField.getText(), descriptionEditField.getText(), sourceEditField.getText());