Creata Jade Agent with another agent - agents-jade

please , I need help. How to create a JADE agent in the body of another agent ?
Profile p = new ProfileImpl();
p.setParameter(Profile.MAIN_HOST, "localhost");
p.setParameter(Profile.MAIN_PORT, "1099");
AgentContainer ac = rt.createMainContainer(p);
AgentController agent ac.createNewAgent ("agentBD", "agents.AgentBD");
agent.start();

try something like this ("agent" is you current agent from whitch you create other agent):
private static Codec codec = new SLCodec();
private static ContentManager cm = new ContentManager();
static
{
cm.registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL0);
cm.registerOntology(FIPAManagementOntology.getInstance());
cm.registerOntology(JADEManagementOntology.getInstance());
}
public static AID createNewAgent(Agent agent, String name, String className)
{
CreateAgent ca = new CreateAgent();
ca.setAgentName(name);
ca.setClassName(className);
ca.setContainer((ContainerID) agent.here());
ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
request.addReceiver(agent.getAMS());
request.setOntology(JADEManagementOntology.getInstance().getName());
request.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
request.setReplyWith("new-agent-" + agent.getName() + System.currentTimeMillis());
try
{
cm.fillContent(request, new Action(agent.getAMS(), ca));
agent.send(request);
MessageTemplate mt = MessageTemplate.MatchInReplyTo(request.getReplyWith());
ACLMessage reply = agent.blockingReceive(mt, 10000);
if(reply == null)
throw new RuntimeException("cannot create agent [" + name + "; " + className + "]");
return new AID(name, AID.ISLOCALNAME);
}
catch (Codec.CodecException e)
{
throw new RuntimeException(e);
}
catch (OntologyException e)
{
throw new RuntimeException(e);
}
}

Related

Delete button stops working sporadically, only on Windows, when using our editor plugin

We are developing a markdown editor plugin for eclipse. My colleagues who are using Windows 10 encounter a bug that causes keys to stop working. The most common key is delete, other times it is ctrl + s.
Here is the code for the editor extension:
public class MarkdownEditor extends AbstractTextEditor {
private Activator activator;
private MarkdownRenderer markdownRenderer;
private IWebBrowser browser;
public MarkdownEditor() throws FileNotFoundException {
setSourceViewerConfiguration(new TextSourceViewerConfiguration());
setDocumentProvider(new TextFileDocumentProvider());
// Activator manages connections to the Workbench
activator = Activator.getDefault();
markdownRenderer = new MarkdownRenderer();
}
private IFile saveMarkdown(IEditorInput editorInput, IDocument document, IProgressMonitor progressMonitor) {
IProject project = getCurrentProject(editorInput);
String mdFileName = editorInput.getName();
String fileName = mdFileName.substring(0, mdFileName.lastIndexOf('.'));
String htmlFileName = fileName + ".html";
IFile file = project.getFile(htmlFileName);
String markdownString = "<!DOCTYPE html>\n" + "<html>" + "<head>\n" + "<meta charset=\"utf-8\">\n" + "<title>"
+ htmlFileName + "</title>\n" + "</head>" + "<body>" + markdownRenderer.render(document.get())
+ "</body>\n" + "</html>";
try {
if (!project.isOpen())
project.open(progressMonitor);
if (file.exists())
file.delete(true, progressMonitor);
if (!file.exists()) {
byte[] bytes = markdownString.getBytes();
InputStream source = new ByteArrayInputStream(bytes);
file.create(source, IResource.NONE, progressMonitor);
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
private void loadFileInBrowser(IFile file) {
IWorkbench workbench = PlatformUI.getWorkbench();
try {
if (browser == null)
browser = workbench.getBrowserSupport().createBrowser(Activator.PLUGIN_ID);
URL htmlFile = FileLocator.toFileURL(file.getLocationURI().toURL());
browser.openURL(htmlFile);
IWorkbenchPartSite site = this.getSite();
IWorkbenchPart part = site.getPart();
site.getPage().activate(part);
} catch (IOException | PartInitException e) {
e.printStackTrace();
}
}
#Override
public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException {
super.init(site, editorInput);
IDocumentProvider documentProvider = getDocumentProvider();
IDocument document = documentProvider.getDocument(editorInput);
IFile htmlFile = saveMarkdown(editorInput, document, null);
loadFileInBrowser(htmlFile);
}
#Override
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider documentProvider = getDocumentProvider();
if (documentProvider == null)
return;
IEditorInput editorInput = getEditorInput();
IDocument document = documentProvider.getDocument(editorInput);
if (documentProvider.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
}
} else {
// Convert document from string to string array with each instance a single line
// of the document
String[] stringArrayOfDocument = document.get().split("\n");
String[] formattedLines = PipeTableFormat.preprocess(stringArrayOfDocument);
StringBuilder builder = new StringBuilder();
for (String line : formattedLines) {
builder.append(line);
builder.append("\n");
}
String formattedDocument = builder.toString();
// Calculating the position of the cursor
ISelectionProvider selectionProvider = this.getSelectionProvider();
ISelection selection = selectionProvider.getSelection();
int cursorLength = 0;
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
cursorLength = textSelection.getOffset(); // etc.
activator.log(Integer.toString(cursorLength));
}
// This sets the cursor on at the start of the file
document.set(formattedDocument);
// Move the cursor
this.setHighlightRange(cursorLength, 0, true);
IFile htmlFile = saveMarkdown(editorInput, document, progressMonitor);
loadFileInBrowser(htmlFile);
performSave(false, progressMonitor);
}
}
private IProject getCurrentProject(IEditorInput editorInput) {
IProject project = editorInput.getAdapter(IProject.class);
if (project == null) {
IResource resource = editorInput.getAdapter(IResource.class);
if (resource != null) {
project = resource.getProject();
}
}
return project;
}
}
Here is the repository: https://github.com/borisv13/GitHub-Flavored-Markdown-Eclipse-Plugin
Any help is accepted

