How to programmatically get provisioning resources with oim 11g client api - oracle

I'm using the oracle OIM 11g api (in packages oracle.iam). I use the class oracle.iam.platform.OIMClient to get all the OIM client services like UserManager.
I need to find the resources got with the provisioning workflows. Which service can I use? How can I do with the OIM api?

The method below should export all resources into an XML file-
public Boolean export() {
Boolean result = true;
String export_object="Resource";
try {
FileWriter fstream = new FileWriter("OIMResources.xml");
BufferedWriter out = new BufferedWriter(fstream);
tcExportOperationsIntf moExportUtility = (tcExportOperationsIntf) ioUtilityFactory.getUtility("Thor.API.Operations.tcExportOperationsIntf");
Collection<RootObject> lstObjects = moExportUtility.findObjects(export_object, "*");
System.out.println(lstObjects);
lstObjects.addAll(moExportUtility.getDependencies(lstObjects));
lstObjects.addAll(moExportUtility.retrieveChildren(lstObjects));
lstObjects.addAll(moExportUtility.retrieveDependencyTree(lstObjects));
String s = moExportUtility.getExportXML(lstObjects, "*");
out.write(s);
LOG.info(Resource + "Objects successfully exported");
out.close();
} catch (Exception e) {
LOG.log(Level.SEVERE, "Exception occured while exporting OIM object" + Resource, e);
}
return result;
}

Related

Is there a way to batch upload a collection of InputStreams to Amazon S3 using the Java SDK?

I am aware of the TransferManager and the .uploadFileList() and .uploadFileDirectory() methods, however they accept java.io.File types as arguments. I have a collection of byte array input streams containing jpeg image data. I don't want to create in-memory files to store this data before I upload it either.
So what I need is essentially what the S3 client's PutObjectRequest does but for a collection of InputStream objects. Also, if one upload fails, I want to abort the whole thing and not upload anything, much like how a database transaction will reverse the changes if something goes wrong along the way.
Is this possible with the Java SDK?
Before I share an answer, please consider upgrading...
fyi - TransferManager is deprecated, now supported as TransferManagerBuilder in JAVA AWS SDK, please consider upgrading if TransferManagerBuilder Object suits your needs.
now since you asked about TransferManager, you could either 1) copy the code below and replace the functionality/arguments with your custom in memory handling of the input stream and handle it in your custom function... or; 2) further below is another sample, try to use this as-is...
Github source modify with with inputstream and issue listed here
private def uploadFile(is: InputStream, s3ObjectName: String, metadata: ObjectMetadata) = {
try {
val putObjectRequest = new PutObjectRequest(bucketName, s3ObjectName,
is, metadata)
// TransferManager supports asynchronous uploads and downloads
val upload = transferManager.upload(putObjectRequest)
upload.addProgressListener(ExceptionReporter.wrap(UploadProgressListener(putObjectRequest)))
} catch {
case e: Exception => throw new RuntimeException(e)
}
}
Bonus, Nice custom answer here using sequence input streams
public void combineFiles() {
List<String> files = getFiles();
long totalFileSize = files.stream()
.map(this::getContentLength)
.reduce(0L, (f, s) -> f + s);
try {
try (InputStream partialFile = new SequenceInputStream(getInputStreamEnumeration(files))) {
ObjectMetadata resultFileMetadata = new ObjectMetadata();
resultFileMetadata.setContentLength(totalFileSize);
s3Client.putObject("bucketName", "resultFilePath", partialFile, resultFileMetadata);
}
} catch (IOException e) {
LOG.error("An error occurred while combining files. {}", e);
}
}
private Enumeration<? extends InputStream> getInputStreamEnumeration(List<String> files) {
return new Enumeration<InputStream>() {
private Iterator<String> fileNamesIterator = files.iterator();
#Override
public boolean hasMoreElements() {
return fileNamesIterator.hasNext();
}
#Override
public InputStream nextElement() {
try {
return new FileInputStream(Paths.get(fileNamesIterator.next()).toFile());
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
throw new RuntimeException(e);
}
}
};
}

