Twitter raw JSON Spring social Twitter - spring-social

How to get original JSON data tweet using spring social Twitter API ? There is "Tweet" class, but I didn't find any function that allows to retrieve original tweet content- returned by Twitter in JSON format.

I don't know why do you want the raw JSON data but it is possible and here is how you can fetch it:
Follow this Guide to setup Spring Social Twitter.
If you want raw JSON data from Twitter then you can use the RestTemplate obtained from TwitterTemplate.
Add this Controller in above guide:
#Controller
#RequestMapping("/jsontweets")
public class JsonTweetsController {
private ConnectionRepository connectionRepository;
private TwitterTemplate twitterTemplate;
#Inject
public JsonTweetsController(Twitter twitter, ConnectionRepository connectionRepository, TwitterTemplate twitterTemplate) {
this.connectionRepository = connectionRepository;
this.twitterTemplate = twitterTemplate;
}
#RequestMapping(method=RequestMethod.GET)
public String helloTwitter(#RequestParam String search, Model model) {
if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
return "redirect:/connect/twitter";
}
Connection<Twitter> con = connectionRepository.findPrimaryConnection(Twitter.class);
UserProfile userProfile = con.fetchUserProfile();
String username = userProfile.getFirstName() + " " + userProfile.getLastName();
RestTemplate restTemplate = twitterTemplate.getRestTemplate();
//More Query Options # https://dev.twitter.com/rest/reference/get/search/tweets
String response = restTemplate.getForObject("https://api.twitter.com/1.1/search/tweets.json?q="+search, String.class);
System.out.println("JSON Response From Twitter: "+response);
model.addAttribute("jsonstring", response);
model.addAttribute("username", username);
return "json";
}
}
Add a template to view raw tweets json.html:
<!DOCTYPE html>
<html>
<head>
<title>JSON Tweets</title>
</head>
<body>
<h3>Hello, <span th:text="${username}">Some User</span>!</h3>
<div th:text="${jsonstring}">JSON Tweets</div>
</body>
</html>
Check the complete Project and the latest Commit for above code.

Related

How to fetch url api "http://terriblytinytales.com/test.txt" in spring boot

I am using Rest Template :- TO fetch The data
#RestController
public class apicontroller {
#Autowired
public RestTemplate restTemplate;
#RequestMapping(value="/movies",method = RequestMethod.GET,consumes = MediaType.TEXT_PLAIN)
public List<Object> getobject(){
Object[] movies=restTemplate.getForObject("http://terriblytinytales.com/test.txt",Object[].class);
return Arrays.asList(movies);
}
}
It is not fetching the data as its content type is text/plain
What should i do to change Content type here
Text content can't be assigned to an array. Change Object[] to String.
String movies = restTemplate.getForObject("https://terriblytinytales.com/test.txt", String.class);

HttpStatus 406 "not acceptable" when returning Flux<String> on Spring 4.3.7 MVC Controller to a EventSource in html page

Im trying to make a timer of how much time a page is open via spring webflux, i had made this example work on springboot but with spring mvc is not working, so i know the code does work. may i have to set up something im not aware of?
Controller:
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(){
return "home";
}
#RequestMapping(value = "/timer", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public #ResponseBody Flux<String> startTimer(){
Instant startTime = Instant.now();
return Flux.fromStream(
Stream.generate(() -> calculateTimeMethod(startTime, Instant.now()))
).delayElements(Duration.ofSeconds(1));
}
}
JSP home.jsp :
<html>
<head>
<title> Home </title>
</head>
<body>
<label> tiempo trascurrido </label>
<label id="timer"></label>
<script>
var eventSource = new EventSource("url/timer");
eventSource.onmessage = function ( event ) {
document.getElementById("timer").innerText = event.data;
};
</script>
</body>
</html>
home page load but timer doesnt start, console output shows: Failed to load resource: the server responded with a status of 406 (No Aceptable)

How to load a JavaScript file using thymeleaf + springboot

