impossible to import android.content.res.Resources - java

I can't find how to import android.content.res.Resources;
Here is my code:
package com.mycompany.fortune;
import com.google.gson.JsonObject;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import android.content.res.Resources; //This don't work
import retrofit.http.GET;
import java.util.List;
import java.util.Random;
public class FortuneClient {
private static final String API_URL = "http://www.myurl.fr";
private interface FortuneService {
#GET("/test.php")
void getFortune(Callback<JsonObject> callback);
}
public static class OnFortuneListener {
public void onFortune(String fortune) {
}
}
private static Random rng = new Random();
private FortuneService service;
public FortuneClient() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
service = adapter.create(FortuneService.class);
}
public void getFortune(final OnFortuneListener listener) {
service.getFortune(new Callback<JsonObject>() {
#Override
public void success(JsonObject json, Response response) {
String test = json.getAsJsonObject("0").getAsJsonObject("title").toString();
String test2 = json.getAsJsonObject("0").getString('title');
listener.onFortune(test2);
}
#Override
public void failure(RetrofitError error) {
listener.onFortune(error.toString());
}
});
}
}
the error is: "Error:(8, 26) Gradle: error: package android.content.res does not exist"
What I tried:
-Make, remake, build, clean, rebuild,
-Invalidate cache and restart,
-Verify the java/sdk/jdk positions,
-Stupid things on the gradle/xml files.

This import android.content.res.Resources; //This don't work is used in your application code to access the resources. To Access any particular resource you should pass the context to this class atleast .

Related

Error: While resolving module, the Haste package was found. the module could not be found within the package

I am trying the new arch of react native. I have enabled it in my gradle.properties file. This error is for android only and I have not tried iOS yet.
I am following the exact sample of Calculator mentioned over here.
I get an error saying
error: Error: While resolving module `rtn-calculator/js/NativeCalculator.js`, the Haste package `rtn-calculator` was found. However the module `js/NativeCalculator.js` could not be found within the package. Indeed, none of these files exist:
* `/Users/transformhub/Desktop/rnapp/RTNCalculator/js/NativeCalculator.js(.native|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`
* `/Users/transformhub/Desktop/rnapp/RTNCalculator/js/NativeCalculator.js/index(.native|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`
at resolveHasteName (/Users/transformhub/Desktop/rnapp/node_modules/metro-resolver/src/resolve.js:173:9)
at Object.resolve (/Users/transformhub/Desktop/rnapp/node_modules/metro-resolver/src/resolve.js:63:20)
at ModuleResolver.resolveDependency (/Users/transformhub/Desktop/rnapp/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:111:31)
at DependencyGraph.resolveDependency (/Users/transformhub/Desktop/rnapp/node_modules/metro/src/node-haste/DependencyGraph.js:260:43)
at Object.resolve (/Users/transformhub/Desktop/rnapp/node_modules/metro/src/lib/transformHelpers.js:177:21)
at Graph._resolveDependencies (/Users/transformhub/Desktop/rnapp/node_modules/metro/src/DeltaBundler/Graph.js:432:35)
at Graph._processModule (/Users/transformhub/Desktop/rnapp/node_modules/metro/src/DeltaBundler/Graph.js:218:38)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Graph._addDependency (/Users/transformhub/Desktop/rnapp/node_modules/metro/src/DeltaBundler/Graph.js:314:20)
at async Promise.all (index 2)
The complete repo is here
Below is sample code
NativeCalculator.ts
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import {TurboModuleRegistry} from 'react-native';
export interface Spec extends TurboModule {
add(a: number, b: number): Promise<number>;
}
export default TurboModuleRegistry.get<Spec>('RTNCalculator') as Spec | null;
package com.rtncalculator;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.TurboReactPackage;
import java.util.Collections;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
public class CalculatorPackage extends TurboReactPackage {
#Nullable
#Override
public NativeModule getModule(String name, ReactApplicationContext reactContext) {
if (name.equals(CalculatorModule.NAME)) {
return new CalculatorModule(reactContext);
} else {
return null;
}
}
#Override
public ReactModuleInfoProvider getReactModuleInfoProvider() {
return () -> {
final Map<String, ReactModuleInfo> moduleInfos = new HashMap<>();
moduleInfos.put(
CalculatorModule.NAME,
new ReactModuleInfo(
CalculatorModule.NAME,
CalculatorModule.NAME,
false, // canOverrideExistingModule
false, // needsEagerInit
true, // hasConstants
false, // isCxxModule
true // isTurboModule
));
return moduleInfos;
};
}
}
package com.rtncalculator;
import androidx.annotation.NonNull;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
import com.rtncalculator.NativeCalculatorSpec;
public class CalculatorModule extends NativeCalculatorSpec {
public static String NAME = "RTNCalculator";
CalculatorModule(ReactApplicationContext context) {
super(context);
}
#Override
#NonNull
public String getName() {
return NAME;
}
#Override
public void add(double a, double b, Promise promise) {
promise.resolve(a + b);
}
}
This is a react native issue introduced in 0.70 and was resolved in 0.71. Check here for more details