ArcGIS version 100.3.0 android token

Below is the code I'm using for setting user credentials on ServiceFeatureTable.
ServiceFeatureTable featureTablePolygons = new ServiceFeatureTable(polygonUrl);
featureTablePolygons.setCredential(UserCredential.createFromToken(gisToken, referer));
//query feature from the table
final ListenableFuture<FeatureQueryResult> queryResultPolygons = featureTablePolygons.queryFeaturesAsync(query);
queryResultPolygons.addDoneListener(() -> {
try {
FeatureCollection featureCollection = new FeatureCollection();
FeatureQueryResult result = queryResultPolygons.get();
FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);
featureCollectionTable.setRenderer(new SimpleRenderer(new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.translucent_red), new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 1))));
featureCollection.getTables().add(featureCollectionTable);
FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);
mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);
if (result.iterator().hasNext()) {
Feature feature = result.iterator().next();
Envelope envelope = feature.getGeometry().getExtent();
mMapView.setViewpointGeometryAsync(envelope);
} else {
}
} catch (InterruptedException | ExecutionException e) {
Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
}
});
But this is not working. If I'm using AuthenticationManager then it's working fine but I don't want to use username and password in my code.
If you're manually getting the token, you can create a UserCredential object using createFromToken() and set it on the ServiceFeatureTable with setCredential().
However, many workflows for getting a token are handled by the Runtime (e.g. username + password, or OAuth via a Portal). Take a look at the AuthenticationManager documentation to get started.
Lastly, I think you'll get more eyes on your questions over at the ArcGIS Runtime SDK for Android forums.

Using JAX-RS and trying to DELETE an item

I am currently working in Enterprise Java and I'm a newbie. I am trying to create a method which should delete a selected item from a data table. My project contains Graphical User Interface elements from "http://www.primefaces.org/showcase/".
The deletion is made through a web-service.
This is the method I created so far:
public boolean delete(String articleId) {
Client client = ClientBuilder.newClient();
WebTarget target
= client.target(DELETE_URL);//this is a String
//TODO call ws method delete
try{
target.request()....;
} catch(Exception ex) {
LOGGER.error("Delete Article Error ", ex);
}
return true;
}
Could you tell me how can I handle the deletion in an appropiate way?
All the best!
In your case the following should do the trick.
target.request().delete(Response.class)

Elmah doesn't log exceptions using WebAPI with HttpResponseException