I have 2 methods that return a ModelAndView Object.
The first one gets the mapping from the browser and returns a modelandview that links to to an html file.
On that html file on the end I link a script tag to a spring root like this:
<!-- Calendar Js -->
<script type="text/javascript" src="../../../static/assets/vendor/netcorr/calendar/calendar.js"
th:src="#{/customer/web/wall/calendarItems(wallId=${wallId})}"></script>
In the controller, I have the second method that loads based on this call that I'm making just above:
/customer/web/wall/calendarItems(wallId=${wallId})
This method throws into the modelandview some objects that i need in the view.
This modelandview has root to a js file.
The problem is that the html does not load the js file that is called above.
Tried some solutions found on Stackoverflow, the solutions were to handle all of this in the mvdconfig controller.
And go throw the dependencies and make sure the dependencies are for Spring 4.
I m using Spring 1.5.9 and spring-boot-starter-thymeleaf
#GetMapping(value = "/customer/web/wall/calendar", params = {"wallId"})
public ModelAndView calendar(#RequestParam(value = "wallId") long wallId,
Authentication auth,
RedirectAttributes redirectAttributes){
ModelAndView modelAndView = new ModelAndView("/customer/wall/calendar");
modelAndView.addObject("wallId",wallId);
return modelAndView;
}
#GetMapping(value = "/customer/web/wall/calendarItems", params = {"wallId"})
public ModelAndView calendarItems(#RequestParam(value = "wallId") long wallId,
Authentication auth,
RedirectAttributes redirectAttributes){
User currentUser = (User) auth.getPrincipal();
Set<Long> wallIds = new HashSet<>();
wallIds.add(wallId);
PlaybookFilters playbookFilters = new PlaybookFilters();
playbookFilters.setCustomerId(currentUser.getCustomerId());
playbookFilters.setWallIds(wallIds);
List<Playbook> playbooks = playbookService.getPlaybooks(playbookFilters);
Date dateBegin = calendarService.getDateBegin();
Date dateEnd = calendarService.getDateEnd();
List<CalendarItem> calendarItems = calendarService.fetchPbiForPlaybooks(playbooks, dateBegin, dateEnd);
ArrayNode items = objectMapper.createArrayNode();
calendarItems.forEach(item -> items.add(item.toJsonNode()));
ModelAndView modelAndView = new ModelAndView("/customer/wall/calendarItems");
modelAndView.addObject("events", items);
return modelAndView;
}

Storing an image using ajax request inside Postgresql in Spring application

