Categories
discuss

How can I send message to specific contact through WhatsApp from my android app?

I am developing an android app and I need to send a message to specific contact from WhatsApp. I tried this code:

Uri mUri = Uri.parse("smsto:+999999999");
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("sms_body", "The text goes here");
mIntent.putExtra("chat",true);
startActivity(mIntent);

The problem is that the parameter “sms_body” is not received on WhatsApp, though the contact is selected.

Answer

Try using Intent.EXTRA_TEXT instead of sms_body as your extra key. Per WhatsApp’s documentation, this is what you have to use.

An example from their website:

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);

Their example uses Intent.ACTION_SEND instead of Intent.ACTION_SENDTO, so I’m not sure if WhatsApp even supports sending directly to a contact via the intent system. Some quick testing should let you determine that.

Categories
discuss

What does this annotation in Intellij source code mean?

When looking into the source code of IntelliJ IDEA Community Edition project in github, in one of the files I found the following notation:

void m() {
    <selection><caret>System.out.println("");</selection>
}

What does this <selection> annotation mean? By which tool is it being processed?

The complete source of afterEnumConstantWithArgs.java is as follows.

// "Use existing implementation of 'm'" "true"
enum I {
    A("a") {
        void m() {
            <selection><caret>System.out.println("");</selection>
        }
    },
    B("b") {
        public void m() {
            System.out.println("");
        }
    };
    abstract void m();
    I(String s){}
}

Answer

Firstly you should note you’re reading test data, not a source file itself. Presumably this is emulating a file that would be loaded into IntelliJ.

<caret> would be referring to where the caret is in the file, i.e. the blinking cursor. <selection> would be the code that’s currently selected, which is why it has a beginning and end tag.

Source: reading the code until I figured this out.

Seems to be parsed by this file.

Categories
discuss

Reading a csv file with millions of row via java as fast as possible

I want to read a csv files including millions of rows and use the attributes for my decision Tree algorithm. My code is below:

String csvFile = "myfile.csv";
List<String[]> rowList = new ArrayList();
String line = "";
String cvsSplitBy = ",";
String encoding = "UTF-8";
BufferedReader br2 = null;
try {
    int counterRow = 0;
    br2 =  new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), encoding));
    while ((line = br2.readLine()) != null) { 
        line=line.replaceAll(",,", ",NA,");
        String[] object = line.split(cvsSplitBy);
        rowList.add(object); 
        counterRow++;
    }
    System.out.println("counterRow is: "+counterRow);
    for(int i=1;i<rowList.size();i++){
        try{
           //this method includes many if elses only.
           ImplementDecisionTreeRulesFor2012(rowList.get(i)[0],rowList.get(i)[1],rowList.get(i)[2],rowList.get(i)[3],rowList.get(i)[4],rowList.get(i)[5],rowList.get(i)[6]); 
        }
        catch(Exception ex){
           System.out.printlnt("Exception occurred");   
        }
    }
}
catch(Exception ex){
    System.out.println("fix"+ex);
}

It is working fine when the size of the csv file is not large. However, it is large indeed. Therefore I need another way to read a csv faster. Is there any advice? Appreciated, thanks.

Answer

In this snippet I see two issues which will slow you down considerably:

while ((line = br2.readLine()) != null) { 
    line=line.replaceAll(",,", ",NA,");
    String[] object = line.split(cvsSplitBy);
    rowList.add(object); 
    counterRow++;
}

First, rowList starts with the default capacity and will have to be increased many times, always causing a copy of the old underlying array to the new.

Worse, however, ist the excessive blow-up of the data into a String[] object. You’ll need the columns/cells only when you call ImplementDecisionTreeRulesFor2012 for that row – not all the time while you read that file and process all the other rows. Move the split (or something better, as suggested by comments) to the second row.

(Creating many objects is bad, even if you can afford the memory.)

Perhaps it would be better to call ImplementDecisionTreeRulesFor2012 while you read the “millions”? It would avoid the rowList ArrayList altogether.

Later Postponing the split reduces the execution time for 10 million rows from 1m8.262s (when the program ran out of heap space) to 13.067s.

If you aren’t forced to read all rows before you can call Implp…2012, the time reduces to 4.902s.

Finally writing the split and replace by hand:

String[] object = new String[7];
//...read...
    String x = line + ",";
    int iPos = 0;
    int iStr = 0; 
    int iNext = -1;
    while( (iNext = x.indexOf( ',', iPos )) != -1 && iStr < 7 ){
        if( iNext == iPos ){
            object[iStr++] = "NA";
        } else {
             object[iStr++] = x.substring( iPos, iNext );
        }
        iPos = iNext + 1;
    }
    // add more "NA" if rows can have less than 7 cells

reduces the time to 1.983s. This is about 30 times faster than the original code, which runs into OutOfMemory anyway.

Categories
discuss

Error: ENOENT: no such file or directory, stat ‘/public/main.html’ at Error (native)