Integration testing for events in the Jersey container listener

I have an application based on Jersey JAX-RS. I need to refactor the event handler and therefore also write a test for it.
I'm trying to do this with the JerseyTest Framework. I created a configuration to extend ResourceConfig, but when I use the target () call the handler is not called.
I will present the situation using code.
Here is an example Resource class:
package com.my.page;
import org.glassfish.hk2.api.messaging.Topic;
import com.my.core.entity.Link;
import com.my.core.location.LinkHitLocationFactory;
import com.my.core.service.LinkService;
import com.my.core.service.link.LinkFinder;
import com.my.core.service.link.LinkFinderFactory;
import com.my.event.LinkHitEvent;
import com.my.exception.FragmentNotFoundException;
import javax.annotation.security.PermitAll;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
#PermitAll
#Path("/")
public class LinkResource {
#Inject
private LinkService linkService;
#Inject
private Topic<LinkHitEvent> linkHitPublisher;
#Inject
private LinkFinderFactory linkFinderFactory;
#Inject
private LinkHitLocationFactory linkHitLocationFactory;
#GET
#Path("/{fragment:[^ ]{1,32}}")
public Response redirect(
#PathParam("fragment") String fragment,
#HeaderParam("Range") String range,
#HeaderParam("User-Agent") String userAgent,
#Context HttpHeaders headers) throws Exception {
LinkFinder linkFinder = linkFinderFactory.getLinkFinder(fragment);
Link link = linkFinder.getLink(fragment);
if (link.isExpired()) {
throw new FragmentNotFoundException(fragment);
}
linkService.insertHit();
linkHitPublisher.publish(new LinkHitEvent(link));
return handlerFactory.getHandler(link).handleGet(link, range).build();
}
}
Event test:
package com.my.page;
import org.glassfish.hk2.extras.events.internal.TopicDistributionModule;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import pl.comvision.hk2.events.ThreadedEventDistributorService;
import com.my.client.CallbackTargetBuilder;
import com.my.core.entity.Link;
import com.my.core.mapper.LinkMapper;
import com.my.core.service.LinkService;
import com.my.page.resource.LinkResource;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import static javax.ws.rs.core.Response.Status.TEMPORARY_REDIRECT;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
#RunWith(MockitoJUnitRunner.class)
public class CallbackEventTest extends JerseyTest {
#Mock
private LinkMapper linkMapper;
#Mock
private LinkService linkService;
private CallbackTargetBuilder callbackTargetBuilder;
private final String callbackUrl = "";
#Override
protected Application configure() {
this.callbackTargetBuilder = spy(new CallbackTargetBuilder(this.callbackUrl));
ResourceConfig config = new ResourceConfig(LinkResource.class);
config.register(new TopicDistributionModule());
config.register(new AbstractBinder() {
#Override
protected void configure() {
addActiveDescriptor(ThreadedEventDistributorService.class).setRanking(100);
}
});
config.register(new EventsContainerListener(CallbackEventHandler.class));
config.register(new AbstractBinder() {
#Override
protected void configure() {
bind(linkMapper).to(LinkMapper.class);
bind(linkService).to(LinkService.class);
bind(mock(LinkService.class)).to(LinkService.class);
bind("").to(String.class).named("varPath");
bind("127.0.0.1").to(String.class).named("requestIP");
bind(callbackTargetBuilder).to(CallbackTargetBuilder.class);
}
});
return config;
}
#Test
public void publish_event() {
Link link = mock(Link.class);
when(link.getUrl()).thenReturn("example");
when(link.getName()).thenReturn("test");
when(linkMapper.getByName(anyString())).thenReturn(link);
Response response = target("/testY").property("jersey.config.client.followRedirects", false).request().get();
assertEquals(TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
verify(callbackTargetBuilder).build();
}
}
For testing purposes, I only injected callbackTargetBuilder into the handler, and called the build method on it to verify the call:
package com.my.page;
import org.glassfish.hk2.api.messaging.MessageReceiver;
import org.glassfish.hk2.api.messaging.SubscribeTo;
import org.jvnet.hk2.annotations.Service;
import com.my.client.CallbackTargetBuilder;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
#Service
#Singleton
#MessageReceiver
public class CallbackEventHandler {
#Named("callbackUrl")
private String url;
#Inject
private CallbackTargetBuilder callbackTargetBuilder;
#MessageReceiver
public void handle(#SubscribeTo LinkHitEvent event) {
Form form = new Form();
form.param("id", event.getLink().getId().toString());
form.param("name", event.getLink().getName());
callbackTargetBuilder.build();
Client client = ClientBuilder.newClient();
client.target(url).request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
}
}
Edit:
I tried to register dependencies differently, but it does not bring satisfactory results. Each time verification fails:
verify (callbackTargetBuilder) .build ();
Looking for information I found that I can configure the DeploymentContext, but I don't know if this is the right direction.
Edit the second:
A quick test shows that I may have some more basic problem with mocking. Because the call:
verify (linkService) .insertHit (anyObject ());
It also fails.
I will write only for posterity that the above code is correct. The problem was a lot of small bugs in the tested code and how to mock it.

How does a Micronaut controller determine its base URL

For example if I have the following controller:
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.*;
#Controller("/test")
public class TestController {
#Get()
#Produces(MediaType.TEXT_PLAIN)
public String index() {
// How should this be implemented?
return "???";
}
}
and I run it on my-server, then I would like the index method to return http://my-server:8080.
Asof Micronaut V1.2.0, you can use the HttpHostResolver interface, for example:
import io.micronaut.http.*;
import io.micronaut.http.annotation.*;
import io.micronaut.http.server.util.HttpHostResolver;
import io.micronaut.web.router.RouteBuilder;
#Controller("/test")
public class TestController {
private final HttpHostResolver httpHostResolver;
private final RouteBuilder.UriNamingStrategy uriNamingStrategy;
public TestController(
HttpHostResolver httpHostResolver,
RouteBuilder.UriNamingStrategy uriNamingStrategy
) {
this.httpHostResolver = httpHostResolver;
this.uriNamingStrategy = uriNamingStrategy;
}
#Get()
#Produces(MediaType.TEXT_PLAIN)
public String index(HttpRequest httpRequest) {
return httpHostResolver.resolve(httpRequest) +
uriNamingStrategy.resolveUri(TestController.class);
}
}
This seems to work:
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.*;
import io.micronaut.runtime.server.EmbeddedServer;
import io.micronaut.web.router.RouteBuilder;
import java.net.*;
#Controller("/test")
public class TestController {
protected final String baseUrl;
public TestController(EmbeddedServer embeddedServer, RouteBuilder.UriNamingStrategy uns)
throws MalformedURLException {
final String host = embeddedServer.getHost();
final int port = embeddedServer.getPort();
final String file = uns.resolveUri(TestController.class);
baseUrl = new URL("http", host, port, file).toString();
}
#Get()
#Produces(MediaType.TEXT_PLAIN)
public String index() {
return baseUrl;
}
}
I'm not sure whether it's idiomatic, or whether it works in all cases. If someone posts a better answer I'll accept that.
If you want the controller to respond at / then use #Controller("/") instead of #Controller("/test").
package com.tech.api;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.PathVariable;
import java.util.List;
import javax.inject.Inject;
#Controller("/")
public class ModelDefinitionsApi {
#Get(uri="/modelName", produces = MediaType.APPLICATION_JSON)
public String getModel(#PathVariable String modelName) {
return "modelName";
}
}
http://my-server:8080 => main controller url
http://my-server:8080/modelName => for getModel method

Spring Data Cassandra cant find entity class

I'm trying to persist a cassandra entity but on startup I get:
Caused by: org.springframework.data.mapping.MappingException: Couldn't find PersistentEntity for type class com.service.model.Cart!
This is my entity class:
package com.service.model;
import io.vavr.collection.LinkedHashMap;
import io.vavr.collection.Map;
import lombok.Getter;
import lombok.ToString;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
#ToString
#Table("carts")
public class Cart {
#Getter
#PrimaryKey
private final UUID uuid;
private final Map<CartItemKey, CartItem> items;
public Cart(UUID uuid) {
this(uuid, LinkedHashMap.empty());
}
private Cart(UUID uuid, Map<CartItemKey, CartItem> items) {
this.uuid = Objects.requireNonNull(uuid, "Cart's uuid cannot be null");
this.items = Objects.requireNonNull(items, "Cart's items cannot be null");
}
}
This is my CassandraConfig:
package com.service.configuration;
import com.service.model.Cart;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.cassandra.config.AbstractClusterConfiguration;
import org.springframework.data.cassandra.core.convert.CassandraCustomConversions;
import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.KeyspaceOption;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static java.util.Collections.singletonList;
#Configuration
public class CassandraConfig extends AbstractClusterConfiguration {
#Value("${spring.data.cassandra.keyspace-name}")
private String keyspaceName;
#Value("${spring.data.cassandra.contact-points}")
private String contactPoints;
#Override
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
return singletonList(
CreateKeyspaceSpecification.createKeyspace(keyspaceName)
.ifNotExists()
.with(KeyspaceOption.DURABLE_WRITES, true)
.withSimpleReplication());
}
#Override
protected boolean getMetricsEnabled() {
return false;
}
#Override
protected String getContactPoints() {
return contactPoints;
}
#Bean
public CassandraCustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(new CartWriteConverter());
converters.add(new CartReadConverter());
return new CassandraCustomConversions(converters);
}
static class CartWriteConverter implements Converter<Cart, String> {
public String convert(Cart source) {
try {
return new ObjectMapper().writeValueAsString(source);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
static class CartReadConverter implements Converter<String, Cart> {
public Cart convert(String source) {
if (StringUtils.hasText(source)) {
try {
return new ObjectMapper().readValue(source, Cart.class);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
return null;
}
}
}
And lastly my Application:
package com.service.cart;
import org.axonframework.springboot.autoconfig.AxonServerAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import org.springframework.scheduling.annotation.EnableAsync;
#EnableCaching
#EnableAsync
#EnableFeignClients
#SpringBootApplication
#EnableAutoConfiguration(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
AxonServerAutoConfiguration.class})
#EnableCassandraRepositories(basePackages = "com.service.repository")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
What seems puzzling to me is that when I remove customConversions() bean it fails with a different error - not being able to map vavr Map, so spring must have scanned and registered this entity so that it got inspected. This is expected while it is not cassandra data type but in my understanding adding my custom conversions should solve this problem.
I also tried experimenting with #EntityScan with the same results.
Any help would be appreciated.

java annotation processing: problems generating a new class

I'm playing with java annotation processing to learn how to generate java code on compile time. I've created an abstract processor that (using javapoet) creates a new class. However I can't manage to make it work.
I've compressed the example in a single java class.
What I'm doing wrong?
When I compile the project I get:
Error:java: Bad service configuration file, or exception thrown while constructing Processor object: javax.annotation.processing.Processor: Provider com.mateuyabar.AnnotProc not found
Here is the java code:
package com.mateuyabar;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
#AutoService(Processor.class)
public class AnnotProc extends AbstractProcessor{
public #interface MyAnnotation {}
#MyAnnotation
public static void dummyForAnnotation(){}
#Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment env) {
for(Element el:env.getElementsAnnotatedWith(MyAnnotation.class)){
System.out.println(el.asType());
}
MethodSpec sampleMethod = MethodSpec.methodBuilder("sampleMethod").addModifiers(Modifier.PUBLIC).returns(String.class).addParameter(String.class, "param1")
.addStatement("return $S+$N", "Welcome, ", "name").build();
TypeSpec customerService = TypeSpec.classBuilder("MyGeneratedClass").addModifiers(Modifier.PUBLIC).addMethod(sampleMethod).build();
JavaFile javaFile = JavaFile.builder("com.mateuyabar", customerService).build();
try {
javaFile.writeTo(System.out);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
#Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton(MyAnnotation.class.getName());
}
#Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
public static void main(String[] args){
System.out.println(new com.mateuyabar.MyGeneratedClass().sampleMethod("a"));
}
}

Categories

Resources