I'm trying to use Graph Api to create a tab in my Microsoft Teams Channel but I kept getting error about the program finished with non-zero exit value 1.
public static void createTab(){
if (graphClient == null) throw new NullPointerException(
"Graph client has not been initialized. Call initializeGraphAuth before calling this method");
TeamsTab newTab = new TeamsTab();
newTab.configuration.contentUrl = "https://www.google.com/?client=safari";
newTab.configuration.entityId = null;
newTab.configuration.removeUrl = null;
newTab.configuration.websiteUrl = "https://www.google.com/?client=safari";
newTab.displayName = "New Website Tab";
//Post New Tab
graphClient.teams("teams-id").channels("channel-id")
.tabs().buildRequest().expand("teamsApp").post(newTab);
}
This is my code, can someone please have a look?
Just for the heck of it, try this:
public void createTab() {
if (graphClient == null) throw new NullPointerException(
"Graph client has not been initialized. Call initializeGraphAuth before calling this method");
TeamsTab newTab = new TeamsTab();
User me = newTab.graphClient.getMe().buildRequest().get();
newTab.configuration.contentUrl = "https://www.google.com/?client=safari";
newTab.configuration.entityId = null;
newTab.configuration.removeUrl = null;
newTab.configuration.websiteUrl = "https://www.google.com/?client=safari";
newTab.displayName = "New Website Tab";
//Post New Tab
newTab.graphClient.getMe().teams("teams-id").channels("channel-id")
.getTab().buildRequest().post();
}
```
Related
I'm new to android programming and I'm having a problem with my codes. Can anyone help me or point out the cause of my error because I'm not really sure why it's giving me a NullPointerException when its a text view or if that is possible.
LogCat:
java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
at com.example.app.rosbridge.MainActivity$2$1.run(MainActivity.java:133)
Here is the code for that line:
current.setText(String.format("%.4f%s", batteryStateData.msg.current * Math.pow(10, 6), "A"));
But when i run my app my voltage is setting null and here is the code for the voltage:
voltage.setText(String.format("%.4f%s", batteryStateData.msg.voltage, "v"));
Here is the full code:
public class MainActivity extends Activity {
private TextView voltage, current, percentage, status;
private SubscribedData<BatteryState> batteryStateData;
private RosbridgeListener rosbridge;
private boolean subscribed = false;
private boolean advertised = false;
/** Indicates that Lint should ignore the specified warnings for the annotated element. */
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
Button settings_btn = (Button) findViewById(R.id.connect_btn);
voltage = findViewById(R.id.voltage_txt);
current = findViewById(R.id.current_txt);
percentage = findViewById(R.id.percentage_txt);
status = findViewById(R.id.status_txt);
connectButton = findViewById(R.id.connect_btn);
batteryStateData = new SubscribedData<>();
final Type batteryStateType = new TypeToken<SubscribedData<BatteryState>>() {
}.getType();
// ROSBRIDGE protocol allows access to underlying ROS messages and services as serialized JavaScript Object Notation (JSON) objects
WebSocket protocol communicates to a server for the connection from a user's web browser
//A connection to the rosbridge thru the IP address of the robot from the socket
rosbridge = new RosbridgeListener("ws://10.24.204.231:9090");
rosbridge.setOnDataReceivedListener(new RosbridgeMessageListener() {
// a running thread that when the connection is made the data of the topic will serialize and deserialized java objects to (and from) JSON. #param msg
#Override
public void onDataReceived(final String msg) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
batteryStateData = new Gson().fromJson(msg, batteryStateType);
voltage.setText(String.format("%.4f%s", batteryStateData.msg.voltage, "v"));
current.setText(String.format("%.4f%s", batteryStateData.msg.current * Math.pow(10, 6), "A"));
percentage.setText(String.format("%.2f%s", batteryStateData.msg.percentage, "%"));
status.setText(String.format("%s", PowerSupplyStatus.values()[batteryStateData.msg.powerSupplyStatus]));
}
});
Log.d("B9T", String.format("Received data: %s", msg));
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!subscribed) {
rosbridge.Subscribe("/battery", "sensor_msgs/BatteryState");
subscribed = true;
connectButton.setText("Disconnect");
} else {
rosbridge.UnSubscribe("/battery");
subscribed = false;
connectButton.setText("Connect");
}
}
});
Everytime when you are setting the text to textview, you must need to check if it is not null.
You can check null before you set text on textview like the following.
#Override
public void run() {
batteryStateData = new Gson().fromJson(msg, batteryStateType);
// check null before set text or calculate something
if(batteryStateData.msg.current != null){
current.setText(String.format("%.4f%s", batteryStateData.msg.current * Math.pow(10, 6), "A"));
}
// you can check belows like above
voltage.setText(String.format("%.4f%s", batteryStateData.msg.voltage, "v"));
percentage.setText(String.format("%.2f%s", batteryStateData.msg.percentage, "%"));
status.setText(String.format("%s", PowerSupplyStatus.values()[batteryStateData.msg.powerSupplyStatus]));
}
Check weather your created class with GSON is not null
and then check class fields values is not null or 0.
batteryStateData = new Gson().fromJson(msg, batteryStateType);
if (batteryStateData != null) {
if (batteryStateData.msg.voltage!=0)
voltage.setText(String.format("%.4f%s", batteryStateData.msg.voltage, "v"));
if (batteryStateData.msg.current!=0)
current.setText(String.format("%.4f%s", batteryStateData.msg.current * Math.pow(10, 6), "A"));
if (batteryStateData.msg.percentage!=0)
percentage.setText(String.format("%.2f%s", batteryStateData.msg.percentage, "%"));
if (batteryStateData.msg.values !=null)
status.setText(String.format("%s", PowerSupplyStatus.values()[batteryStateData.msg.powerSupplyStatus]));
}
I would like to create an intent using the Dialogflow java-sdk. The problem is I am am able to create training phrases and slots but I am not able to alocate the specific word to the training phrase like we do in the dialogflow console.
I have checked and Dialogflow also does not do it by itself.
Below I have wrotten the code I am currently using and the functions I have used. This may not help but may help in providing info into the current method I am using .
Is there any function in the dialogflow java api that will help me to achive this.
public OutputResponseDTO createIntent(CreateIntentInputDTO createIntentInputDTO)
{
// Instantiates a client
try (IntentsClient intentsClient = IntentsClient.create()) {
// Set the project agent name using the projectID (my-project-id)
ProjectAgentName parent = ProjectAgentName.of(createIntentInputDTO.getProjectId());
//first check if intent already exists
for (Intent intent : intentsClient.listIntents(parent).iterateAll()) {
//logger.error(intent.getDisplayName()+"Inside delete!!!!!!"+createIntentInputDTO.getIntentName());
if (intent.getDisplayName().equals(createIntentInputDTO.getDisplayName())) {
logger.error("Inside delete!!!!!!");
deleteIntent(createIntentInputDTO.getIntentName(),createIntentInputDTO.getProjectId());
}
}
List<String> trainingPhrasesIP=new ArrayList<String>();
for(int l=0;l<createIntentInputDTO.getTrainingPhrasesParts().size();l++)
{
trainingPhrasesIP.add(createIntentInputDTO.getTrainingPhrasesParts().get(l).getPhraseName());
}
// Build the trainingPhrases from the trainingPhrasesParts
List<TrainingPhrase> trainingPhrases = new ArrayList<>();
for (String trainingPhrase : trainingPhrasesIP) {
trainingPhrases.add(
TrainingPhrase.newBuilder().addParts(
Part.newBuilder().setText(trainingPhrase).build())
.build());
}
// Build the message texts for the agent's response
Message messages = Message.newBuilder()
.setText(
Text.newBuilder()
.addAllText(createIntentInputDTO.getMessageTexts()).build()
).build();
List<Parameter> parameters=new ArrayList<Intent.Parameter>();
for(int j=0;j<createIntentInputDTO.getSlotsInputDTOs().size();j++)
{
//String firstFourChars = createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName().substring(0, 5);
//System.out.println(firstFourChars);
String paraNameWithoutAtTwo;
String paraNameWithoutAtOne;
String paraNameWithoutAtAndWithDollar;
String paraNameWithAt;
try
{
paraNameWithoutAtOne=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName().replace("#sys.", "");
paraNameWithoutAtTwo=paraNameWithoutAtOne.replace("#", "");
}
catch(Exception e)
{
paraNameWithoutAtTwo=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName();
logger.info("Something happended when removing stuff");
}
paraNameWithoutAtAndWithDollar="$"+paraNameWithoutAtTwo;
paraNameWithAt="#"+paraNameWithoutAtTwo;
paraNameWithoutAt=createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName();
Parameter parameter=Parameter.newBuilder()
.setValue(createIntentInputDTO.getSlotsInputDTOs().get(j).getValue())
.setDisplayName(paraNameWithoutAtTwo)
.setValue(paraNameWithoutAtAndWithDollar)
.setEntityTypeDisplayName(createIntentInputDTO.getSlotsInputDTOs().get(j).getEntityDisplayName())
.build();
parameters.add(parameter);
}
// Build the intent
Intent intent = Intent.newBuilder()
.setDisplayName(createIntentInputDTO.getDisplayName())
.addMessages(messages)
// .addParameters(p)
.addAllParameters(parameters)
.addAllTrainingPhrases(trainingPhrases)
.build();
// Performs the create intent request
Intent response = intentsClient.createIntent(parent, intent);
// System.out.format("Intent created: %s\n", response);
try
{
IntentMasterCollection intentMasterCollection=new IntentMasterCollection();
intentMasterCollection.setName(createIntentInputDTO.getDisplayName());
intentActionMaster.save(intentMasterCollection);
}
catch(Exception e)
{
logger.error("Error adding in DB intent master");
}
try
{
//we gonna put the data again!(Training phrases only)
String[] splitName = response.getName().split("/");
// intentIds.add(splitName[splitName.length - 1]);
//finally setting all the values
updateIntent(splitName[splitName.length - 1]);
}
catch(Exception e)
{
logger.error("Error in writing to intent");
}
return new OutputResponseDTO(true, message.getStatusCode("success.message.createIntent.id"),
message.get("success.message.createIntent"), null, null,requestBean.getTraceId());
}
catch(Exception e)
{
logger.error("Error Creating Intent:"+e.getMessage());
return new OutputResponseDTO(false, message.getStatusCode("error.message.generalError.id"),
message.get("error.message.generalError"), null, e.getMessage(),requestBean.getTraceId());
}
}
I think the problem you're having is related to Parts definition.
Every training phrase is split into parts, and for each part, you can define if it is just text or if it contains an entity:
Part part1 = Part.newBuilder().setText("I want to cancel a card ended in ").build();
Part part2 = Part.newBuilder().setText("5123").setEntityType("#cardNumber").setAlias("cardNumber")
.setUserDefined(true).build();
List<Part> parts = new ArrayList<Part>();
parts.add(part1);
parts.add(part2);
Then you build the training phrase:
TrainingPhrase tp = TrainingPhrase.newBuilder().setType(Type.EXAMPLE).addAllParts(parts).build();
Here is my code:
public String addxyz ()
{
String returnStatus = "";
DBConnection conn = new DBConnection();
returnStatus = conn.fun_GetData();
ArrayList<String> emailList = new ArrayList<String>();
emailList.add("xyz#gmail.com");
emailList.add("asd#hotmail.com");
for(String email : emailList)
{
SendEmail sendEmail = new SendEmail();
boolean statusEmail = sendEmail.SendingEmail(email);
}
return returnStatus;
}
I want to know what is the best way to send email to every email address after returning method status.
For example I have 100 email list so the above method is first sending 100 email then return status.
But i want to return something then send email so is that possible?
You have to send emails asynchronously then.
You can very well right a multi threaded program wherein you are sending emails in a different executor thread and main thread returns back with a status without getting blocked on sending the emails.
You can use Java Executors api for this one.
For multi threading you can do like this:
public String addxyz (String qweqw)
{
String returnStatus = "status";
ArrayList<String> emailList = new ArrayList<String>();
emailList.add("xyz#gmail.com");
emailList.add("asd#hotmail.com");
for(String email : emailList)
{
// create a thread
Thread th = new Thread(){
#Override
public void run(){
// Your SendMail logic
SendEmail sendEmail = new SendEmail();
boolean statusEmail = sendEmail.SendingEmail(email);
}
};
th.start(); // start the thread & continue to next email
}
return returnStatus;
}
From the snippet in your question, the status and parameter seem completely useless. So you could do:
// in main execution path
String returnStatus = "status";
new Thread( new Runnable() {
#Override public void run(){ addxyz("dummy"); }
} ).start();
But I really doubt that this will work out. I guess your example misses where and why status could be changed in the function. Then this solution is void!
UPDATE
From the point where your status won't change inside the function, you can wrap the rest in a Thread/Runnable and run it. For example:
....
returnStatus = conn.fun_GetData();
new Thread( new Runnable() { #Override public void run() {
ArrayList<String> emailList = new ArrayList<String>();
emailList.add("xyz#gmail.com");
emailList.add("asd#hotmail.com");
for(String email : emailList)
{
SendEmail sendEmail = new SendEmail();
boolean statusEmail = sendEmail.SendingEmail(email);
}
}}).start();
return returnStatus;
In Java 8 you can also use Lambda:
new Thread( () -> {
// your code here
} ).start();
Trying to upgrade from 6 to 7 VAADIN getting the following error.
I new to Java and Vaadin any help would be nice.
Thanks
Description Resource Path Location Type
The method getMainWindow() is undefined for the type
private void periodicRefresh() {
// Logout if requested
if (mKicker != null) {
String kickMessage = KickoutMessageText + mKicker.getData().getName();
mKicker = null;
logoutCore();
getMainWindow().showNotification(KickoutMessageTitle, kickMessage, Notification.TYPE_WARNING_MESSAGE);
}
// Refresh logged in users
refreshLoggedInUsers();
// Refresh GPIO pin states
refreshGPIOPinStates();
}
Second problem:
Description Resource Path Location Type
The method getMainWindow() is undefined for the type new LoginForm.LoginListener()
also in same code
Description Resource Path Location Type
The method addComponent(LoginForm) is undefined for the type Panel
private void createLoginUI(final AbstractOrderedLayout parentLayout) {
final Rpi_gpio_controllerApplication application = this;
LoginForm loginForm = new LoginForm();
loginForm.addListener(new LoginForm.LoginListener() {
Rpi_gpio_controllerApplication mApplication = application;
#Override
public void onLogin(LoginEvent event) {
String loginErrorMessage = new User(
new UserData(event.getLoginParameter("username"), event.getLoginParameter("password")),
mApplication).login();
if (loginErrorMessage != null) {
Notification notification = new Notification(LoginErrorMessage, loginErrorMessage,
Notification.TYPE_ERROR_MESSAGE);
notification.setDelayMsec(1000);
getMainWindow().showNotification(notification);
}
}
});
Panel loginPanel = new Panel("Log in!!!!");
loginPanel.setWidth("200px");
loginPanel.setHeight("250px");
loginPanel.addComponent(loginForm);
parentLayout.addComponent(loginPanel);
parentLayout.setComponentAlignment(loginPanel, Alignment.MIDDLE_CENTER);
}
1st the notification are used in other way:
Notification.show(KickoutMessageTitle, kickMessage, Notification.TYPE_WARNING_MESSAGE);
2nd - panel in 6 has a default content and You can add components to it,
in version 7 the content must be set by You.
Solution - create a Layout (contentLayout) and use setContent(contentLayout)
then add other components to the contentLayout
If You need to get a Window (like the getMainWindowMethod) in vaadin 7 You need to use:
UI.getCurrent().getWindow()
EDIT:
1:
private void periodicRefresh() {
// Logout if requested
if (mKicker != null) {
String kickMessage = KickoutMessageText + mKicker.getData().getName();
mKicker = null;
logoutCore();
Notification.show(KickoutMessageTitle, kickMessage, Notification.TYPE_WARNING_MESSAGE);
}
// Refresh logged in users
refreshLoggedInUsers();
// Refresh GPIO pin states
refreshGPIOPinStates();
}
2:
private void createLoginUI(final AbstractOrderedLayout parentLayout) {
final Rpi_gpio_controllerApplication application = this;
LoginForm loginForm = new LoginForm();
loginForm.addListener(new LoginForm.LoginListener() {
Rpi_gpio_controllerApplication mApplication = application;
#Override
public void onLogin(LoginEvent event) {
String loginErrorMessage = new User(
new UserData(event.getLoginParameter("username"), event.getLoginParameter("password")),
mApplication).login();
if (loginErrorMessage != null) {
Notification notification = new Notification(LoginErrorMessage, loginErrorMessage,
Notification.TYPE_ERROR_MESSAGE);
notification.setDelayMsec(1000);
notification.show(Page.getCurrent());
}
}
});
Panel loginPanel = new Panel("Log in!!!!");
loginPanel.setWidth("200px");
loginPanel.setHeight("250px");
loginPanel.setContent(loginForm);
parentLayout.addComponent(loginPanel);
parentLayout.setComponentAlignment(loginPanel, Alignment.MIDDLE_CENTER);
}
I'm trying to implement an action in which I will add permissions to all parent nodes. However, I need to run as admin to manage the permissions. Currently my code looks like this:
permissionService = serviceRegistry.getPermissionService();
//Read the username of the current user
final String loggedInUser = authenticationService.getCurrentUserName();
ChildAssociationRef childAssociationRef = nodeService.getPrimaryParent(actionedUponNodeRef);
//Get the parent NodeRef
NodeRef parent = childAssociationRef.getParentRef();
String fileName = (String) nodeService.getProperty(parent, ContentModel.PROP_NAME);
//Iterate till you get to document library
while(!fileName.contains("documentLibrary")){
ChildAssociationRef childAssociationRef2 = nodeService.getPrimaryParent(parent);
parent = childAssociationRef2.getParentRef();
//Have to declare a final variable in order to access it in the RunAsWork
final NodeRef ref = parent;
fileName = (String) nodeService.getProperty(parent, ContentModel.PROP_NAME);
RunAsWork<?> raw = new RunAsWork<Object>() {
public Object doWork() throws Exception {
//Set permission to this folder for the logged in user
permissionService.setPermission(ref, loggedInUser, PermissionService.CONTRIBUTOR, true);
return null;
}
};
//Run as admin
AuthenticationUtil.runAs(raw, "admin");
}
The exception that I get is pretty obvious:
SEVERE: 04210027 Access Denied. You do not have the appropriate permissions to perform this operation.
Any suggestions?
Thanks
To detail the answer from Krutik, you should wrap code in a runAsSystem block like this:
final permissionService = serviceRegistry.getPermissionService();
//Read the username of the current user
final String loggedInUser = authenticationService.getCurrentUserName();
ChildAssociationRef childAssociationRef = nodeService.getPrimaryParent(actionedUponNodeRef);
//Get the parent NodeRef
NodeRef parent = childAssociationRef.getParentRef();
String fileName = (String) nodeService.getProperty(parent, ContentModel.PROP_NAME);
//Iterate till you get to document library
while(!fileName.contains("documentLibrary")){
ChildAssociationRef childAssociationRef2 = nodeService.getPrimaryParent(parent);
parent = childAssociationRef2.getParentRef();
//Have to declare a final variable in order to access it in the RunAsWork
final NodeRef ref = parent;
fileName = (String) nodeService.getProperty(parent, ContentModel.PROP_NAME);
AuthenticationUtil.runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
public Object doWork() throws Exception {
permissionService.setPermission(ref, loggedInUser, PermissionService.CONTRIBUTOR, true);
return "";
}
});
}
Try with AuthenticationUtil.runAsSystemmethod in alfresco.
AuthenticationUtil.runAsSystem(() -> {
// do your work
return null;
});