ejb client in netbeans platform application module - ejb

Im trying to create a ejb Client in Netbean platform appliactaions module, to call ejb deployed in glassfish.
I have added all required jar files from my ejb server application and required glashfish jars.
appserv-rt.jar,javaee.jar, gf-client.jar.
Following code works fine when called from standalone java application , but when i try to call it from netbeans platfrom application module , Im unable to get context.
Are there any netbean platform specific configurations required?
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state",
"com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl"
);
props.setProperty("org.omg.CORBA.ORBInitialHost", "127.0.0.1");
props.setProperty("org.omg.CORBA.ORBInitialPort","3700");
InitialContext ctx = new InitialContext (props);
MySessionBeanRemote mySessionBean=
(MySessionBeanRemote)ctx
.lookup("sessions.MySessionBeanRemote");
Userprofile user = new Userprofile();
user.setActive('A');
user.setDescription("some desc");
user.setEmail("abc");
user.setFirstname("xyz");
user.setLastname("123");
user.setPassword("pwd");
user.setStatus("Enabled");
user.setUserid(Long.valueOf(25));
user.setUsername("abc");
mySessionBean.persist(user);
} catch (javax.naming.NamingException ne) {
ne.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

This is not an easy task. Have a look at the this tutorial, its a bit old but should still apply.

Related

Is Azure Function to Function authentication with MSI supported

I created 2 Azure Function Apps, both setup with Authentication/Authorization so an AD App was created for both. I would like to setup AD Auth from one Function to the other using MSI. I setup the client Function with Managed Service Identity using an ARM template. I created a simple test function to get the access token and it returns: Microsoft.Azure.Services.AppAuthentication: Token response is not in the expected format.
try {
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://myapp-registration-westus-dev.azurewebsites.net/");
log.Info($"Access Token: {accessToken}");
return req.CreateResponse(new {token = accessToken});
}
catch(Exception ex) {
log.Error("Error", ex);
throw;
}
Yes, there is a way to do this. I'll explain at a high level, and then add an item to the MSI documentation backlog to write a proper tutorial for this.
What you want to do is follow this Azure AD authentication sample, but only configure and implement the parts for the TodoListService: https://github.com/Azure-Samples/active-directory-dotnet-daemon.
The role of the TodoListDaemon will be played by a Managed Service Identity instead. So you don't need to register the TodoListDaemon app in Azure AD as instructed in the readme. Just enable MSI on your VM/App Service/Function.
In your code client side code, when you make the call to MSI (on a VM or in a Function or App Service), supply the TodoListService's AppID URI as the resource parameter. MSI will fetch a token for that audience for you.
The code in the TodoListService example will show you how to validate that token when you receive it.
So essentially, what you want to do is register an App in Azure AD, give it an AppID URI, and use that AppID URI as the resource parameter when you make the call to MSI. Then validate the token you receive at your service/receiving side.
Please check that the resource id used "https://myapp-registration-westus-dev.azurewebsites.net/" is accurate. I followed steps here to setup Azure AD authentication, and used the same code as you, and was able to get a token.
https://learn.microsoft.com/en-us/azure/app-service/app-service-mobile-how-to-configure-active-directory-authentication
You can also run this code to check the exact error returned by MSI. Do post the error if it does not help resolve the issue.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Secret", Environment.GetEnvironmentVariable("MSI_SECRET"));
var response = await client.GetAsync(String.Format("{0}/?resource={1}&api-version={2}", Environment.GetEnvironmentVariable("MSI_ENDPOINT"), "https://myapp-registration-westus-dev.azurewebsites.net/", "2017-09-01"));
string msiResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
log.Info($"MSI Response: {msiResponse}");
Update:-
This project.json file and run.csx file work for me. Note: The project.json refers to .NET 4.6, and as per Azure Functions documentation (link in comments), .NET 4.6 is the only supported version as of now. You do not need to upload the referenced assembly again. Most probably, incorrect manual upload of netstandard assembly, instead of net452 is causing your issue.
Only the .NET Framework 4.6 is supported, so make sure that your
project.json file specifies net46 as shown here. When you upload a
project.json file, the runtime gets the packages and automatically
adds references to the package assemblies. You don't need to add #r
"AssemblyName" directives. To use the types defined in the NuGet
packages, add the required using statements to your run.csx file.
project.json
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.Azure.Services.AppAuthentication": "1.0.0-preview"
}
}
}
}
run.csx
using Microsoft.Azure.Services.AppAuthentication;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
try
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net/");
log.Info($"Access Token: {accessToken}");
return req.CreateResponse(new {token = accessToken});
}
catch(Exception ex)
{
log.Error("Error", ex);
throw;
}
}