How I can link between JADE agent with the OPC

How I can link between Agent and OPC? Because when I add the Agent code, JAVA cannot connect the OPC. Thank you
public class G2P extends Agent{
//Agent initializations
protected void setup() {
// Printout a welcome message
System.out.println("G2-agent "+getAID().getName()+" is ready.");
}
public static void main(String[] args) throws Exception {
// create connection information
final ConnectionInformation ci = new ConnectionInformation();
ci.setHost("");
ci.setDomain("");
ci.setUser("");
ci.setPassword("");
ci.setClsid("F8582CF2-88FB-11D0-B850-00C0F0104305");
final String itemId1 = "....";
// create a new server
final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
try {
// connect to server
server.connect();
// add sync access, poll every 500 ms
final AccessBase access = new SyncAccess(server, 500);
access.addItem(itemId1, new DataCallback() {
#Override
public void changed(Item item, ItemState state) {
// also dump value
try {
if (state.getValue().getType() == JIVariant.VT_UI4) {
System.out.println("<<< " + state + " / value = " + state.getValue().getObjectAsUnsigned().getValue());
} else {
System.out.println("<<< " + state + " / value = " + state.getValue().getObject());
}
} catch (JIException e) {
e.printStackTrace();
}
}
});
// Add a new group
final Group group = server.addGroup("test");
// Add a new item to the group
final Item item = group.addItem(itemId1);
// start reading
access.bind();
// add a thread for writing a value every 3 seconds
ScheduledExecutorService writeThread = Executors.newSingleThreadScheduledExecutor();
final AtomicInteger i = new AtomicInteger(0);
writeThread.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
final JIVariant value = new JIVariant(i.incrementAndGet());
try {
System.out.println(">>> " + "writing value " + i.get());
item.write(value);
} catch (JIException e) {
e.printStackTrace();
}
}
}, 5, 3, TimeUnit.SECONDS);
// wait a little bit
Thread.sleep(20 * 1000);
writeThread.shutdownNow();
// stop reading
access.unbind();
} catch (final JIException e) {
System.out.println(String.format("%08X: %s", e.getErrorCode(), server.getErrorMessage(e.getErrorCode())));
}
}
}

How to get user along with it's computer name from active directory

