Hi i want to make very simple application that print an openweathermap.org API answer in console. I thought it should works, but when i'm going to an adress in my browser i've got Whitelabel Error Page and nothing in console. I've made two classes. Main:
package com.example.restTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
#SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class, args);
}
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
and controller:
package com.example.restTemplate.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
#RestController
public class ConsumeWebService {
#Autowired
RestTemplate restTemplate;
#RequestMapping(value = "localhost:8080/weather")
public void printWeather() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
System.out.println(restTemplate.exchange("http://api.openweathermap.org/data/2.5/weather?q=London,uk&myAPIKey",
HttpMethod.GET, entity, String.class).getBody());
}
}
Of course i didn't put here my real key to API and i should to declared city and key in params, but i will think about it in future. For now i just want to get a simple output in console and wll be appreciated for your help.
Why do you put "localhost:8080/weather" as value?
Change from
#RequestMapping(value ="localhost:8080/weather")
To
#RequestMapping(value = "/weather")
Related
Here is my NativScript code for android
package com.chetti; // replace com.your-app-name with your app’s name
import com.facebook.react.bridge.NativeModule;
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 androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.app.Activity;
public class CalendarModule extends ReactContextBaseJavaModule {
CalendarModule(ReactApplicationContext context) {
super(context);
}
#Override
public String getName() {
return "CalendarModule";
}
#ReactMethod
public String createCalendarEvent() {
// I am not sure about how to get TelephonyManager instance!
TelephonyManager manager=(TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber1 = manager.getLine1Number();
return phoneNumber1;
}
}
Error throwing are follows->
error: cannot find symbol
TelephonyManager manager=(TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
^
symbol: method getActivity()
location: class CalendarModule
My requirement is to get the mobile numbers using Native Module for android?.
My specs:
1, React Native 0.68.0
2, node 17
Just putting here a function so that you can get an idea:
#Override
public void onReceive(final Context context, final Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String phoneNumber) {
Log.d("RINGER_IID", phoneNumber);
onCustomCallStateChanged(context, state, phoneNumber);
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
https://developer.android.com/reference/android/telephony/TelephonyManager
Got through this. Hope this helps.
As i know we can define pointcut even for an advice. example
package com.master_scrum.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class ConstructorAspect {
#Before("execution(com.master_scrum.Account.new(..)")
public void beforeExecuteConstructor(JoinPoint jp){
System.out.println("Do somthing good");
}
}
now how i can create another advice for this advice? What is synctax?
i've tried with this one but does not work:
package com.master_scrum.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class AspectOfConstructorAspect {
#Before("execution("* ConstructorAspect.*(..))") //aspects are in same package
public void beforeAspect(JoinPoint jp){
System.out.println("Before constructor advice");
}
}
Thanks
i found solution from AspectJ manual
just define pointcut like this
package com.master_scrum.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class AspectOfConstructorAspect {
#Before("adviceexecution() && within(com.master_scrum.aop.ConstructorAspect)")
public void beforeAspect(JoinPoint jp){
System.out.println("Before constructor advice");
}
}
Just for those who need a piece of code very usefull for handling bean validation exception in JAX-RS REST Web Services.
Saveriu
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
#Provider
public class ValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
private <T> List<T> mergeList(#NotNull List<T> l1 , #NotNull List<T> l2 ) {
return new ArrayList<T>(l1) {{addAll(l2);}};
}
#Override
public Response toResponse(final ConstraintViolationException exception) {
Map<Path,List<String>> errors =
exception.getConstraintViolations()
.stream()
.collect(
Collectors.toMap(
ConstraintViolation::getPropertyPath,
cv -> asList(cv.getMessage()),
this::mergeList
)
);
return Response.status(Response.Status.BAD_REQUEST)
.entity(errors)
.build();
}
}
I am facing issue in calling my java class methods (android native code) from JS.
I have already followed https://facebook.github.io/react-native/docs/native-modules-android.html but its not working. Please find below the issues which I am facing.
Where we should export android module, I have done it in index.js
import {NativeModules} from 'react-native';
const { ScannerInteractor } = NativeModules;
export default ScannerInteractor;
or
import {NativeModules} from 'react-native';
module.exports = NativeModules.ScannerInteractor;
In a javascript class where I want to call this method how should I import my class, I have written following code. Does it matter if index.js are at same level as of my javascript class?
import ScannerInteractor from "./ScannerInteractor"
I have created member methods then how to call them? As per example, it need to be call as static method call.
ScannerInteractor.startScan(this, null, null);
How to pass context variable from JS, will passing 'this' parameter will work?
I am not getting any error or log messages in the logcat but method is also not getting triggered.
NativeModule class
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.kohl.scan.common.ScannerInteractor;
public class ModuleInjector implements ReactPackage {
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
#Override public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ScannerInteractor(reactContext));
return modules;
}
}
ApplicationClass
import com.facebook.react.ReactPackage;
import java.util.Arrays;
import java.util.List;
import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;
import com.reactnativenavigation.NavigationApplication;
import com.oblador.vectoricons.VectorIconsPackage;
import com.rfpproject.ModuleInjector;
public class MainApplication extends NavigationApplication {
#Override
public boolean isDebug() {
// Make sure you are using BuildConfig from your own application
return BuildConfig.DEBUG;
}
protected List<ReactPackage> getPackages() {
// Add additional packages you require here
// No need to add RnnPackage and MainReactPackage
return Arrays.<ReactPackage>asList(
// eg. new VectorIconsPackage()
new ReactNativeConfigPackage(),
new VectorIconsPackage(),
new ModuleInjector()
);
}
#Override
public String getJSMainModuleName() {
return "index";
}
#Override
public List<ReactPackage> createAdditionalReactPackages() {
return getPackages();
}
}
I am calling it from JS script as mentioned below:
onClick1(){
ScannerInteractor.startScan(this, null, null);
//alert('cllllll');
}
It has worked after using
import {NativeModules} from 'react-native';
module.exports = NativeModules.ScannerInteractor;
and
import {NativeModules} from 'react-native'; in the JS class and calling using NativeModules.ScannerInteractor.check()
Still not clear about how to pass context variable as an argument.
When i make a request to my JAX-RS path with an empty body I am getting error 500 as a response. If I send a body with {} is ok since it interprets that is a JSON.
I would like to be able to return the error code 400 BAD_REQUEST since in my opinion this is a client error.
#PUT
#Produces(APPLICATION_JSON)
#Consumes(APPLICATION_JSON)
#Path("/up")
public Response signUp(Credentials credentials) {
I am using jersey, and for the JSON mapper this library:
org.glassfish.jersey.media:jersey-media-json-jackson:2.22.2'
Create a custom provider to deserialise your JSON payload and hook up your logic. I assume you are using JAXB annotation in your classes.
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONUnmarshaller;
#Provider
#Consumes({MediaType.APPLICATION_JSON})
public class MyJsonReaderProvider<T> implements MessageBodyReader<T> {
#Override
public boolean isReadable(Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType) {
return type.isAnnotationPresent(XmlRootElement.class);
}
#Override
public T readFrom(Class<T> type,
Type genericType,
Annotation[] annotations,
MediaType mediatype,
MultivaluedMap<String, String> headers,
InputStream inputStream) throws IOException,
WebApplicationException {
try {
JAXBContext jc = JSONJAXBContext.newInstance(type);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JSONUnmarshaller jsonUnmarshaller = JSONJAXBContext.getJSONUnmarshaller(unmarshaller);
T object = (T) jsonUnmarshaller.unmarshalFromJSON(inputStream, type);
return object;
} catch (JAXBException e) {
throw new BadRequestException("Bad Request");
}
}
}
Register the provider in your javax.ws.rs.core.Application