I made a simple program that kill a process when cpu usage is high.
public class Main {
public static void main(String[] args){
try
{
if(SystemStatusReader.getCpu() < 50)
{
String startApp = "./standalone.sh 0.0.0.0 &";
// Process pr = Runtime.getRuntime().exec("pgrep -u jboss java");
Process pr = Runtime.getRuntime().exec("pidof top");
BufferedReader read = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String str = read.readLine();
System.out.println("Process id(s) to kill: " + str);
String strKillPr = "kill -9 " + str;
Process killPr = Runtime.getRuntime().exec(strKillPr);
}
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
The program works if it's running from terminal but when I try to run it from Crontab using
*/1 * * * * /usr/java/jdk1.7.0_45/bin/java -jar /usr/local/jboss-as-7.1.1.Final/bin/CpuChecker.jar
Also the jar file have the permission (chmod 777).
Anybody knows what I'm missing?
Related
I want to write a java client consumer, such that it need to pull a set of messages from a jetStream. Here I want to either pull all of the messages or pull the last messages(batch size can be specified).
Is there anyway to implement without using PullSubscribeOptions.durable() ?
Because I found out that if I don't use the durable, everytime the server sends the same batch.
public static void main(String[] args)
throws IOException, InterruptedException, JetStreamApiException, IllegalStateException, TimeoutException {
String userName = "local";
String password = "password";
String host = "0.0.0.0";
String port = "37733";
String streamName = "test_stream";
String subjectName = "test_subject_1";
int BATCH_SIZE = 100;
Connection nc = Nats.connect("nats://" + userName + ":" + password + "#" + host + ":" + port);
JetStream js = nc.jetStream();
PullSubscribeOptions pullOptions = PullSubscribeOptions.builder()
.durable("configurator_service_9")
.stream(streamName)
.build();
outerloop:
while(true){
JetStreamSubscription sub = js.subscribe(subjectName, pullOptions);
List<Message> messages = sub.fetch(1000, Duration.ofMillis(1000));
for (Message m : messages) {
System.out.println(m);
m.ack();
if(m==null) {
System.out.println(m);
nc.flush(Duration.ofSeconds(1));
nc.close();
break;
}
}
System.out.println("Message count is " + messages.size());
}
By the way as I see we can pull the entire steam on nats-cli. I need to do this again and again.
The code will not compile. I changed the JRE to 1.7. The compiler does not highlight the class in Eclipse and the CrawlConfig appears to fail in the compiler. The class should be run from the command line in Linux.
Any ideas?
Compiler Error -
Description Resource Path Location Type
Syntax error on token "crawlStorageFolder", VariableDeclaratorId expected after this token zeocrawler.java /zeowebcrawler/src/main/java/com/example line 95 Java Problem
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.WebURL;
public class Controller {
String crawlStorageFolder = "/data/crawl/root";
int numberOfCrawlers = 7;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("http://www.senym.com");
controller.addSeed("http://www.merrows.co.uk");
controller.addSeed("http://www.zeoic.com");
controller.start(MyCrawler.class, numberOfCrawlers);
}
public URLConnection connectURL(String strURL) {
URLConnection conn =null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
int test = 0;
}catch(MalformedURLException e) {
System.out.println("Please input a valid URL");
}catch(IOException ioe) {
System.out.println("Can not connect to the URL");
}
return conn;
}
public static void updatelongurl()
{
// System.out.println("Short URL: "+ shortURL);
// urlConn = connectURL(shortURL);
// urlConn.getHeaderFields();
// System.out.println("Original URL: "+ urlConn.getURL());
/* connectURL - This function will take a valid url and return a
URL object representing the url address. */
}
public class MyCrawler extends WebCrawler {
private Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g"
+ "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf"
+ "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether
* the given url should be crawled or not (based on your
* crawling logic).
*/
#Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
#Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
}
}
This is a pretty strange error since the code seems to be clean. Try to start eclipse with the -clean option on command line.
Change
String crawlStorageFolder = "/data/crawl/root";
to
String crawlStorageFolder = "./data/crawl/root";
i.e. add a leading .
I know that you can open a connection to a URL when programming in Blackberry but is it possible to open a connection on a specific port ? For example I want to send some data to the echo port of the server to check if it is alive and measure the ping time. Any ideas ?
Try something like this;
// Create ConnectionFactory
ConnectionFactory factory = new ConnectionFactory();
// use the factory to get a connection descriptor
ConnectionDescriptor conDescriptor = factory.getConnection("socket://www.abc.com:portnumber");
You can specify the port number when specifying the url to open the connection.
try this code :-
String host = "Your address" ;
new Thread()
{
run()
{
try {
SocketConnection connection = (SocketConnection)Connector.open("socket://" + host + ":80");
OutputStream out = connection.openOutputStream();
InputStream in = connection.openInputStream();
// Standard HTTP GET request all in text
// Only the required Host header, no body
String request = "GET / HTTP/1.1\r\n" +
"Host:" + host + "\r\n" +
"\r\n" +
"\r\n";
out.write(request.getBytes());
out.flush();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int firstByte = in.read();
if (firstByte >= 0) {
baos.write((byte)firstByte);
int bytesAvailable = in.available();
while(bytesAvailable > 0) {
byte[] buffer = new byte[bytesAvailable];
in.read(buffer);
baos.write(buffer);
bytesAvailable = in.available();
}
}
baos.close();
connection.close();
final_OP(new String(baos.toByteArray()) );
} catch (IOException ex) {
final_OP(ex.getMessage());
}
}
}.start();
public void final_OP(final String message) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("Output" + message);
}
});
}
I have 2 servers in AD (2008R2)
On one of them I have shared folder (c:\Shared\dirForUserAAA ==> \DC1\dir1)
On other one I have c# program that must manage folder quota on \DC1\dir1
Is it possible and how it can be done?
I try to use this piece of code, but it works only on local paths :(
public static void SetQuotaToFolder(string UNCPathForQuota, int quotaLimitBytes)
{
if (!Directory.Exists(UNCPathForQuota))
{
Directory.CreateDirectory(UNCPathForQuota);
}
// Create our interface
IFsrmQuotaManager FSRMQuotaManager = new FsrmQuotaManagerClass();
IFsrmQuota Quota = null;
try
{
// First we need to see if there is already a quota on the directory.
Quota = FSRMQuotaManager.GetQuota(UNCPathForQuota);
// If there is quota then we just set it to our new size
Quota.QuotaLimit = quotaLimitBytes;
}
catch (COMException e)
{
unchecked
{
if (e.ErrorCode == (int)0x80045301)
{
// There is no quota on this directory so we need to create it.
Quota = FSRMQuotaManager.CreateQuota(UNCPathForQuota);
// And then set our desired quota
Quota.QuotaLimit = quotaLimitBytes;
}
else
{
// some other COM exception occured so we return the error
Console.WriteLine(e);
return;
}
}
}
catch (Exception e)
{
// Generic error handling would go here
Console.WriteLine(e);
return;
}
// and finally we commit our changes.
Quota.Commit();
}
}
Old Question, but if someone needs a hint:
Open a RemotePowershell on the server where your folders are saved. Then use the Cmdlets from here
Some code snippets:
Open Runspace:
public static Runspace CreateAndOpen(string domain, string username, string password, string computername)
{
string userName = username + "#" + domain;
var securePassword = password.ToSecureString();
PSCredential credential = new PSCredential(username, securePassword);
var connectionInfo = new WSManConnectionInfo(false, computername, 5985, "/wsman", shellUri, credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
connectionInfo.OpenTimeout = 2 * 60 * 1000; // 2 minutes
Runspace powershellRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
powershellRunspace.Open();
return powershellRunspace;
}
Set a quota on a path
public void SetQuotaTemplateOnPath(Runspace runspace, string path, string template)
{
using (var pipe = runspace.CreatePipeline())
{
var newFsrmQuotaCommand = new Command("New-FsrmQuota");
newFsrmQuotaCommand.Parameters.Add("Path", path);
newFsrmQuotaCommand.Parameters.Add("Template", template);
newFsrmQuotaCommand.Parameters.Add("Confirm", false);
pipe.Commands.Add(newFsrmQuotaCommand);
var results = pipe.Invoke();
if (pipe.Error.Count > 0)
{
//Handle error
}
}
}
I am working on a project to connect test instruments and get request and response from it using webservice.
I have to request more than one service from the instrument, but when I use more than two #Gets in the server, I get an error in my browser saying
Cannot access WADL, please restart your restful webservice
This is my code,
GET
#Produces("text/html")
public String getHtml(){
String ins_name=null;
try {
String [] env=null;
//setting the environment variable.
String[]callAndArgs= {"python","instrument_name.py"};//Python and file name
Process p = Runtime.getRuntime().exec(callAndArgs,env,
new java.io.File("C:\\fakepath\\NetBeansProjects\\DemoApp1\\build\\web"));//executing Python file
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));//getting the value from Python file
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));// reading the error
ins_name = stdInput.readLine();//reading the output from the Pythonfile
System.out.println(ins_name);
}
catch (IOException e) {//catching the exception
System.out.println("exception occured");
e.printStackTrace();
System.exit(-1);
}
return ins_name;//returning the instrument name
}
#GET
#Produces("text/html")
public String getHtml1() {
String check=null;
String c1="hjhj";
String [] env=null;
//setting the environment variable.
try{
String[] callAndArgs= {"python","check_connection.py",c1};//Python and file name
Process p = Runtime.getRuntime().exec(callAndArgs,env,
new java.io.File("C:\\Users\\Balkishore\\Documents\\NetBeansProjects\\DemoApp1\\build\\web"));//executing Python file
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));//getting the value from Python file
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));// reading the error
check= stdInput.readLine();//reading the output from the Python file
System.out.println();
}
catch (IOException e) {//catching the exception
System.out.println("exception occured");
e.printStackTrace();
System.exit(-1);
}
return check;
}
/**
* Web service operation
}
/**
* PUT method for updating or creating an instance of GenericResource
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("text/html")
public String putHtml(String interface_name) {
try {
String [] env=null;
String [] callAndArgs= {"python","connection.py",this.interface_name=interface_name};//Python file with arguments
Process p = Runtime.getRuntime().exec(callAndArgs,env,
new java.io.File("C:\\fakepath\\NetBeansProjects\\DemoApp1\\build\\web"));//executing the Python file
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));//getting the input
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));//getting the error
interface_name = stdInput.readLine();//reading the output
System.out.println(interface_name);
}
catch (IOException e) {//catching the exception
System.out.println("exception occured");
e.printStackTrace();
System.exit(-1);
}
return interface_name;
}
}
I have also attached the image of the error message.
You can't define distinct "GET" for a resource unless you specify distinct Path for your methods #Path("/mypath") in addition to your resource path
#Path("/myRes")
public class myResource{
#GET #Path("/myAttr")
public void getAttr(...)
}