I just want to create a simple policy using Balana code in very simple and basic steps ! This policy contain only one resource and one rule just to see how policies can be created in Balana!.
and this is my code
MatchElementDTO medto = new MatchElementDTO();
medto.setMatchId("urn:oasis:names:tc:xacml:1.0:function:string-equal");
AttributeValueElementDTO avdto = new AttributeValueElementDTO();
avdto.setAttributeValue("file");
avdto.setAttributeDataType("http://www.w3.org/2001/XMLSchema#string");
AttributeDesignatorDTO addto = new AttributeDesignatorDTO();
addto.setAttributeId("urn:oasis:names:tc:xacml:1.0:resource:resource-id");
addto.setCategory("urn:oasis:names:tc:xacml:3.0:attribute-category:resource");
addto.setDataType("http://www.w3.org/2001/XMLSchema#string");
addto.setMustBePresent("true");
medto.setAttributeValueElementDTO(avdto);
medto.setAttributeDesignatorDTO(addto);
AllOfElementDTO aodto = new AllOfElementDTO();
aodto.addMatchElementDTO(medto);
List<AllOfElementDTO> allOfElementDTOs = new ArrayList<AllOfElementDTO>();
allOfElementDTOs.add(aodto);
AnyOfElementDTO aydto = new AnyOfElementDTO();
aydto.setAllOfElementDTOs(allOfElementDTOs);
List<AnyOfElementDTO> anyOfElementDTOs = new ArrayList<AnyOfElementDTO>();
anyOfElementDTOs.add(aydto);
TargetElementDTO tedto = new TargetElementDTO();
tedto.setAnyOfElementDTOs(anyOfElementDTOs);
RuleElementDTO redto = new RuleElementDTO();
redto.setRuleId("ruleForFile");
redto.setRuleEffect("Permit");
redto.setTargetElementDTO(tedto);
List<RuleElementDTO> ruleElementDTOs = new ArrayList<RuleElementDTO>();
ruleElementDTOs.add(redto);
// Creating Policy by PolicyElementDTO
PolicyElementDTO pedto = new PolicyElementDTO();
pedto.setPolicyName("amirPolicy");
pedto.setPolicyDescription("simple having one element policy");
pedto.setRuleCombiningAlgorithms("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
pedto.setRuleElementDTOs(ruleElementDTOs);
pedto.setTargetElementDTO(tedto);
pedto.setVersion("1.0");
try {
pb.build(pedto);
} catch (PolicyBuilderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I call build(PolicyElementDTO) .. then there I got error that Exception in thread "main" java.lang.NullPointerException. Where is the problem in my code
Actually, I want to create policy by giving some parameters only.. (i.e. Subject, Action, Resource).
Anyone can guide me. I am newbie in Balana. So plz help me step by step.
Related
I am developing a REST client using JBOSS app server and RESTEasy 2.3.6. I've included the following line at the beginning of my code:
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
Here's the rest of the snippet:
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, port, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userid,password));
ClientExecutor executor = createAuthenticatingExecutor(httpclient, host, port);
String uriTemplate = "http://myhost:8080/webapp/rest/MySearch";
ClientRequest request = new ClientRequest(uriTemplate, executor);
request.accept("application/json").queryParameter("query", searchArg);
ClientResponse<SearchResponse> response = null;
List<MyClass> values = null;
try
{
response = request.get(SearchResponse.class);
if (response.getResponseStatus().getStatusCode() != 200)
{
throw new Exception("REST GET failed");
}
SearchResponse searchResp = response.getEntity();
values = searchResp.getValue();
}
catch (ClientResponseFailure e)
{
log.error("REST call failed", e);
}
finally
{
response.releaseConnection();
}
private ClientExecutor createAuthenticatingExecutor(DefaultHttpClient client, String server, int port)
{
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
HttpHost targetHost = new HttpHost(server, port);
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
// Create ClientExecutor.
ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);
return executor;
}
The above is a fairly simple client that employs the ClientRequest/ClientResponse<T> technique. This is documented here. The above code does work (only left out some trivial variable declarations like host and port). It is unclear to me from the JBOSS documentation as to whether I need to run RegisterBuiltin.register first. If I remove the line completely - my code still functions. Do I really need to include the register method call given the approach I have taken? The Docs say I need to run this once per VM. Secondly, if I am required to call it, is it safe to call more than one time in the same VM?
NOTE: I do understand there are newer versions of RESTEasy for JBOSS, we are not there yet.
My program encountered a error:
"org.jboss.remoting3.ProtocolException: Too many channels open"
I have search from internet for some solutions to fix this error.Unfortunately, the suggestions from others is not working for me.
Below is the Code on how I call the jndi remote and the properties that I have used.
public static void createUser(String loginID) throws Exception {
Hashtable props = new Hashtable();
try {
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
props.put(Context.PROVIDER_URL, "remote://" + localhost:4447);
props.put("jboss.naming.client.ejb.context", "true");
props.put(Context.SECURITY_PRINCIPAL, "userJBoss");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
context = new InitialContext(props);
context.lookup("ejb:/createUserOperation/CreateUserGenerator!password.api.CreateUserService");
.....
......
LOGGER.info("DONE");
} catch (Exception e) {
LOGGER.error("ERROR");
} finally {
context.close();
}
}
Due to some certain reason I am not able to show all the content of the method.
The "createUser" will be call everytime when there is a needed of create new user. It will be call up to hundred or thousand time.
I did always close the connection when every time it finish execute the method.
Let say I have call the method for 100 times, some of the users will be created successfully whereas some of the users will be failed.
Error below will prompt to me:
2014-12-04 17:23:23,026 - ERROR [Remoting "config-based-naming-client-endpoint" task-4] (org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver- Line:134) - Failed to open channel for context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext#bbaebd6, receiver=Remoting connection EJB receiver [connection=Remoting connection <78e43506>,channel=jboss.ejb,nodename=webdev01]} org.jboss.remoting3.ProtocolException: Too many channels open
Once the error occurred, it required me to restart my jboss.And it comes again after sometimes.
Appreciate it if anyone wound able to help on my problem faced.
Thanks
You are using mixture of context properties.
This should be enough
final Properties ejbProperties = new Properties();
ejbProperties.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
ejbProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
ejbProperties.put("remote.connections", "1");
ejbProperties.put("remote.connection.1.host", "localhost");
ejbProperties.put("remote.connection.1.port", "4447");
ejbProperties.put("remote.connection.1.username", "ejbuser");
ejbProperties.put("remote.connection.1.password", "ejbuser123!");
final EJBClientConfiguration ejbClientConfiguration = new PropertiesBasedEJBClientConfiguration(ejbProperties);
final ConfigBasedEJBClientContextSelector selector = new ConfigBasedEJBClientContextSelector(ejbClientConfiguration);
EJBClientContext.setSelector(selector);
final Context context = new InitialContext(ejbProperties);
// lookup
Foo proxy = context.lookup("ejb:/createUserOperation/CreateUserGenerator!password.api.CreateUserService");
when using org.jboss.ejb.client.naming it creates EJBClientContext object.
When closing context you are closing InitialContext not EJBClientContext
to close EJBClientContext:
EJBClientContext.getCurrent().close();
There is a known JBoss bug (EAP 6, AS 7) whereby opening and closing too many InitialContext instances too quickly causes the following error:
ERROR: Failed to open channel for context EJBReceiverContext
Instead of:
final Properties properties = ...
final Context context = new InitialContext( properties );
Try caching the context for a set of properties instead:
private Map<Integer, InitialContext> initialContexts = new HashMap<>();
final Context context = getInitialContext(properties);
private InitialContext getInitialContext(final Properties properties) throws Exception {
final Integer hash = properties.hashCode();
InitialContext result = initialContexts.get(hash);
if (result == null) {
result = new InitialContext(properties);
initialContexts.put(hash, result);
}
return result;
}
Remember to call close() when the context is no longer necessary.
I'm trying to connect to a ForexTrading broker FIX API and do some trading.
I tried my best to read through the Quickfix for .net. and almost understand the process of how the quickfix works. However, when I try to initiate the socketinitiator, I failed to do that and there are no complaints and exceptions from VS 2012. It is simply stuck there.
Here's my code:
private void iFind_ItemClick(object sender, ItemClickEventArgs e)
{
try
{
QuickFix.SessionSettings settings = new QuickFix.SessionSettings("C:\\Users\\Administrator\\Documents\\My Box Files(shewenhao#hotmail.com)\\Work With Mr.Liu\\ForexAutoTradingSystem\\ForexAutoTradingSystem\\integralfix.cfg");
IntegralFixAPI integralFixAPIApplication = new IntegralFixAPI();
QuickFix.IMessageStoreFactory storeFactory = new QuickFix.FileStoreFactory(settings);
QuickFix.ILogFactory logFactory = new QuickFix.ScreenLogFactory(settings);
QuickFix.Transport.SocketInitiator initiator = new QuickFix.Transport.SocketInitiator(
integralFixAPIApplication, storeFactory, settings, logFactory);
MessageBox.Show(settings.ToString());
integralFixAPIApplication.MyInitiator = initiator;
initiator.Start();
while (true)
{
Thread.Sleep(200);
MessageBox.Show("true");
}
//initiator.Stop();
}
catch (System.Exception systeme)
{
Console.WriteLine(systeme.Message);
Console.WriteLine(systeme.StackTrace);
}
}
You may notice that I have a MessageBox right below the SocketInitiator and it pops up before this QuickFix.Transport.SocketInitiator line. I do not get it that why I failed at this point. On the page of quickfix .Net http://quickfixn.org/tutorial/creating-an-application, it says that you simply need to replace the threadedacceptor with the socketinitiator. However, I can not pass through this initiation line.
I could use Refactor->Inine when I need to inline a method.
This the code skeleton that I tried, I used the code in this post - Is there any eclipse refactoring API that I can call programmatically?.
// 1. Get ICompiationUnit for type "smcho.Hello"
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("Hello");
project.open(null /* IProgressMonitor */);
IJavaProject javaProject = JavaCore.create(project);
IType itype = javaProject.findType("smcho.Hello");
org.eclipse.jdt.core.ICompilationUnit icu = itype.getCompilationUnit();
// 2. Contribution and Description creation
RefactoringContribution contribution = RefactoringCore.getRefactoringContribution(IJavaRefactorings.INLINE_METHOD);
InlineMethodDescriptor descriptor = (InlineMethodDescriptor) contribution.createDescriptor();
descriptor.setProject(icu.getResource().getProject().getName( ));
// 3. executing the refactoring
RefactoringStatus status = new RefactoringStatus();
try {
Refactoring refactoring = descriptor.createRefactoring(status);
IProgressMonitor monitor = new NullProgressMonitor();
refactoring.checkInitialConditions(monitor);
refactoring.checkFinalConditions(monitor);
Change change = refactoring.createChange(monitor);
change.perform(monitor);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I execute the code, I got this error
org.eclipse.core.runtime.CoreException: The refactoring script argument 'input' is missing
in the refactoring script.
I think I need to give the refactored method name to the API. What might be wrong in the code?
You never supply the method to the refactoring operation in the above code, you only give it the project context. But I don't know the necessary API for that.
If you look at this source code, you will notice the use of JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, which is probably the one you also need to set. Maybe you can search the refactoring.ui plugin sources for references to that attribute.
This is the code that works with inline refactoring JDT API.
It requires start position and length to be inlined.
int[] selection= {start, length}; // getSelection();
InlineMethodRefactoring refactoring= InlineMethodRefactoring.create(this.icu, new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(this.icu, true), selection[0], selection[1]);
refactoring.setDeleteSource(true);
refactoring.setCurrentMode(Mode.INLINE_ALL); // or INLINE SINGLE based on the user's intervention
IProgressMonitor pm= new NullProgressMonitor();
RefactoringStatus res = refactoring.checkInitialConditions(pm);
res = refactoring.checkFinalConditions(pm);
final PerformRefactoringOperation op= new PerformRefactoringOperation(
refactoring, getCheckingStyle());
op.run(new NullProgressMonitor());
When you know the name of the method that is going to be inlined, you can use the code in - Getting startPosition and length of a method invocation using JDT
I am building a Windows Workflow into a .Net webapp. The problem I have is that every time I add or remove or change an activity in the state machine and then re-compile and run it, it no longer matches up to what is in the database for tracking and persistence. Instead of updating the changes, or creating a new version of the workflow in the database it throws an error. Sometimes it an "index out of bounds" error, other times its "Cannot get the member XXXXX."
To get it to work I have to delete the database and re-build it. I believe this works because when the workflow engine looks for the workflow in the database it doesn't find it and thus adds it to the database. This is very frustrating at the stage I am at, where I am building the workflow and it changes many times in a day.
Is there a way I can simply get the workflow engine to update the relevant tables in the database with the changes I have made to the workflow? Or overwrite it with a new version? I have looked at various webpages on setting up the workflow for dynamic updating at runtime but none of these suggestions worked for me. And whilst that is a feature I would like for my workflow, I am not sure if it is really the way to solve the problem I am having. It is not so much that I am creating a new version of the workflow, rather I am building a workflow and want to test the part I have just finished/added and I don't care about previous versions of the workflow and any partially complete workflows in the database.
Thanks.
I too faced similar problem , everytime Workflow design was change, all the old workflow instances in the DB use to throw error.
To overcome this , I created Tracking profile for each type of workflow. If I changed any workflow, i updated the version of my profile. This worked for me ..Here is the sample code -
For this you need to add tracking service to workflow runtime .
TrackingProfile profile = CreateProfile();
StoreProfileToDB(profile, connString, typeof(ExceptionWF.ParameterExceptionWF),"2.0.0.0");
private static TrackingProfile CreateProfile()
{
TrackingProfile myProfile = new TrackingProfile();
ActivityTrackingLocation stateActivityLocation = CreateActivityLocation(typeof(StateActivity));
AddActivityExecutionStatus(stateActivityLocation);
ActivityTrackingLocation eventDrivenActLoc = CreateActivityLocation(typeof(EventDrivenActivity));
AddActivityExecutionStatus(eventDrivenActLoc);
ActivityTrackPoint actPt = new ActivityTrackPoint();
actPt.MatchingLocations.Add(stateActivityLocation);
actPt.MatchingLocations.Add(eventDrivenActLoc);
myProfile.ActivityTrackPoints.Add(actPt);
WorkflowTrackPoint workflowTrack = CreateWorkflowTrackPoint();
myProfile.WorkflowTrackPoints.Add(workflowTrack);
UserTrackPoint utp = new UserTrackPoint();
UserTrackingLocation ul = new UserTrackingLocation();
ul.ActivityType = typeof(HandleExternalEventActivity);
ul.ArgumentType = typeof(object);
ul.MatchDerivedArgumentTypes = true;
ul.MatchDerivedActivityTypes = true;
utp.MatchingLocations.Add(ul);
myProfile.UserTrackPoints.Add(utp);
myProfile.Version = new Version("1.0.0.0");
return myProfile;
}
private static void StoreProfileToDB(TrackingProfile profile, string connString, Type wfType,string version)
{
TrackingProfileSerializer serializer = new TrackingProfileSerializer();
System.IO.StringWriter writer = new System.IO.StringWriter(new StringBuilder());
serializer.Serialize(writer, profile);
SqlConnection conn = null;
try
{
if (!String.IsNullOrEmpty(connString))
{
conn = new SqlConnection(connString);
string storedProc = "dbo.UpdateTrackingProfile";
SqlCommand cmd = new SqlCommand(storedProc, conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("#TypeFullName", SqlDbType.NVarChar, 128);
param.Direction = ParameterDirection.Input;
param.Value = wfType.FullName;
cmd.Parameters.Add(param);
param = new SqlParameter("#AssemblyFullName", SqlDbType.NVarChar, 256);
param.Direction = ParameterDirection.Input;
param.Value = wfType.Assembly.FullName;
cmd.Parameters.Add(param);
param = new SqlParameter("#Version", SqlDbType.VarChar, 32);
param.Direction = ParameterDirection.Input;
//Note that you should increment version number for your
//TrackingProfile to be able to use new TrackingProfile.
//Default version is "1.0.0.0, It uses the default profile if not increamented.
param.Value = version;
cmd.Parameters.Add(param);
param = new SqlParameter("#TrackingProfileXml", SqlDbType.NText);
param.Direction = ParameterDirection.Input;
param.Value = writer.ToString();
cmd.Parameters.Add(param);
conn.Open();
cmd.ExecuteNonQuery();
}//if
}// try
catch (Exception ex)
{
if (ex is SqlException)
{
//Check to see if it's a version error
if (ex.Message.Substring(0, 24) == "A version already exists")
{
EventLogger.Log("A profile with the same version already exists in database");
}//if
else
{
EventLogger.Log("Error writing profile to database : " + ex.ToString());
}
}
else
{
EventLogger.Log("Error writing profile to database : " + ex.ToString());
}
}
finally
{
if (conn != null) { conn.Close(); }
}
}