Cloud Function with Java and Springboot - java

I'm pretty new to this stuff, but I need it for university. So maybe someone can help me please?
I've made a little Java Application with Springboot to handle a simple ToDo-List:
package coco.ToDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class ToDoListController {
private final ToDoListService toDoListService;
#Autowired
public ToDoListController(ToDoListService toDoListService) {
this.toDoListService = toDoListService;
}
#RequestMapping(value = "/ToDoList")
public List<ToDo> getToDoList() {
return toDoListService.getToDoList();
}
#RequestMapping("/ToDoList/add")
public void addToDo(#RequestParam("ToDo") String toDo){
toDoListService.addToDo(toDo);
}
}
I would like to run it on gcloud with Cloud Functions.
But i haven't figured it out yet.

Cloud Functions is designed to handle only a function, only ONE entry point. If you have several entry point (request mapping) you must host a webserver on App Engine or on Cloud Run.

Related

Spring Integration Pub sub sample project "Could not autowire. No beans of 'PubSubTemplate' type found."

I'm checking out some of Spring Integration with GCP pub sub and I've cloned their sample project. I'm getting a warning / error in my IDE which I'm struggling to understand.
Basically in this class https://github.com/spring-cloud/spring-cloud-gcp/blob/6c95a16f7e6ad95404b4f992b5f46340e831e5cb/spring-cloud-gcp-samples/spring-cloud-gcp-integration-pubsub-json-sample/src/main/java/com/example/WebController.java#L47
package com.example;
import java.util.ArrayList;
import java.util.List;
import com.example.SenderConfiguration.PubSubPersonGateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;
/**
* Provides REST endpoint allowing you to send JSON payloads to a sample Pub/Sub topic for
* demo.
*
* #author Daniel Zou
*/
#RestController
public class WebController {
private final PubSubPersonGateway pubSubPersonGateway;
#Autowired
#Qualifier("ProcessedPersonsList")
private ArrayList<Person> processedPersonsList;
public WebController(PubSubPersonGateway pubSubPersonGateway, SenderConfiguration.PubSubProjectGateway pubSubProjectGateway ) {
this.pubSubPersonGateway = pubSubPersonGateway;
}
#PostMapping("/createPerson")
public RedirectView createUser(#RequestParam("name") String name, #RequestParam("age") int age) {
Person person = new Person(name, age);
this.pubSubPersonGateway.sendPersonToPubSub(person);
return new RedirectView("/");
}
#GetMapping("/listPersons")
public List<Person> listPersons() {
return this.processedPersonsList;
}
}
I have the following error
Could not autowire. No beans of 'PubSubPersonGateway' type found.
Could someone please explain why I'm getting this error / warning and if its something I need to be concerned with? FYIW, The project will compile and run correctly
This is just an IDE inspection issue, nothing more. That PubSubPersonGateway is a special #MessagingGateway bean which is not understood by IDE. Probably better to raise an improvement ticket against that IDE to let them know that Spring Integration inspection should be improved.

Service discovery in Micronaut if I have to call another microservice with a low-level HTTP client using reactor-netty

I need to call another microservice already registered in Consul. But I can't use the Micronaut HTTP Client either the RxJava HTTP client. I need to discover the URL of that microservice to call it. Therefore, I think, I can't use #client annotation to specify the name of the service that I want to discover its URL. Please, give me an example of how can I use reactor-netty to call another microservice and could discover its URL which already registered in Consul.
I achieved this by injecting the Consul Client and calling "getInstances" function his.
package happy.shopping.apigw.infrastructure.client.rest.reports;
import io.micronaut.discovery.ServiceInstance;
import io.micronaut.discovery.consul.client.v1.ConsulClient;
import io.reactivex.Flowable;
import io.reactivex.Single;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;
import static reactor.adapter.rxjava.RxJava2Adapter.singleToMono;
#Singleton
public class ReportClient {
private static final Logger logger
= LoggerFactory.getLogger(ReportClient.class);
#Inject
ConsulClient consulClient;
public Mono<List<ServiceInstance>> getInstances() {
Single<List<List<ServiceInstance>>> listaDeInstancias = Flowable.fromPublisher(consulClient.getInstances("ms-reports")).toList();
Single<List<ServiceInstance>> instanciasAplanadas = listaDeInstancias.map(this::flattenListOfListsStream);
return singleToMono(instanciasAplanadas);
}
public <T> List<T> flattenListOfListsStream(#NotNull List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
public Mono<Optional<String>> chooseAnInstance(){
Mono<List<ServiceInstance>> instances = getInstances();
Random rnd = new Random();
return instances.map(listOfInstances -> {
if (listOfInstances.size() > 0) {
int instanceIndex = rnd.nextInt(listOfInstances.size());
return Optional.ofNullable(listOfInstances.get(instanceIndex).getURI().toString());
}else {
return Optional.empty();
}
});
}
}
function "chooseAnInstance" returns an URL of one of the instances and I use that to call the other microservice' API. Function "chooseAnInstance" chooses one random instance.

Springboot Twitter Binding API Authorization

i want to make my springboot application can connect into twitter through API using my secret and client key. Here it is my code
package com.backend.siap.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TestTwitter {
#Autowired
private Twitter twitter;
#RequestMapping(value="twitter/{hashTag}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public List<Tweet> getTweets (#PathVariable final String hashTag)
{
return twitter.searchOperations().search(hashTag, 5).getTweets();
}
#RequestMapping(value="timeline", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public List<Tweet> getTimeline()
{
return twitter.timelineOperations().getHomeTimeline();
}
}
if i call getTweet method controller it return json that contain some tweet that i search using hashtag. so it work
but if i call getTimeline method controller it return something like this
org.springframework.social.MissingAuthorizationException: Authorization is required for the operation, but the API binding was created without authorization.
I also have added my secret and client code in my application properties.
how to solve that problem? thanks

Returning image from remote server play framework java

I tried to return the image as shown below:
return ok(new File("http://example.com/dpa/client_name/images/client_log.jpg"));
but the method in the controller couldn't fetch the image from the remote server and threw a image not found exception.
How do I retrieve an image from the remote server and return as a response using java play framework?
Simply use WS API
package controllers;
import play.libs.ws.WSClient;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
public class HomeController extends Controller {
#Inject WSClient ws;
public CompletionStage<Result> index() {
return ws
.url("http://www.maine-coon-cat-nation.com/image-files/orange-maine-coon-cat.jpg")
.get()
.thenApply(file -> ok(file.getBodyAsStream()).as("image/jpeg"));
}
}

Play framework 2.4 GlobalSettings. no interface expected here

I am new to the Play framework and Java in general. What is wrong with this Global.java file? I get the error no interface expected here on the line public class Global extends GlobalSettings {
import play.*;
import play.libs.*;
import com.avaje.ebean.Ebean;
import models.*;
import java.util.*;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import play.api.Application;
import play.api.GlobalSettings;
public class Global extends GlobalSettings {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
#Override
public void onStart(Application app) {
if(User.find.findRowCount() == 0){
Ebean.save((List) Yaml.load("initial-data.yml"));
}
//Start Spring WS framework
applicationContext.start();
}
#Override
public void onStop(Application app) {
applicationContext.stop();
}
}
I am trying to create a simple SOAP web service within Play Java using the Spring framework. Perhaps I am going about this the wrong way?
Remove the play.api.GlobalSettings import. Do the same for play.api.Application. These...
import play.api.Application;
import play.api.GlobalSettings;
It looks like your project has defaulted to a Scala project rather than a Java one, I think. You should be using the play.GlobalSettings and play.Application objects for a Java Play application, covered by your current play.* import.

Categories