I am trying to store an image in postgresql db from my spring application but I am stuck with multiple problems and confusion.
First let me give you the overview of my spring application code:
var documentData = new FormData();
function update(){
var fname=document.getElementById("fname").value;
var lname=document.getElementById("lname").value;
var password=document.getElementById("password").value.trim();
var email=document.getElementById("email").value;
documentData.append('fname',fname);
documentData.append('lname',lname);
documentData.append('password',password);
documentData.append('email',email);
documentData.append('profilePic',$('#profilePic').attr('src'));
alert($('#profilePic').attr('src'));
$
.ajax({
type : 'PUT',
url : baseUrl + "/restApi/UpdateUser",
data : JSON
.stringify({
documentData
}),
success: function(){
location.reload(true);
},
error : function(e) {
},
dataType : "json",
contentType : "application/json"
});
}
}
$(function () {
$(":file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#profilePic').attr('src', e.target.result);
$('#viewPic').attr('src',e.target.result);
};
I have this controller
#RequestMapping(value = "/restApi/UpdateUser", method = RequestMethod.PUT, headers = "Accept=application/json")
public ServiceResponse modifyUser(#RequestBody Object user)
{
return setDataPut("http://localhost:7020/UpdateUser",user,getUserObject().getUsername(),getUserObject().getPassword());
}
In my setDataPut method I am sending response with GSON
WebResource webResource = client
.resource(path);
ClientResponse response = webResource.type("application/json").accept("application/json")
.put(ClientResponse.class, gson.toJson(object));
In model class I took byte[] type variable and in db I made column with type bytea
Now In above gson service the call is made to rest services hosted.
#CrossOrigin
#RequestMapping(value = "/ModifyUser", method = RequestMethod.PUT, headers = "Accept=application/json")
public ServiceResponse modifyUser(#RequestBody User user) {
/*Code which deals with storing User data*/
}
So I have taken all data through model User class.
Now earlier it was working perfectly until I wanted to store image also.
Nothing is getting saved no error.
Confusion: If I am sending image with some data then should I change content type or add enctype as "multipart/form-data". But If I use multipart then what should be changed in headers. Like #produces #consumes. Major doubt is whether I need to convert the image in binary code before sending?
Problem: I am having trouble in storing image in postgresql through ajax request. Please look through my code what is the problem.
You are asking quite a lot in one question here. Essentially, you are asking how to upload files from the browser/client to the Spring-based server, how to handle that upload in the Spring-based server in order to save it into a Postgresql database and associate it with my User entity so that I can fetch it again later.
So, let's have a go at answering all of that for you.
Let's start on the client-side. This code will upload the chosen file to an existing resource:-
index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script>
function upload() {
var data = new FormData();
data.append('file', jQuery('#file')[0].files[0]);
jQuery.ajax({
url: '/userImage/userId',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
});
}
</script>
</head>
<body>
<div>
<h1>New File</h1>
<input type="file" id="file" name="file"/>
<button onclick="upload()">Upload</button>
</div>
</body>
</html>
Now, turning our attention to the Spring-bsed server side. To abstract away the implementation of exactly how to store the uploaded file in the database (and how to update it, and how to fetch it, and how to delete it and so on) I would use Spring Content otherwise you have a lot of code to write that Spring Content already implements for you.
So, add the following dependencies:
pom.xml
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-jpa</artifactId>
<version>0.1.0</version> // 0.0.11 for Spring Boot 1 dependencies
</dependency>
Configure the database schema creation in one of your config classes:
Config.java
#Configuration
#EnableJpaStores // enable JPA-based storage
public class PostgresqlTestConfig {
...dataSource and entityManager, etc beans...
#Value("/org/springframework/content/jpa/schema-drop-postgresql.sql")
private Resource dropReopsitoryTables;
#Value("/org/springframework/content/jpa/schema-postgresql.sql")
private Resource dataReopsitorySchema;
#Bean
DataSourceInitializer datasourceInitializer() {
ResourceDatabasePopulator databasePopulator =
new ResourceDatabasePopulator();
databasePopulator.addScript(dropReopsitoryTables);
databasePopulator.addScript(dataReopsitorySchema);
databasePopulator.setIgnoreFailedDrops(true);
DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource());
initializer.setDatabasePopulator(databasePopulator);
return initializer;
}
}
Associate content with your User entity:
User.java
#Entity
public class User {
...existing fields...
#ContentId private String contentId;
private String mimeType;
}
Create a UserStore:
UserImageStore.java
public interface UserImageStore extends AssociativeStore<User, String> {
}
Update your controller to handle the upload of files, store them in the database and associating that stored image on your entity:
UserController.java
#Autowired
private UserImageStore store;
...
#RequestMapping(value="/userImage/{userId}", method = RequestMethod.POST)
public ResponseEntity<?> setContent(#PathVariable("userId") Long id, #RequestParam("file") MultipartFile file)
throws IOException {
User user = // fetch your existing user here
user.setMimeType(file.getContentType());
String originalFilename = file.getOriginalFilename();
InputStream is = file.getInputStream();
OutputStream os = ((WritableResource)store.getResource(originalFilename)).getOutputStream();
IOUtils.copyLarge(is, os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
// associate content (this will update the #ContentId field)
store.associate(user, originalFilename);
// save updated content-related info
save(user);
return new ResponseEntity<Object>(HttpStatus.OK);
}
return null;
#RequestMapping(value="/userImage/{userId}", method = RequestMethod.GET)
public ResponseEntity<?> getContent(#PathVariable("userId") Long id) {
User user = // fetch your existing user here
Resource r = store.getResource(user.getContentId());
HttpHeaders headers = new HttpHeaders();
headers.setContentLength(r.getContentLength());
headers.set("Content-Type", user.getMimeType());
return new ResponseEntity<Object>(r, headers, HttpStatus.OK);
}
return null;
}
That's about it. So what's going to happen here is that when your app starts it sees the dependency on spring-content-jpa and then it sees your UserImageStore. Assumes that you want to store images (BLOBs) in jpa and injects a JPA implementation of the UserImageStore interface meaning that you don't need to write it yourself. Spring Content hides the implementation but exposes a relatively simply interface (based on Spring Resource actually) that is #Autowired into your controller making that implementation simple.
Anyways, let me know if you are using Spring Data or Spring Boot and I can update this answer so that it is more relevant for you.
HTH

How to return JSON from spring RESTful service and access it using RestTemplate class

I made a spring RESTful web service for giving list of top songs in JSON formate, for this I added song names in a List and I returned this from the #Restcontroller of my Spring RESTful web service.SO #RestController will automatically process this List and rturns me this JSON form ["song1","song2","song3"].
Now can any body tell me how I can return song names with some more attribute like
- (Song Name , Film, Lyricist, Singer(s), Total hits)
For Example - (“Lungi Dance”, “Chennai Express”, "Honey Singh", "Honey Singh”, 5000).Also tell me how can I access it my spring MVC application calling this web service using RestTemplate.
Please tell me the changes in below files.
Inside my #RestController class of my Spring RESTful web service
#RequestMapping(value = "/topsongsWS", headers="Accept=application/json")
Public List<?> getTopSongsWS()
{
List<String> l1 = new ArrayList<String>();
l1.add("mann mera (Table No 21)");
l1.add("Lazy lad (Ghanchakkar)");
l1.add("Oye boy Charlie (Matru Ki Bijli Ka Mandola)");
l1.add("Blue Hai Pani Pani");
l1.add("Latt lag gayi (Race 2)");
return l1;
}
Inside my config-servlet.xml
<context:component-scan base-package="com.songs.service.controller" />
<mvc:annotation-driven />
Inside the controller of my spring MVC app calling this above RESTful web service
#RequestMapping(value="/topsongs",method=RequestMethod.POST)
public String getTopSongs(ModelMap md)
{
//did stuff to configure headers & entity
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
//this is the URL of my RESTfulservice returning JSON format ["song1","song2","song3"]
String url="http://localhost:7001/SongAppWS/songappWS/topsongsWS";
RestTemplate rt=new RestTemplate();
ResponseEntity<?> listoftopmovies=rt.exchange(url,HttpMethod.GET,entity, List.class);
md.addAttribute("listname", "Top 5 Songs of The Week:");
String response=listoftopmovies.getBody().toString();
List<String> listed = new ArrayList<String>(Arrays.asList(response.split(", ")));
md.addAttribute("res",listed);
return "Sucess";
}
To return your songs with more attribute, you should create a resource representation class.In your case,it could look like
class Song {
private String name
private String film
//other fields and methods...
Then in your restfull ws
#RequestMapping(value = "/topsongsWS", headers="Accept=application/json")
public List<?> getTopSongsWS()
{
List<Song> l1 = new ArrayList<Song>();
l1.add(new Song(atr1,atr2....));
l1.add(new Song(atr1,atr2....));
l1.add(new Song(atr1,atr2....));
return l1;
}
In your spring mvc app, you should have too the resource representation class, and the response type will now be Song instead of String
To consume your ws, this should work
#RequestMapping(value="/topsongs",method=RequestMethod.POST)
public String getTopSongs(ModelMap md)
{
String url="http://localhost:7001/SongAppWS/songappWS/topsongsWS";
RestTemplate rt=new RestTemplate();
Song[] songs = template.getForObject(url, Song[].class);
md.addAttribute("listname", "Top 5 Songs of The Week:");
md.addAttribute("res", Arrays.asList(songs));
return "Sucess";
}
you have to use model class like List
Please have a look this below source code in github. It has json response as object. Hope it will help.
https://github.com/mohansaravanan/spring
https://github.com/mohansaravanan/spring/tree/master/springmvc-3.2.2

Resources