I am new to using Active Directory and want to create search form which take username from user, do wildcard search using that and returns username found along with it's computer name. I am using following code:
private SearchResultCollection GetSearchResultCollection(string DomainName, string Filter)
{
try
{
/* Getting connection info. */
Login ObjLogin = new Login();
string ServerIP = ObjLogin.GetSystemSettingByName("LDAPServer");
string Port = ObjLogin.GetSystemSettingByName("Port");
string UserName = ObjLogin.GetSystemSettingByName("ADUsername");
string Password = ObjLogin.GetSystemSettingByName("ADPassword");
DirectoryEntry Ldap = new DirectoryEntry(#"LDAP://" + ServerIP + ":" + Port, UserName, Password);
DirectorySearcher LdapSearcher = new DirectorySearcher(Ldap);
LdapSearcher.Filter = Filter;
return LdapSearcher.FindAll();
}
catch (Exception ex)
{
return null;
}
}
public string FindUsernameInAD(string Username, out int Count)
{
Count = 0;
string FoundUsername = Username;
try
{
/* Getting domain name */
Login ObjLogin = new Login();
string DomainName = ObjLogin.GetSystemSettingByName("DomainName");
SearchResultCollection LdapSearcherResults = GetSearchResultCollection(DomainName, "(&(objectClass=user))");
foreach (SearchResult resultLdap in LdapSearcherResults)
{
if ((resultLdap.Properties["sAMAccountName"] != null) && (resultLdap.Properties["sAMAccountName"].Count > 0))
{
if (resultLdap.Properties["sAMAccountName"][0].ToString().ToLower().Contains(Username.ToLower()))
{
//return resultLdap.Properties["cn"][0].ToString() + "(" + resultLdap.Properties["sAMAccountName"][0].ToString() + "#" + Username + ")";
FoundUsername = resultLdap.Properties["sAMAccountName"][0].ToString();
Count++;
}
}
}
}
catch (Exception ex)
{
/* Catch Exception Here */
log.Error("Error in UserManager.cs, FindUsernameInAD function: " + ex.Message);
}
return FoundUsername;
}
This code returns me username but no computer name so how do I get computer name? Also I want to know that "Is computer name for user is unique for each user in active directory?"

Exception creating transaction after running sql server backup via SMO

I keep on getting the following error every time i try to create a new transaction after i have backed up my database using SMO (Sql Server Management Objects):
New transaction is not allowed because there are other threads running in the session.
I have created a little console app that demonstrates the problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;
using System.Data;
namespace TestSMO
{
class Program
{
string username = "radandba";
string password = "belmont";
string servername = "e2idev\\e2isqlexpress";
string databaseName = "e2i";
string backupfilename = "c:\\e2i.bak";
Server server;
static void Main(string[] args)
{
Program prog = new Program();
prog.server = new Server(prog.servername);
prog.server.ConnectionContext.LoginSecure = false;
prog.server.ConnectionContext.Password = prog.password;
prog.server.ConnectionContext.Login = prog.username;
try
{
prog.server.ConnectionContext.Connect();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
return;
}
Console.WriteLine("Connected");
//prog.SelectData();
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = prog.databaseName;
backup.Devices.Clear();
backup.Incremental = false;
backup.Devices.AddDevice(prog.backupfilename, DeviceType.File);
backup.BackupSetName = prog.databaseName + " database backup";
backup.BackupSetDescription = prog.databaseName + " database - Full backup";
backup.Initialize = true;
backup.CopyOnly = true;
backup.LogTruncation = BackupTruncateLogType.NoTruncate;
backup.CompressionOption = BackupCompressionOptions.Default;
backup.Complete += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(prog.backup_Complete);
backup.Information += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(prog.backup_Information);
backup.PercentComplete += new PercentCompleteEventHandler(prog.backup_PercentComplete);
backup.SqlBackupAsync(prog.server);
}
void backup_PercentComplete(object sender, PercentCompleteEventArgs e)
{
Console.WriteLine("Backup progress: " + e.Percent);
}
void backup_Information(object sender, Microsoft.SqlServer.Management.Common.ServerMessageEventArgs e)
{
Console.WriteLine("Backup status: No:" + e.Error.Number + " Detail: " + e.Error.Message);
}
void backup_Complete(object sender, Microsoft.SqlServer.Management.Common.ServerMessageEventArgs e)
{
Console.WriteLine("Backup status: No:" + e.Error.Number + " Detail: " + e.Error.Message);
SelectData();
}
public void SelectData()
{
SqlConnection sqlCon = server.ConnectionContext.SqlConnectionObject;
try
{
if (sqlCon.State != System.Data.ConnectionState.Open)
sqlCon.Open();
SqlTransaction trans = sqlCon.BeginTransaction();
SqlDataAdapter adapter = new SqlDataAdapter("select * from version", sqlCon);
adapter.SelectCommand.Transaction = trans;
DataTable dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(row[0]);
}
trans.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
sqlCon.Close();
}
Console.ReadLine();
}
}
}
You could try to enable MARS on connection (msdn about MARS)
In connection string should be: "MultipleActiveResultSets=true;"
As stated by Anders UP turned out it was the NoLogTruncation was affecting it.

