running elasticsearch from java code - windows

I want to run elastic search from a servlet.
I use this method in my servlet to run elasticsearch but it does not seem to work.
ejbsessionbean.runcommand( "cmd C:\\ELK\\elasticsearch\\bin\\elasticsearch";)
The code for runcommand follows:
public static void runcommand(String ch) throws IOException {
if (ch.length() <= 0) {
System.err.println("Need command to run");
System.exit(-1);
}
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(ch);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:",
ch);
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}

Related

Run ansible playbook from java

Is there a way to execute ansible playbook from java.Can you please help me with reference could not find any good tutorial.
The simplest way is to run your command using ProcessBuilder:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class AnsibleServive {
public static void main(String[] args) {
runCommand("ansible-playbook test.yml -i host.ini");
}
private static void runCommand(String command) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", command);
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
StringBuilder errOutput = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errReader.readLine()) != null) {
errOutput.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Command Successfully executed.");
System.out.println(output);
} else {
System.err.println("Error ocured during running command.");
System.out.println(output);
System.err.println(errOutput);
}
} catch (IOException | InterruptedException e) {
System.err.println("Failed to execute command.");
e.printStackTrace();
}
}
}

Performance of Spring boot project when makes it installed

I made two programs. One is a Client program that sends UDP Packet to UDP Server and the other is a Server program that receives UDP Packet from UDP Client.
UDP Server is made by Spring boot.
The problem is that there is difference of performance between run in STS(Spring Tools Suite) and run as jar(maven installed).
When I run this program in STS(Run as->Spring boot app), it gets all packets from client. If Client sent 3,000 packets, it gets 3,000 packet. But when I run as jar(maven install), it gets a little of packets about 200-300. Even It's exactly same code.
I don't know why it occurs. Is there any way to build spring boot app or need some option?
Whole code is too large. so I upload connect, send, bind code.
This is Client program
public UdpClient(String[] args) {
connector = new NioDatagramConnector();
connector.setHandler(this);
ConnectFuture connFuture = connector.connect(new InetSocketAddress(
args[0], 6001));
connFuture.awaitUninterruptibly();
if(args[1] != null) {
totalCount = Integer.parseInt(args[1]);
}
if(args[2] != null) {
count = Integer.parseInt(args[2]);
}
connFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture future) {
if (future.isConnected()) {
session = future.getSession();
try {
sendData(totalCount, count);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
LOGGER.error("Not connected...exiting");
}
}
});
}
private void sendData(int totalCount, int count) throws InterruptedException {
int tempCount = 0;
for (int i = 0; i < totalCount; i++) {
try{
File udpData = new File("udp_data.txt");
BufferedReader br = new BufferedReader(new FileReader(udpData));
String line;
int k = 0;
ArrayList<IoBuffer> bufList = new ArrayList<IoBuffer>();
while((line = br.readLine()) != null) {
String[] str = line.split(" ");
IoBuffer buf = IoBuffer.allocate(str.length);
for (int j = 0; j < str.length; j++) {
int hexData = Integer.parseInt(str[j],16);
byte hexByte = (byte)hexData;
buf.put(hexByte);
}
bufList.add(buf);
buf.flip();
}
long startTime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
session.write(bufList.get(j));
tempCount++;
if(j % 100 == 0) {
Thread.sleep(1);
}
}
long endTime = System.currentTimeMillis();
System.out.println("oper Time : " + (endTime - startTime));
} catch(Exception e) {
e.printStackTrace();
}
}
System.out.println("Total Send Count : " + tempCount);
}
and this is server program.
#Service
public class ModBusUdpMina {
private static Logger logger = LoggerFactory.getLogger(ModBusUdpMina.class);
#Autowired
private IoHandlerAdapter ioUdpHandlerAdapter;
#Autowired
private ProtocolCodecFactory ambProtocolCodecFactory;
#PostConstruct
public void bind() {
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
acceptor.getFilterChain().addLast(\"codec\", new ProtocolCodecFilter(ambProtocolCodecFactory));
acceptor.setHandler(ioUdpHandlerAdapter);
acceptor.getSessionConfig().setReuseAddress(true);
acceptor.getSessionConfig().setReceiveBufferSize(1024*512);
acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
try {
acceptor.bind(new InetSocketAddress(6001));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

android async task executing api's repeteadly

I am using Android Async Task function to execute an api using urlconnection. this api in turn sends emails to selected users.Now the issue is I am getting spammed by these emails at first I thought of it as an server side issue or my script but I created a new api and used it on IOS version of my application and everything works fine.But when I execute it on android I start getting spams,so I think the Issue lies in my android programming.
public class submitparse extends AsyncTask<String ,String,String> {
String Url;
#Override
protected String doInBackground(String... params) {
URL phonelink;
HttpURLConnection urlConnection = null;
try {
phonelink = new URL(params[0]);
urlConnection = (HttpURLConnection) phonelink
.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isw);
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null) {
buffer.append(line);
}
String finalresult = buffer.toString();
return finalresult;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace(); //If you want further info on failure...
}
}
return null;
}
I am using this command to call it..
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String link = "";
new submitparse().execute(link);
}
});
On getting result I start another activity,where link is a string containing url.
If you don't care, you can also use just a new Thread. That should fit your needs and works fine. As far as I read, you don't need to use an AsyncTask and therefore IMO a normal Thread would be better.
// Runnable uiThreadRunnable = new Runnable.....
Handler handler = new Handler(); // import android.os.Handler
Runnable runnable = new Runnable() {
public void run() {
// do your stuff
// use 'handler.post(uiThreadRunnable);' to if you NEED to run something on main thread
}
};
Thread thread = new Thread(runnable);
thread.start();

Https request not working for android Application

Https request not waking on my machine for an android app while HTTP is working fine.
I did lot of goggling but can't find success.
public static String requestWithPostMethod(String url, String jsonData)
* throws
* ClientProtocolException, IOException
*/
{
//HttpURLConnection urlConnection;
String result = null;
try {
// Connect
URL newurl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) newurl.openConnection();
// urlConnection = createConnection(url);
urlConnection.setRequestMethod("POST");
urlConnection
.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.connect(); //here it return null exception
// Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
outputStream, "UTF-8"));
writer.write(jsonData);
writer.close();
outputStream.close();
// Read
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(),
"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
// {"success":true,"result":[],"error":"","error_key":"email_validation_code"}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
if (e != null) {
e.printStackTrace();
}
} catch (IOException e) {
if (e != null) {
e.printStackTrace();
}
}
return result;
}
It might be the issue with Server Certificates.

Spring and serving files from outside of the web server

I want spring to serve certain files from the /tmp... directory, the specific directory isn't determined until shortly after the server starts so using <mvc:resources location="/images/**" mapping="/absolute/path/to/image/dir"/> won't seemingly work.
As Dave Newton noted - stream them from a controller. A very basic implementation:
#RequestMapping("/static/temp/{path}")
public void getResource(#PathVariable path, OutputStream os) {
//TODO proper IO management
InputStream is = new BufferedInputStream(new FileInputStream("/temp/" + path));
IOUtils.copy(is, os);
}
I do something like this:
#RequestMapping(value="/staticFile/{id}", method = RequestMethod.GET)
public void getPhotoRide2(HttpServletResponse response, #PathVariable int id) {
try {
FileInputStream in = new FileInputStream("your file");
OutputStream out = response.getOutputStream();
response.setContentType("your mime type");
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {}
}

Resources