Publishing web app to Azure Websites Staging deployment slot fails with webjob

I just created a new deployment slot for my app, imported the publishing profile to Visual Studio, but after deployment I get this error message:
Error 8: An error occurred while creating the WebJob schedule: No website could be found which matches the WebSiteName [myapp__staging] and WebSiteUrl [http://myapp-staging.azurewebsites.net] supplied.
I have 2 webjobs, a continuous and a scheduled webjob.
I already signed in to the correct Azure account, as stated by this answer.
Will I need to set something else up in order to deploy my app to a staging Deployment Slot with webjobs?
My app is using ASP.NET, if it makes a difference?
There are a few quirks when using the Azure Scheduler. The recommendation is to use the new CRON support instead. You can learn more about it here and here.
Jeff,
As David suggested, you can/should migrate to the new CRON support. Here's an example. The WebJob will be deployed as a continuous WebJob.
Keep in mind that in order to use this you need to install the WebJobs package and extensions that are currently a prerelease. You can get them on Nuget.
Install-Package Microsoft.Azure.WebJobs -Pre
Install-Package Microsoft.Azure.WebJobs.Extensions -Pre
Also, as David suggested if you're not using the WebJobs SDK, you can also run this using a settings.job file. He provided an example here.
Program.cs
static void Main()
{
//Set up DI (In case you're using an IOC container)
var module = new CustomModule();
var kernel = new StandardKernel(module);
//Configure JobHost
var storageConnectionString = "your_connection_string";
var config = new JobHostConfiguration(storageConnectionString) { JobActivator = new JobActivator(kernel) };
config.UseTimers(); //Use this to use the CRON expression.
//Pass configuration to JobJost
var host = new JobHost(config);
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
Function.cs
public class Functions
{
public void YourMethodName([TimerTrigger("00:05:00")] TimerInfo timerInfo, TextWriter log)
{
//This Job runs every 5 minutes.
//Do work here.
}
}
You can change the schedule in the TimerTrigger attribute.
UPDATE Added the webjob-publish-settings.json file
Here's an example of the webjob-publiss-settings.json
{
"$schema": "http://schemastore.org/schemas/json/webjob-publish-settings.json",
"webJobName": "YourWebJobName",
"startTime": null,
"endTime": null,
"jobRecurrenceFrequency": null,
"interval": null,
"runMode": "Continuous"
}

How to specify credentials from a Java Web Service in PTC Windchill PDMLink

I am currently investigating the possibility of using a Java Web Service (as described by the Info*Engine documentation of Windchill) in order to retrieve information regarding parts. I am using Windchill version 10.1.
I have successfully deployed a web service, which I consume in a .Net application. Calls which do not try to access Windchill information complete successfully. However, when trying to retrieve part information, I get a wt.method.AuthenticationException.
Here is the code that runs within the webService (The web service method simply calls this method)
public static String GetOnePart(String partNumber) throws WTException
{
WTPart part=null;
RemoteMethodServer server = RemoteMethodServer.getDefault();
server.setUserName("theUsername");
server.setPassword("thePassword");
try {
QuerySpec qspec= new QuerySpec(WTPart.class);
qspec.appendWhere(new SearchCondition(WTPart.class,WTPart.NUMBER,SearchCondition.LIKE,partNumber),new int[]{0,1});
// This fails.
QueryResult qr=PersistenceHelper.manager.find((StatementSpec)qspec);
while(qr.hasMoreElements())
{
part=(WTPart) qr.nextElement();
partName = part.getName();
}
} catch (AuthenticationException e) {
// Exception caught here.
partName = e.toString();
}
return partName;
}
This code works in a command line application deployed on the server, but fails with a wt.method.AuthenticationException when performed from within the web service. I feel it fails because the use of RemoteMethodServer is not what I should be doing since the web service is within the MethodServer.
Anyhow, if anyone knows how to do this, it would be awesome.
A bonus question would be how to log from within the web service, and how to configure this logging.
Thank you.
You don't need to authenticate on the server side with this code
RemoteMethodServer server = RemoteMethodServer.getDefault();
server.setUserName("theUsername");
server.setPassword("thePassword");
If you have followed the documentation (windchill help center), your web service should be something annotated with #WebServices and #WebMethod(operationName="getOnePart") and inherit com.ptc.jws.servlet.JaxWsService
Also you have to take care to the policy used during deployment.
The default ant script is configured with
security.policy=userNameAuthSymmetricKeys
So you need to manage it when you consume your ws with .Net.
For logging events, you just need to call the log4j logger instantiated by default with $log.debug("Hello")
You can't pre-authenticate server side.
You can write the auth into your client tho. Not sure what the .Net equivilent is, but this works for Java clients:
private static final String USERNAME = "admin";
private static final String PASSWORD = "password";
static {
java.net.Authenticator.setDefault(new java.net.Authenticator() {
#Override
protected java.net.PasswordAuthentication getPasswordAuthentication() {
return new java.net.PasswordAuthentication(USERNAME, PASSWORD.toCharArray());
}
});
}

Red5: Server application skeleton and helloworld

Can anyone provide an updated application skeleton for a Red5 application? From what I have found the logging system changed from Log4j. I've been looking for some tutorials just to setup everything but can't really find something that simply works.
In addiction, can anyone provide a simple tutorial with a server application and Flex client?
Thanks in advance!
I struggled a lot with that.. This reference worked for me:
http://fossies.org/unix/privat/red5-1.0.0-RC2.tar.gz:a/red5-1.0.0/doc/reference/html/logging-setup.html
The trick was to Remove any log4j.properties or log4j.xml files and Remove any "log4j" listeners from the web.xml
Create a logback-myApp.xml where myApp is the name for your webapp and place it on your webapp classpath (WEB-INF/classes or in your application jar within WEB-INF/lib)
and im my app i did:
import org.slf4j.Logger;
import org.red5.logging.Red5LoggerFactory;
and then:
private static Logger log = Red5LoggerFactory.getLogger(MyClassName.class, "myApp");
the clients actionscript looks like this:
// Initializiing Connection
private function initConnection():void{
nc = new NetConnection();
nc.client = new NetConnectionClient();
nc.objectEncoding = flash.net.ObjectEncoding.AMF0;
nc.connect(rtmpPath.text,true); //Path to FMS Server e.g. rtmp://<hostname>/<application name>
nc.addEventListener("netStatus", publishStream); //Listener to see if connection is successful
}
private function publishStream(event:NetStatusEvent):void{
if(nc.connected){
nsPublish = new NetStream(nc); //Initializing NetStream
nsPublish.attachCamera(Camera.getCamera());
nsPublish.attachAudio(Microphone.getMicrophone()); //Attaching Camera & Microphone
nsPublish.publish(streamName.text,'live'); //Publish stream
mx.controls.Alert.show("Published");
}
else{
mx.controls.Alert.show("Connection Error");
}
}

Silverlight error while calling a service

I am trying to call a service from a silverlight application, but I am getting the following error.
Uncaught Error: Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid. Check InnerException for exception details.
This works fine locally. I don't know if it make any sense, but locally if I add the url of the webservice on a browser, I am getting the details page of the service. In the other hand, on production server, it prompts me to download it.
Does anyone know something about this?
Thanks
public MainPage() {
InitializeComponent();
Loaded += new System.Windows.RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e) {
var newsFeedWcfClient = new NewsFeedWCFClient();
newsFeedWcfClient.GetNewsFeedItemsCompleted += newsFeedWcfClient_GetNewsFeedItemsCompleted;
newsFeedWcfClient.GetNewsFeedItemsAsync();
}
void newsFeedWcfClient_GetNewsFeedItemsCompleted(object sender, GetNewsFeedItemsCompletedEventArgs e) {
var source = (IList<NewsFeed>)e.Result;
IList<CustomNewsFeed> customNewsFeeds = new List<CustomNewsFeed>();
foreach (var item in source) {
customNewsFeeds.Add(new CustomNewsFeed() {
ProductID = item.Products.ProductID,
ProductTitle = item.Products.Title,
Status = item.Text,
Thumb = string.Format("{0}/{1}", item.Products.Product_Photos.Select(pp => pp.PhotoPath).FirstOrDefault(), item.Products.Product_Photos.Select(pp => pp.PhotoName).FirstOrDefault()),
UserID = item.User.Id,
UserName = item.User.Username
});
}
NewsFeedLB.ItemsSource = customNewsFeeds;
}
The fact that on the production server it "prompts you to download" would suggest that the production web server doesn't know what to do with your .svc or .asmx file. It is treating it like a normal file (.txt, .pdf etc).
Have you got all of the required items installed in production. For instance, you need the correct .NET runtime to be installed. Also, ASP.NET needs to be installed and then enabled.
To determine exactly what is happening I would recommend installing Fiddler and using it to trace what is happening when the Silverlight app calls the server. I have found this approach to be invaluable when troubleshooting Silverlight to Web Service communication problems.

Resources