This is my server.js file:

var express = require('express'),
    app = express();  
app 
    .use(express.static('./public'))
    .get('*',function (req,res) {
        res.sendfile('/public/main.html');
        })
 .listen(3000);

This is my main.html:

<!DOCTYPE html>
<html>
    <head>
        <titel>Contacts</titel>
    <base href'/'> 
    </head>
    <body>
        <div class="container">
         <div class="page-header">
             <h1>Contatcs</h1>
         </div>
        </div> 
    </body>
</html>

And the folder structure:

Answer

Since both the server and the index file are INSIDE the “public” directory, you can simply use :

res.sendfile('./main.html');

To answer the question in the comments : In Express 4.x, the sendfile method was replaced by the sendFile method (all lowercase -> camelCase). Probably just an oversight in early versions, that got fixed in the latter.

Categories
discuss

How to schedule an Xagent from a Domino Java agent?

Trying to get an Xagent to run on schedule by triggering from a scheduled Java agent.

The following is the code for my xagentmail.xsp which simply sends me an email:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" rendered="false">
 <xp:this.beforePageLoad><![CDATA[#{javascript:
// test send mail
doc = database.createDocument() ;
doc.replaceItemValue("Form", "memo");
doc.replaceItemValue("Subject", " from xagentmail.xsp");
doc.replaceItemValue("SendTo", "PDella-Nebbia@testdomain.com");
doc.send();

}]]></xp:this.beforePageLoad>
</xp:view>

Using the SSL-ENCRYPTED connection approach described in Devin Olson’s blog, Scheduled Xagents, I created the following scheduled Domino Java agent:

import java.io.BufferedReader; 
 import java.io.BufferedWriter; 
 import java.io.InputStreamReader; 
 import java.io.OutputStreamWriter; 
 import java.net.Socket; 

 import javax.net.ssl.SSLSocketFactory; 

 import lotus.domino.AgentBase; 

 public class JavaAgent extends AgentBase { 
 // Change these settings below to your setup as required. 
 static final String hostName = "server1.testdomain.com"; 
 static final String urlFilepath = "/test/poidemo.nsf/xagentmail.xsp"; 
 static final int sslPort = 443; 


 public void NotesMain() { 
   try { 
     final SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); 
     final Socket socket = factory.createSocket(JavaAgent.hostName, JavaAgent.sslPort); 

     final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 
     final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

     final StringBuilder sb = new StringBuilder(); 
     sb.append("GET "); 
     sb.append(JavaAgent.urlFilepath); 
     sb.append(" HTTP/1.1n"); 
     final String command = sb.toString(); 

     sb.setLength(0); 
     sb.append("Host: "); 
     sb.append(JavaAgent.hostName); 
     sb.append("nn"); 
     final String hostinfo = sb.toString(); 

     out.write(command); 
     out.write(hostinfo); 
     out.flush(); 

     in.close(); 
     out.close(); 
     socket.close(); 

   } catch (final Exception e) { 
     // YOUR_EXCEPTION_HANDLING_CODE 
   } 
 } 
 } 

When I enter the URL in a browser to my xagentmail.xsp I get mail as expected.

But my scheduled Java agent is not triggering the Xagent to send the mail.

I did set the Anonymous access to Reader for the application with both the agent and xagent. I also have restricted and non-restricted privileges on the server.

Any ideas?

Answer

I use the following approach which works great: I use HttpURLConnection instead of a BufferedWriter and I use localhost on port 80 to talk directly with the server locally.

Here’s my agent code:

import lotus.domino.AgentBase;
import lotus.domino.Session;

public class JavaAgent extends AgentBase {

    @Override
    public void NotesMain() {
        try {
            final String xpageName = "demo";

            Session session = getSession();
            dk.fmcgsolutions.XAgent.run(session.getAgentContext(), xpageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And here’s the XAgent class that the agent uses:

package dk.fmcgsolutions;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import lotus.domino.AgentContext;

public class XAgent {

    public static void run(AgentContext agentContext, String xpageName) {

        try {

            String dbPath = agentContext.getCurrentDatabase().getFilePath();
            String url = "http://localhost/" + dbPath + "/" + xpageName + ".xsp";

            System.out.println("Starting " + xpageName + " in database " + dbPath);

            URL xPageURL = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) xPageURL.openConnection();

            conn.connect();

            switch (conn.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                // read from the urlconnection via the bufferedreader
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println("Response: " + line);
                }
                bufferedReader.close();

                break;
            case HttpURLConnection.HTTP_INTERNAL_ERROR:
                System.out.println("Interal server error while running");
                break;
            default:
                System.out.println("An error occurred: " + conn.getResponseCode());
                System.out.println("Error message: " + conn.getResponseMessage());
                break;
            }

            conn.disconnect();

            System.out.println("Finished " + xpageName + " in database " + dbPath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The agent needs to run with runtime security level 2.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..