Powermock: ProcessBuilder redirectErrorStream giving nullPointerException

I am using powermock to mock some native command invocation using process builder. the strange thing is these test pass sometimes and fail sometimes giving a NPE. Is this a powermock issue or some gotcha in the program.
Here is a snippet of the class I am testing:
public void method1(String jsonString, String filename) {
try {
JSONObject jObj = new JSONObject(jsonString);
JSONArray jArr = jObj.getJSONArray("something");
String cmd = "/home/y/bin/perl <perlscript>.pl<someConstant>" + " -k " + <someConstant> + " -t " + <someConstant>;
cmd += vmArr.getJSONObject(i).getString("jsonKey");
ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
pb.redirectErrorStream(false);
Process shell = pb.start();
shell.waitFor();
if (shell.exitValue() != 0) {
throw new RuntimeException("Error in Collecting the logs. cmd="+cmd);
}
StringBuilder error = new StringBuilder();
InputStream iError = shell.getErrorStream();
BufferedReader bfr =
new BufferedReader(
new InputStreamReader(iError));
String line = null;
while ((line = bfr.readLine()) != null) {
error.append(line + "\n");
}
if (!error.toString().isEmpty()) {
LOGGER.error(error`enter code here`);
}
iError.close();
bfr.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
and the unit test case is:
#PrepareForTest( {<Classtobetested>.class, ProcessBuilder.class,Process.class, InputStream.class,InputStreamReader.class, BufferedReader.class} )
#Test(sequential=true)
public class TestClass {
#Test(groups = {"unit"})
public void testMethod() {
try {
ProcessBuilder prBuilderMock = createMock(ProcessBuilder.class);
Process processMock = createMock(Process.class);
InputStream iStreamMock = createMock(InputStream.class);
InputStreamReader iStrRdrMock = createMock(InputStreamReader.class);
BufferedReader bRdrMock = createMock(BufferedReader.class);
String errorStr =" Error occured";
String json = <jsonStringInput>;
String cmd = "/home/y/bin/perl <perlscript>.pl -k "+<someConstant>+" -t "+<someConstant>+" "+<jsonValue>;
expectNew(ProcessBuilder.class, "bash", "-c", cmd).andReturn(prBuilderMock);
expect(prBuilderMock.redirectErrorStream(false)).andReturn(prBuilderMock);
expect(prBuilderMock.start()).andReturn(processMock);
expect(processMock.waitFor()).andReturn(0);
expect(processMock.exitValue()).andReturn(0);
expect(processMock.getErrorStream()).andReturn(iStreamMock);
expectNew(InputStreamReader.class, iStreamMock)
.andReturn(iStrRdrMock);
expectNew(BufferedReader.class, iStrRdrMock)
.andReturn(bRdrMock);
expect(bRdrMock.readLine()).andReturn(errorStr);
expect(bRdrMock.readLine()).andReturn(null);
iStreamMock.close();
bRdrMock.close();
expectLastCall().once();
replayAll();
<ClassToBeTested> instance = new <ClassToBeTested>();
instance.method1(json, fileName);
verifyAll();
} catch (Exception e) {
Assert.fail("failed while collecting log.", e);
}
}
I get an error on execution and the test case fails..
Caused by: java.lang.NullPointerException
at java.lang.ProcessBuilder.start(ProcessBuilder.java:438)
Note: I do not get this error on all executions. Sometimes it passes and sometimes it fails. I am not able to understand this behavior. Also, I have camouflaged some variable names because of the copyright issues.
Since your are mocking the constructor call you have to prepare your code as wall. This is because the constructor invocation is part of your code. Read more in the PowerMock documentation:
http://code.google.com/p/powermock/wiki/MockConstructor