Using d3.js via postgres - javascript

I'm currently studying java spring and d3.js. And found myself on a roadblock since i can't seem to find the right answer to my problem after countless trial and error plus research.
The code below is the one that is my controller:
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import dashboard.atmandcam.model.MyModel;
import dashboard.atmandcam.repo.MyRepo;
#RestController
public class MyController {
#Autowired
private MyRepo myRepo;
#GetMapping("/test")
public String sayHi() {
return "hi";
}
#GetMapping("/queries")
public List<MyModel> getResult(){
return myRepo.getQueryResult();
}
#GetMapping("/queries/{id}")
public List<MyModel> getSpecific(#PathVariable String id){
return myRepo.getSpecificResult(id);
}
}
Then this is my d3.js
var url = "/queries/31370100";
d3.json(url, function(data) {
console.log(data);
});
the result of my controller is w/ the URL (http://localhost:9090/queries/31370100):
I wanna know how can i use the JSON found on my url in d3.js so i can build my charts around my database.

Related

How to use a js class in a dart file

I have a class in Dart like this
import 'package:js/js.dart';
import 'dart:html';
import 'dart:js' as js;
class VistorianTab {
void showMatrix() {
var dataset = new networkcube.DataSet({
name: dataSetName,
nodeTable: [...],
linkTable: [...],
nodeSchema: {...},
linkSchema: {...}
});
}
I get the error because networkcube isn't defined, I imported the library in the index.html.
The library is this : https://github.com/networkcube/vistorian/blob/master/core/networkcube.js
I'm new to Dart, I'm sorry if I repeteaded a question.
Thank you for your time.

Trouble running a background service in react native

This is my very first post here, so please don't blame me if I'm not as complete and clear as I have to be.
The issue
I am new to React native and I recently began to develop a react native app which could read my incoming SMS's aloud. I already achieved to retrieve the incoming messages and to read them aloud... But only if the app is the foreground.
So, could you please advise me some libraries or tutorials on the subject ?
I'm working on a Nokia 5 with Android 9.
I currently use the following libraries :
React-native-android-sms-listener to retrieve the incoming messages.
React-native-tts to read the content aloud.
What I already tried
I'm searching the Internet for more than a week now (includig Stack Overflow and this example question) and I can't find what I'm looking for. I already tried React-native-background-timer and React-native-background-job. But I couldn't never get a background timer working and React-native-background-job allows tasks to be executed every 15 minutes only (due to the Android limitations).
So I read many articles like this one explaining how to use Headless JS and other libraries until I found this codeburst tutorial today, explaining how to develop a background service to record audio calls. I tried to adapt it, but the background service never starts.
My code
I must tell you that I don't have any knowledge in Java, so the native code below may contain mistakes, even if it is based on tutorials and the React native documentation.
Currently, when the app is launched, the service IncomingSMSService is called. This service, developed following the Codeburst tutorial referenced above, relies on Headless JS and a JS function that listen to the incoming messages and then read them aloud thanks to React-native-tts.
Here is these two files :
IncomingSMSService.java
package com.ava.service;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
public class IncomingSMSService extends HeadlessJsTaskService {
#Override
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"HandleIncomingSMS",
Arguments.fromBundle(extras),
5000,
true
);
}
return null;
}
}
HandleIncomingSMS.js
import { AppRegistry } from 'react-native';
import SmsListener from 'react-native-android-sms-listener';
import Tts from 'react-native-tts';
const HandleIncomingSMS = async (taskData) => {
SmsListener.addListener(message => {
Tts.getInitStatus().then(() => {
Tts.speak(`New message from number ${message.originatingAddress} : ${message.body}`);
});
});
}
AppRegistry.registerHeadlessTask('HandleIncomingSMS', () => HandleIncomingSMS));
These pieces of code are called in a BroadcastReceiver here (IncomingSMSReceiver.java) :
package com.ava.receiver;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ava.service.IncomingSMSService;
import com.facebook.react.HeadlessJsTaskService;
import java.util.List;
public final class IncomingSMSReceiver extends BroadcastReceiver {
#Override
public final void onReceive(Context context, Intent intent) {
if (!isAppOnForeground((context))) {
Intent service = new Intent(context, IncomingSMSService.class);
context.startService(service);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses =
activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance ==
ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
I also requested the good permissions in my AndroidManifest file, and I registered the service like so :
<service
android:name="com.ava.service.IncomingSMSService"
android:enabled="true"
android:label="IncomingSMSService"
/>
<receiver android:name="com.ava.receiver.IncomingSMSReceiver">
<intent-filter android:priority="0">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
What am I doing wrong ? I don't even see service in the Running services tab of the Android Developer options... Any ideas ?
Thanks in advance for your help.
UPDATE (01/06/2019)
After reading or watching several tutorials like this one or this video, I managed to get my app working in the foreground. It now displays a persistent notification.
BUT, I don't know how I can "link" my service and my Broadcsat Receiver to this notification (for now, the service is called only if the app is in foreground).
Here is my updated code :
// IncomingSMSService
package com.ava.service;
import android.graphics.Color;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.ContextWrapper;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.facebook.react.HeadlessJsTaskService;
import com.ava.MainActivity;
import com.ava.R;
public class IncomingSMSService extends Service {
private NotificationManager notifManager;
private String CHANNEL_ID = "47";
private int SERVICE_NOTIFICATION_ID = 47;
private Handler handler = new Handler();
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
Context context = getApplicationContext();
Intent myIntent = new Intent(context, IncomingSMSEventService.class);
context.startService(myIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
handler.postDelayed(this, 2000);
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void createNotificationChannel() {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "General", notifManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(notificationChannel);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.handler.post(this.runnableCode);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Ava")
.setContentText("Listening for new messages...")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(contentIntent)
.setOngoing(true)
.build();
startForeground(SERVICE_NOTIFICATION_ID, notification);
return START_NOT_STICKY;
}
private NotificationManager getManager() {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return notifManager;
}
}
My headlessJS task :
// HandleIncomingSMS.js
import SmsListener from 'react-native-android-sms-listener';
import Tts from 'react-native-tts';
import Contacts from 'react-native-contacts';
import { text } from 'react-native-communications';
module.exports = async () => {
// To lower other applications' sounds
Tts.setDucking(true);
// Prevent the TTS engine from repeating messages multiple times
Tts.addEventListener('tts-finish', (event) => Tts.stop());
SmsListener.addListener(message => {
Contacts.getAll((err, contacts) => {
if (err) throw err;
const contactsLoop = () => {
contacts.forEach((contact, index, contacts) => {
// Search only for mobile numbers
if (contact.phoneNumbers[0].label === 'mobile') {
// Format the contact number to be compared with the message.oritignatingAddress variable
let contactNumber = contact.phoneNumbers[0].number.replace(/^00/, '+');
contactNumber = contactNumber.replace(/[\s-]/g, '');
// Phone numbers comparison
if (contactNumber === message.originatingAddress) {
if (contact.familyName !== null) {
Tts.speak(`Nouveau message de ${contact.givenName} ${contact.familyName} : ${message.body}`);
} else {
// If the contact doesn't have a known family name, just say his first name
Tts.speak(`Nouveau message de ${contact.givenName} : ${message.body}`);
}
} else if (contactNumber !== message.originatingAddress && index === contacts.length) {
// If the number isn't recognized and if the contacts have been all checked, just say the phone number
Tts.speak(`Nouveau message du numéro ${message.originatingAddress} : ${message.body}`);
}
}
});
}
contactsLoop();
// Redirect to the SMS app
text(message.originatingAddress, message = false);
});
});
}
I also added the good permissions in my AndroidManifest.xml file like the following :
...
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
...
I made some progress but I am still stuck, so if you have any idea, please share them ! Thank you !

Bar code scan and generate in xpages

I need to use barcodes in an xpages application, both to generate the barcode and to read it. Does anyone know of any libraries I can use on the application? Has anyone used these features in a xpages application? How do I find out the barcode pattern?
I am using ZXing for creating and reading different types of barcodes.
For Java 6 there is an older version available: Solvoj ZXing
EDIT:
Import http://central.maven.org/maven2/com/solvoj/zxing-java6/core-java6/3.2.0/core-java6-3.2.0.jar
Import http://central.maven.org/maven2/com/solvoj/zxing-java6/javase-java6/3.2.0/javase-java6-3.2.0.jar
Create a managed bean
Add the bean to your XPage
Managed Bean
package ch.hasselba.xpages;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.faces.context.FacesContext;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.ibm.xsp.webapp.XspHttpServletResponse;
public class ZXingBean {
public void generateDemoQRCode() {
FacesContext fc = FacesContext.getCurrentInstance();
XspHttpServletResponse response = (XspHttpServletResponse) fc.getExternalContext().getResponse();
try {
response.setContentType("image/png");
response.getOutputStream().write(generateQRCode("Hello World!", 200, 200 ));
} catch (IOException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
fc.responseComplete();
}
public byte[] generateQRCode(String text, int width, int height)
throws WriterException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitMatrix matrix = new MultiFormatWriter().encode(text,
BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToStream(matrix, "png", baos,
new MatrixToImageConfig());
return baos.toByteArray();
}
}
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config>
<managed-bean>
<managed-bean-name>zxingBean</managed-bean-name>
<managed-bean-class>ch.hasselba.xpages.ZXingBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
XAgent
<xp:view
xmlns:xp="http://www.ibm.com/xsp/core"
rendered="false"
viewState="nostate">
<xp:this.beforeRenderResponse><![CDATA[#{javascript:zxingBean.generateDemoQRCode()}]]></xp:this.beforeRenderResponse>
</xp:view>
I am using Barcode4J in an XPages application to generate bar codes: http://barcode4j.sourceforge.net/.

Inject $http into Tour of Heroes Component

I have the Tour of Heroes app running, but I want to extend it to make ajax calls.
I have a WebAPI service that serves up the data (CORS enabled) and have proven it w/ a silly little non Angular client using JQuery $.post and $GetJson ... All was going well...
Here is my hero-details.component.ts file
(happy to include any others that may help...)
import {Component , Input, OnInit } from '#angular/core';
import { ActivatedRoute, Params } from '#angular/router';
import { Location } from '#angular/common';
import { HttpModule } from '#angular/http';
import 'rxjs/add/operator/switchMap';
import { Hero } from './hero';
import { HeroService } from './hero.service';
#Component({
selector: 'hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls : ['./hero-detail.component.css']
})
export class HeroDetailComponent { // implements OnInit {
#Input() hero: Hero;
powers = ['Really Smart', 'Super Flexible', 'Weather Changer'];
submitted = false;
constructor(
private heroService: HeroService,
private route: ActivatedRoute,
private location: Location,
$http //**--LINE OF INTEREST #2**
) { }
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
}
save(): void {
this.heroService.update(this.hero)
.then(() => this.goBack());
}
goBack(): void {
this.location.back();
}
onSubmit() { this.submitted = true; }
callService( ) {
var uri = 'http://localhost:61212/api/heros';
//**// LINE OF INTEREST #1**
$http({
method: 'GET',
url: uri
}).then(function () { alert('success'); }, function () { alert('fail');});
};
}
If I try to compile I get
TS2304: Cannot find '$http'
I can comment the $HTTP call (Line of Interest #1 ) and it compiles, it runs and i do enter the function and hit a breakpoint where i declare and assign the variable "uri". So I am reasonably sure I have the problem isolated.
So I believe, based on hours of googling, that I need to DI the $http object into this component
But when I pass $http into the constructor (LINE OF INTEREST #2) I get the following error when I try to compile
TS7006 Parameter '$http' implicitly has an 'any' type
I have googled this so much Larry and Sergy have asked me to knock it off.
What I have found is $http being passed into controllers, maybe Im missing something, but I can not seem to translate those articles into something that works for this.
1) Am I right that injecting the $http object is what needs to be done
2) What is the syntax?
when I was googling , i was just googling angular and most the articles were for angular1. Thats why I was seeing answers that involved controllers, etc.
angular2 is much different. If you are trying to get off the ground, try searching angular2 instead. at least the articles you run across will be relevant.
if you are using visual studio.. here is a nice link to get you started...
https://jonhilton.net/2016/12/01/fast-track-your-angular-2-and-net-core-web-app-development/

I am trying to play video using jquery but anchor tag not working while im trying to display video names?

package controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.sun.corba.se.spi.orbutil.fsm.Action;
import bean.Video;
import dao.Dao;
import daoimpl.daoImpl;
public class DisplayVideo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Dao dao=new daoImpl();
String action=request.getParameter("action");
if(action.equals("display")){
ArrayList<Video>al=dao.getAllVideo();
//PrintWriter pw=response.getWriter();
Gson gson=new Gson();
String json = gson.toJson(al);
System.out.println(json);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
This is my servlet where im getting data in json format.
<html>
<head>
<script type="text/javascript" src='js/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
alert("on document ready");
$('#video').click(function(event) {
alert("on click");
$.post("Controller?action=display",
function (data) {
alert("key"+data);
var json = data;
alert("value"+json);
$.each(json, function(key,value) {
alert("key1"+value);
var v ="<a href=${pageContext.request.contextPath}/videos/"+value.videoUrl+"target='blank'>"+value.videoUrl+"</a>";
$(v).appendTo($content);
});
});
});
});
</script>
</head>
<body>
<div id='content'>
<button id="video">Play</button>
</div>
</body></html>
This my sucess.jsp file from here control goes to servlet and get data in json format from database i have only save video name c.mp4,java.mp4 and cpp.mp4 in database also i have create a folder named videos in my webcontent folder in my project and save videos in that folder also.Response getting properly but after printing alert inside each their is nothing print on screen.my requirment is print that all names of video and onclick of link play video in iframe or in popup window.please help me i didnt know the tags which are used.Thanks in Advance.

Categories

Resources