In my WebApi code, I raise a HttpResponseException which short-circuits the request pipeline and generates a valid Http response. However, I'm trying to integrate webApi with elmah logging, yet the HttpResponseExeptions aren't showing up.
I have the web.config set-up for elmah and have the following code:
In Global.asx.cs:
static void ConfigureWebApi(HttpConfiguration config)
{
config.Filters.Add(new ServiceLayerExceptionFilter());
config.Filters.Add(new ElmahHandledErrorLoggerFilter());
config.DependencyResolver = new WebApiDependencyResolver(ObjectFactory.Container);
}
Filter:
public class ElmahHandledErrorLoggerFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
base.OnException(actionExecutedContext);
ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
}
}
Code where exception is raised:
public Task<FileUpModel> UploadFile()
{
if (Request.Content.IsMimeMultipartContent())
{
var provider = new TolMobileFormDataStreamProvider("C:\images\");
var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(
t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var fileInfo = provider.FileData.FirstOrDefault();
if (fileInfo == null)
// the exception here isn't logged by Elmah?!
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var uploadModel = new FileUpModel { success = true };
return uploadModel;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
Can anyone who has implemented this before let me know what I'm doing wrong?
As mentioned above, the Elmah filter does not catch and log anything when you raise a HttpResponseException. More specifically, if the following syntax is used:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "It was a bad request");
or
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "HttpResponseException - This request is not properly formatted"));
I wanted to trap and log an error in both cases. The way to do it is to use an "ActionFilterAttribute", override "OnActionExecuted", and check actionExecutedContext.Response.IsSuccessStatusCode.
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// when actionExecutedContext.Response is null, the error will be caught and logged by the Elmah filter
if ((actionExecutedContext.Response != null) && !actionExecutedContext.Response.IsSuccessStatusCode)
{
try
{
var messages = (System.Web.Http.HttpError)((System.Net.Http.ObjectContent<System.Web.Http.HttpError>)actionExecutedContext.Response.Content).Value;
StringBuilder stringBuilder = new StringBuilder();
foreach (var keyValuePair in messages) {
stringBuilder.AppendLine("Message: Key - " + keyValuePair.Key + ", Value - " + keyValuePair.Value);
}
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Web API Failed Status Code returned - " + stringBuilder.ToString()));
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Error in OnActionExecuted - " + ex.ToString()));
}
}
}
On a side note, I also overwrote "OnActionExecuting" to validate the model state. This allowed me to remove all of the checks within my actions.
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.ModelState != null && !actionContext.ModelState.IsValid)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var obj in actionContext.ModelState.Values)
{
foreach (var error in obj.Errors)
{
if(!string.IsNullOrEmpty(error.ErrorMessage)) {
stringBuilder.AppendLine("Error: " + error.ErrorMessage);
}
}
}
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Invalid Model State -- " + stringBuilder.ToString()));
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
Of course, you will need to add the filter using "config.Filters.Add".
Web API special cases HttpResponseException thrown in action and converts into HttpResponseMessage and hence you are not seeing your exception filter getting invoked.
This is not true in the case of throwing HttpResponseException from filters. However, ideally one need not throw HttpResponseException from filters as you could short-circuit a request by setting the Response property on the supplied input context.
You need to turn on Elmah for HttpFilters in order to get this to work as you expect for WebApi.
Use Elmah.Contrib.WebApi available as a NuGet Package, it will wire include a class that you can then wire up following the instructions on the Elmah.Contrib.WebApi project site.
If you want to do this yourself, Capturing Unhandled Exceptions in ASP.NET Web API's with ELMAH walks you through what the Elmah.Contrib.WebApi is doing for you.
Additionally, I had to change the way that the error response is thrown for it to be picked by Elmah to:
throw new HttpException((int)HttpStatusCode.NotAcceptable, "This request is not properly formatted");
I would also recommend the use of the Elmah.MVC NuGet Package.

How to send email with attachments

I want to send an email with an image attached with it. I am using spring 3 with velocity templates. I am able to do that but for some reasons when I add an extension with the image name I don't get the email delivered.
Following is the code I am using for it:
private MimeMessage createEmail(Application application, String templatePath, String subject, String toEmail, String fromEmail, String fromName) {
MimeMessage mimeMsg = mailSender.createMimeMessage();
Map<String, Object> model = new HashMap<String, Object>();
model.put("application", application);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templatePath, model);
text = text.replaceAll("\n", "<br>");
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
helper.setSubject(subject);
helper.setTo(toEmail);
if (fromName == null) {
helper.setFrom(fromEmail);
} else {
try {
helper.setFrom(fromEmail, fromName);
} catch (UnsupportedEncodingException e) {
helper.setFrom(fromEmail);
}
}
helper.setSentDate(application.getDateCreated());
helper.setText(text, true);
InputStream inputStream = servletContext.getResourceAsStream("images/formstack1.jpg");
helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));
} catch (MessagingException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return mimeMsg;
}
Using the code above I could add formstack1 as attachment but it has no extension so I don't get the formstack1.jpg image file. But when I use formstack1.jpg for the name of resource to be attached in helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); as formstack1 changed to formstack1.jpg I don't get even the email delivered. I am using smtp.gmail.com and 25 for port. I do get the email sent successfully message on the console though. But the email
is never delivered.
EDIT: If I keep it like helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); and change the extension from nothing to .jpg while downloading the attached image I do get the desired image.
Could someone help me understand why is it happening and how send email with 1 or more attachments using spring 3.
Thanks.
You should better use Apache Commons HtmlEMail
http://commons.apache.org/email/userguide.html

Resources