Can't populate components field in JIRA using ComponentRestClient in Java - java

I've been trying different ways to populate components field while creating JIRA using JiraRestClient in java and somehow not able to do that.
Following is one of the approaches I tried -
public String createIssue(String projectKey, Long issueType, String issueSummary, String description) throws URISyntaxException {
IssueRestClient issueClient = restClient.getIssueClient();
ComponentRestClient componentClient = restClient.getComponentClient();
String componentUrl = "https://jira.abc.com/issues/?jql=project+%3D+PROJECTKEY+AND+component+%3D+%22Comp+Name%22";
Component component = componentClient.getComponent(new URI(componentUrl.trim())).claim();
//BasicComponent bc = new BasicComponent();
IssueInput newIssue = new IssueInputBuilder(projectKey, issueType, issueSummary)
.setDescription(description).setComponents(component).build();
return issueClient.createIssue(newIssue).claim().getKey();
}
With this I get error while JSON parsing step -
at org.codehaus.jettison.json.JSONTokener.syntaxError(JSONTokener.java:439) ~[jettison-1.1.jar:1.1]
at org.codehaus.jettison.json.JSONObject.<init>(JSONObject.java:169) ~[jettison-1.1.jar:1.1]
at org.codehaus.jettison.json.JSONObject.<init>(JSONObject.java:266) ~[jettison-1.1.jar:1.1]
at com.atlassian.jira.rest.client.internal.async.AbstractAsynchronousRestClient$1.handle(AbstractAsynchronousRestClient.java:147) ~[jira-rest-java-client-core-4.0.0.jar:?]
at com.atlassian.jira.rest.client.internal.async.AbstractAsynchronousRestClient$3.apply(AbstractAsynchronousRestClient.java:189) ~[jira-rest-java-client-core-4.0.0.jar:?]
at com.atlassian.jira.rest.client.internal.async.AbstractAsynchronousRestClient$3.apply(AbstractAsynchronousRestClient.java:185) ~[jira-rest-java-client-core-4.0.0.jar:?]
at com.atlassian.httpclient.api.ResponsePromiseMapFunction.apply(ResponsePromiseMapFunction.java:81) ~[atlassian-httpclient-api-0.23.0.jar:?]
at com.atlassian.httpclient.api.ResponsePromiseMapFunction.apply(ResponsePromiseMapFunction.java:11) ~[atlassian-httpclient-api-0.23.0.jar:?]
at com.atlassian.util.concurrent.Promises$Of$3.apply(Promises.java:268) ~[atlassian-util-concurrent-2.4.2.jar:?]
at com.atlassian.util.concurrent.Promises$2.onSuccess(Promises.java:158) ~[atlassian-util-concurrent-2.4.2.jar:?]
at com.google.common.util.concurrent.Futures$4.run(Futures.java:1132) ~[guava-20.0.jar:?]
at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:435) ~[guava-20.0.jar:?]
at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:900) ~[guava-20.0.jar:?]
Any help or suggestions will be highly appreciated!

This should work:
IssueInputBuilder builder = new IssueInputBuilder( projectKey, issueType, issueSummary );
Iterable<BasicComponent> components = restClient
.getProject( projectKey )
.getComponents( );
for ( BasicComponent c : components ) {
if ( c.getName().equals( "your component name" ) ) {
builder.setComponents( c ); // assuming you want only one component
}
}
IssueInput newIssue = builder.setDescription(description).build(); // etc...

Related

Soap Request using axis2 java in Eclipse

I want to make an insert operation in an import set table through the web service from ServiceNow with axis2 version 1.6.4
I used wsdl2java with the wsdl file to create classes in my java project.
After it, i created a new class Request on which i would build my soap request to the webservice.
I believe I have 2 (might be more) major problems:
Unserstanding the difference between a stub and a proxy, respectively, the classes ServiceNowSoapStub and ServiceNowSoapProxy and what is the purpose of each of them.
The existing insert method needs a lot of arguments and i wish to make inserts with a selected number of arguments. do i need to add that specific insert method to the architecture?
Here is what I have:
public class Request {
public static void main(String[] args) throws RemoteException {
try{
HttpTransportProperties.Authenticator basicAuthentication = new HttpTransportProperties.Authenticator();
basicAuthentication.setUsername("xxxx");
basicAuthentication.setPassword("xxxx");
ServiceNowSoapStub proxy = new ServiceNowSoapStub();
proxy._setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
proxy._setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, basicAuthentication);
BigDecimal actuals = new BigDecimal("0.04");
BigInteger appId = new BigInteger("3495766");
String appNonApp = "ApNon";
BigInteger productId = new BigInteger("704217");
BigInteger serviceId = new BigInteger("1537");
String serviceName = "IT";
String bpName = "BNK-RSK";
String method = "N";
String bsCode = "ITDV";
String customerCostCode = "30973250";
String customerCountry = "US";
String customerGroup = "Wealth";
String customerLegalEntity = "HB";
String dsId = "EU56";
BigInteger supplierCostCode = new BigInteger("675136");
String supplierCountry = "UK";
String supplierLegalEntity = "BR";
BigInteger total = new BigInteger ("411");
ServiceNowSoapProxy request = new ServiceNowSoapProxy("https://dev34363.service-now.com/u_it_actuals_import_set");
request.insertTest(actuals, appId, appNonApp, productId, serviceId, serviceName, bpName, method, bsCode, customerCostCode,
customerCountry, customerGroup, customerLegalEntity, dsId, supplierCostCode, supplierCountry, supplierLegalEntity, total);
} catch (org.apache.axis.AxisFault e) {
e.printStackTrace();
}
}
}
What am I doing wrong? or can please anyone refer me to some helpful link?
The wiki page of servicenow addressing this subject is a bit out of date so i can't solve my problem through it.
Thanks!

Using AWS Java's SDKs, how can I terminate the CloudFormation stack of the current instance?

Uses on-line decomentation I come up with the following code to terminate the current EC2 Instance:
public class Ec2Utility {
static private final String LOCAL_META_DATA_ENDPOINT = "http://169.254.169.254/latest/meta-data/";
static private final String LOCAL_INSTANCE_ID_SERVICE = "instance-id";
static public void terminateMe() throws Exception {
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest().withInstanceIds(getInstanceId());
AmazonEC2 ec2 = new AmazonEC2Client();
ec2.terminateInstances(terminateRequest);
}
static public String getInstanceId() throws Exception {
//SimpleRestClient, is an internal wrapper on http client.
SimpleRestClient client = new SimpleRestClient(LOCAL_META_DATA_ENDPOINT);
HttpResponse response = client.makeRequest(METHOD.GET, LOCAL_INSTANCE_ID_SERVICE);
return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
}
}
My issue is that my EC2 instance is under an AutoScalingGroup which is under a CloudFormationStack, that is because of my organisation deployment standards though this single EC2 is all there is there for this feature.
So, I want to terminate the entire CloudFormationStack from the JavaSDK, keep in mind, I don't have the CloudFormation Stack Name in advance as I didn't have the EC2 Instance Id so I will have to get it from the code using the API calls.
How can I do that, if I can do it?
you should be able to use the deleteStack method from cloud formation sdk
DeleteStackRequest request = new DeleteStackRequest();
request.setStackName(<stack_name_to_be_deleted>);
AmazonCloudFormationClient client = new AmazonCloudFormationClient (<credentials>);
client.deleteStack(request);
If you don't have the stack name, you should be able to retrieve from the Tag of your instance
DescribeInstancesRequest request =new DescribeInstancesRequest();
request.setInstanceIds(instancesList);
DescribeInstancesResult disresult = ec2.describeInstances(request);
List <Reservation> list = disresult.getReservations();
for (Reservation res:list){
List <Instance> instancelist = res.getInstances();
for (Instance instance:instancelist){
List <Tag> tags = instance.getTags();
for (Tag tag:tags){
if (tag.getKey().equals("aws:cloudformation:stack-name")) {
tag.getValue(); // name of the stack
}
}
At the end I've achieved the desired behaviour using the set of the following util functions I wrote:
/**
* Delete the CloudFormationStack with the given name.
*
* #param stackName
* #throws Exception
*/
static public void deleteCloudFormationStack(String stackName) throws Exception {
AmazonCloudFormationClient client = new AmazonCloudFormationClient();
DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName("");
client.deleteStack(deleteStackRequest);
}
static public String getCloudFormationStackName() throws Exception {
AmazonEC2 ec2 = new AmazonEC2Client();
String instanceId = getInstanceId();
List<Tag> tags = getEc2Tags(ec2, instanceId);
for (Tag t : tags) {
if (t.getKey().equalsIgnoreCase(TAG_KEY_STACK_NAME)) {
return t.getValue();
}
}
throw new Exception("Couldn't find stack name for instanceId:" + instanceId);
}
static private List<Tag> getEc2Tags(AmazonEC2 ec2, String instanceId) throws Exception {
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
DescribeInstancesResult describeInstances = ec2.describeInstances(describeInstancesRequest);
List<Reservation> reservations = describeInstances.getReservations();
if (reservations.isEmpty()) {
throw new Exception("DescribeInstances didn't returned reservation for instanceId:" + instanceId);
}
List<Instance> instances = reservations.get(0).getInstances();
if (instances.isEmpty()) {
throw new Exception("DescribeInstances didn't returned instance for instanceId:" + instanceId);
}
return instances.get(0).getTags();
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// Example of usage from the code:
deleteCloudFormationStack(getCloudFormationStackName());
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

ExtGWT StoreFilterField input doesn't react

I'm trying to build grid with build in column filtering (using sencha gxt), here is my code:
public Grid<Stock> createGrid() {
// Columns definition
ColumnConfig<Stock, String> nameCol = new ColumnConfig<Stock, String>(props.name(), 100, "Company");
// Column model definition and creation
List<ColumnConfig<Stock, ?>> cl = new ArrayList<ColumnConfig<Stock, ?>>();
cl.add(nameCol);
ColumnModel<Stock> cm = new ColumnModel<Stock>(cl);
// Data populating
ListStore<Stock> store = new ListStore<Stock>(props.key());
store.addAll(TestData.getStocks());
// Grid creation with data
final Grid<Stock> grid = new Grid<Stock>(store, cm);
grid.getView().setAutoExpandColumn(nameCol);
grid.setBorders(false);
grid.getView().setStripeRows(true);
grid.getView().setColumnLines(true);
// Filters definition
StoreFilterField<Stock> filter = new StoreFilterField<Stock>() {
#Override
protected boolean doSelect(Store<Stock> store, Stock parent, Stock item, String filter) {
// Window.alert(String.valueOf("a"));
String name = item.getName();
name = name.toLowerCase();
if (name.startsWith(filter.toLowerCase())) {
return true;
}
return false;
}
};
filter.bind(store);
cm.addHeaderGroup(0, 0, new HeaderGroupConfig(filter, 1, 1));
filter.focus();
return grid;
}
My problem is: after I run this code, I cannot write anything to filter input, I'm using test data and classes (Stock.java and StockProperties.java) from this example: http://sencha.com/examples-dev/#ExamplePlace:filtergrid
I try to put allert in doSelect method to check if this function was called, but it wasn't.
Any idea will be welcome. Thanks.
I was able to make your code work. I observed that there were compiler errors in the code for StoreFilterField class. Here is the code that filters the grid based on the values in the first column, that is, name field in the Stock model.
StoreFilterField<Stock> filter1 = new StoreFilterField<Stock>() {
#Override
protected boolean doSelect(Store<Stock> store, Stock parent, Stock record, String property, String filter) {
String name = record.get("name");
name = name.toLowerCase();
if (name.startsWith(filter.toLowerCase())) {
return true;
}
return false;
}
};
filter1.bind(store);
Btw, I tested this with GXT 2.2.5 and GWT 2.4.
Thanks,
Ganesh
I solve this problem according to this paper http://www.sencha.com/forum/archive/index.php/ … but I replace disableTextSelection(false) with setAllowTextSelection(true);

Using a CustomExpression in a DynamicJasper chart

I have a project using DynamicJasper to create reports. It works fine so far, but when I wanted to add a chart to a previously functional report I run into issues.
I keep getting this:
net.sf.jasperreports.engine.design.JRValidationException: Report design not valid :
1. Field not found : customExpression_for_Ganancia
at net.sf.jasperreports.engine.design.JRAbstractCompiler.verifyDesign(JRAbstractCompiler.java:258)
at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:140)
at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:215)
at ar.com.fdvs.dj.core.DynamicJasperHelper.generateJasperReport(DynamicJasperHelper.java:519)
at ar.com.fdvs.dj.core.DynamicJasperHelper.generateJasperPrint(DynamicJasperHelper.java:279)
at ar.com.fdvs.dj.core.DynamicJasperHelper.generateJasperPrint(DynamicJasperHelper.java:232)
Ganancia being the only column in the chart that is a CustomExpression. If I don't add this column as a series to the chart, the chart renders properly. It seems the chart doesn't play well with expressions...
A snippet from my code:
private DynamicReport buildSalesReport() throws ColumnBuilderException, ClassNotFoundException, ChartBuilderException {
DynamicReportBuilder drb = new DynamicReportBuilder();
drb.setReportName("Reporte de Ventas")
.setTitle("Reporte de ventas")
.setSubtitle("Este reporte fue generado el " + new Date())
.setPrintColumnNames(false)
.setIgnorePagination(true)
.setMargins(10, 10, 10, 10)
.setUseFullPageWidth(true);
Style groupOneStyle = new Style();
groupOneStyle.setFont(Font.ARIAL_BIG);
groupOneStyle.setHorizontalAlign(HorizontalAlign.LEFT);
groupOneStyle.setVerticalAlign(VerticalAlign.MIDDLE);
AbstractColumn columnDisplayName = ColumnBuilder.getNew()
.setColumnProperty("bookingType.displayName", String.class.getName())
.setTitle("Tipo").setWidth(new Integer(40))
.setStyle(groupOneStyle)
.build();
AbstractColumn columnDestiny = ColumnBuilder.getNew()
.setColumnProperty("bookedObject.destiny", String.class.getName())
.setTitle("Destino").setWidth(new Integer(40))
.build();
Style priceStyle = new Style();
priceStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
AbstractColumn columnCurrency = ColumnBuilder.getNew()
.setColumnProperty("bookedObject.currency.displayName", String.class.getName())
.setTitle("Cotizacion").setWidth(new Integer(5))
.setShowText(false)
.build();
Style footerStyle = new Style();
footerStyle.setFont(Font.ARIAL_MEDIUM);
footerStyle.setBorderTop(Border.THIN);
footerStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
footerStyle.setVerticalAlign(VerticalAlign.MIDDLE);
AbstractColumn columnPrice = ColumnBuilder.getNew()
.setColumnProperty("bookedObject.price", Double.class.getName())
.setStyle(priceStyle)
.setPattern("$ 0.00")
.setTitle("Precio").setWidth(new Integer(25))
.build();
AbstractColumn columnCount = ColumnBuilder.getNew()
.setColumnProperty("count", Integer.class.getName())
.setStyle(priceStyle)
.setTitle("Cantidad").setWidth(new Integer(25))
.build();
columnCount.setName("Cantidad");
AbstractColumn columnProfit = ColumnBuilder.getNew()
.setCustomExpression(this.getProfitExpression())
.setStyle(priceStyle)
.setTitle("Ganancia").setWidth(new Integer(20))
.setPattern("$ 0.00")
.build();
columnProfit.setName("Ganancia");
GroupBuilder groupBookingTypeBuilder = new GroupBuilder();
DJGroup groupBookingType =
groupBookingTypeBuilder.setCriteriaColumn((PropertyColumn) columnDisplayName)
.setGroupLayout(GroupLayout.VALUE_IN_HEADER_WITH_HEADERS_AND_COLUMN_NAME)
.build();
GroupBuilder groupCurrencyBuilder = new GroupBuilder();
DJGroup groupCurrency =
groupCurrencyBuilder.setCriteriaColumn((PropertyColumn) columnCurrency)
.addFooterVariable(columnCount,DJCalculation.SUM,footerStyle)
.addFooterVariable(columnProfit,DJCalculation.SUM,footerStyle)
.setGroupLayout(GroupLayout.VALUE_IN_HEADER)
.build();
drb.addColumn(columnDisplayName)
.addColumn(columnCurrency)
.addColumn(columnDestiny)
.addColumn(columnCount)
.addColumn(columnPrice)
.addColumn(columnProfit)
.addGroup(groupBookingType)
.addGroup(groupCurrency)
.setPrintBackgroundOnOddRows(true);
DJAxisFormat categoryAxisFormat = new DJAxisFormat("Destino");
categoryAxisFormat.setLabelFont(Font.ARIAL_SMALL);
categoryAxisFormat.setLabelColor(Color.DARK_GRAY);
categoryAxisFormat.setTickLabelFont(Font.ARIAL_SMALL);
categoryAxisFormat.setTickLabelColor(Color.DARK_GRAY);
categoryAxisFormat.setTickLabelMask("");
categoryAxisFormat.setLineColor(Color.DARK_GRAY);
DJAxisFormat valueAxisFormat = new DJAxisFormat("Ventas / Ingresos");
valueAxisFormat.setLabelFont(Font.ARIAL_SMALL);
valueAxisFormat.setLabelColor(Color.DARK_GRAY);
valueAxisFormat.setTickLabelFont(Font.ARIAL_SMALL);
valueAxisFormat.setTickLabelColor(Color.DARK_GRAY);
valueAxisFormat.setTickLabelMask("#,##0");
valueAxisFormat.setLineColor(Color.DARK_GRAY);
DJChart djChart = new DJBarChartBuilder()
//chart
.setX(20)
.setY(10)
.setWidth(500)
.setHeight(250)
.setCentered(false)
.setBackColor(Color.LIGHT_GRAY)
.setShowLegend(true)
.setPosition(DJChartOptions.POSITION_FOOTER)
.setTitle(new StringExpression() {
#Override
public Object evaluate(Map fields, Map variables, Map parameters) {
return variables.get("bookingType.displayName");
}
})
.setTitleColor(Color.DARK_GRAY)
.setTitleFont(Font.ARIAL_BIG_BOLD)
.setSubtitle("subtitle")
.setSubtitleColor(Color.DARK_GRAY)
.setSubtitleFont(Font.COURIER_NEW_BIG_BOLD)
.setLegendColor(Color.DARK_GRAY)
.setLegendFont(Font.COURIER_NEW_MEDIUM_BOLD)
.setLegendBackgroundColor(Color.WHITE)
.setLegendPosition(DJChartOptions.EDGE_BOTTOM)
.setTitlePosition(DJChartOptions.EDGE_TOP)
.setLineStyle(DJChartOptions.LINE_STYLE_DOTTED)
.setLineWidth(1)
.setLineColor(Color.DARK_GRAY)
.setPadding(5)
//dataset
.setCategory((PropertyColumn) columnDestiny)
.addSerie(columnCount, "Cantidad")
.addSerie(columnProfit, "Ganancia") // IF I COMMENT THIS LINE THE CHART IS RENDERED
//plot
.setCategoryAxisFormat(categoryAxisFormat)
.setValueAxisFormat(valueAxisFormat)
.build();
drb.addChart(djChart);
HashMap vars = new HashMap();
vars.put(columnCount, new JRDesignVariable());
vars.put(columnProfit, new JRDesignVariable());
JRDesignGroup group = new JRDesignGroup();
djChart.transform(new DynamicJasperDesign(), "", group, group, vars, 0);
DynamicReport dr = drb.build();
return dr;
}
public JasperPrint getJasperPrint(String status, String userOwner,
String hourFrom, String hourTo, String dateFrom, String dateTo)
throws ColumnBuilderException, ClassNotFoundException, JRException, ChartBuilderException {
DynamicReport dr = this.buildSalesReport();
JRDataSource ds = new JRBeanCollectionDataSource(
this.bookService.getReportBooks(status, userOwner, hourFrom, hourTo, dateFrom, dateTo));
return DynamicJasperHelper.generateJasperPrint(dr , new ClassicLayoutManager(), ds);
}
/**
*
* #return
*/
#SuppressWarnings("serial")
private CustomExpression getProfitExpression() {
return new CustomExpression() {
#SuppressWarnings("rawtypes")
#Override
public Object evaluate(Map fields, Map variables, Map parameters) {
Double amount = (Integer)fields.get("count") * (Double)fields.get("bookedObject.price");
return amount;
}
#Override
public String getClassName() {
return Double.class.getName();
}
};
As I said, the report is shown properly without the chart, with the chart, it fails only if the expression column is included as a series.
Any ideas are welcomed!
Just pushed the change for DJ 4.0.1 in commit 05243a3
Sometime today will also push for DJ 3.X
I've solved this very same problem doing the following:
Set the "fieldDescription" of your column.
Re-write the Method "protected Map registerChartVariable(ar.com.fdvs.dj.domain.chart.DJChart chart)" of class AbstractLayoutManager":
JRDesignExpression expression = new JRDesignExpression();
String property = ((PropertyColumn) col).getFieldDescription();
// ((PropertyColumn) col).getColumnProperty().getProperty();
expression.setText("$F{" + property + "}");
expression.setValueClass(clazz);
3 . As you have already figured out, you'll have to create your own LayoutManager for this task.
4 . This may not be the best solution, it is just an example how to fill the gap of DynamicJasper.
I ran into the same problem, but I had a slightly different solution. There are different types of Column classes, but only the PropertyColumn class is supported in the AbstractLayoutManager for charts. I found out that when you use a CustomExpression, the underlying Column class that is used is an ExpressionColumn. So, I modified the "protected Map registerChartVariable() method in the ar.com.fdvs.dj.core.layout.AbstractLayoutManager to support ExpressionColumn.
I changed the following 3 lines of code in that method:
JRDesignExpression expression = new JRDesignExpression();
expression.setText("$F{" + ((PropertyColumn) col).getColumnProperty().getProperty() + "}");
expression.setValueClass(clazz);
To the following:
if (col instanceof ExpressionColumn) {
ExpressionColumn expCol = (ExpressionColumn) col;
expression.setText(expCol.getTextForExpression());
expression.setValueClassName(expCol.getExpression().getClassName());
} else {
expression.setText("$F{" + ((PropertyColumn) col).getColumnProperty().getProperty() + "}");
expression.setValueClass(clazz);
}
This resolved the problem for me and I no longer get the "Field not found" message.

Running Apache DS embedded in my application

I'm trying to run an embedded ApacheDS in my application. After reading http://directory.apache.org/apacheds/1.5/41-embedding-apacheds-into-an-application.html I build this:
public void startDirectoryService() throws Exception {
service = new DefaultDirectoryService();
service.getChangeLog().setEnabled( false );
Partition apachePartition = addPartition("apache", "dc=apache,dc=org");
addIndex(apachePartition, "objectClass", "ou", "uid");
service.startup();
// Inject the apache root entry if it does not already exist
try
{
service.getAdminSession().lookup( apachePartition.getSuffixDn() );
}
catch ( LdapNameNotFoundException lnnfe )
{
LdapDN dnApache = new LdapDN( "dc=Apache,dc=Org" );
ServerEntry entryApache = service.newEntry( dnApache );
entryApache.add( "objectClass", "top", "domain", "extensibleObject" );
entryApache.add( "dc", "Apache" );
service.getAdminSession().add( entryApache );
}
}
But I can't connect to the server after running it. What is the default port? Or am I missing something?
Here is the solution:
service = new DefaultDirectoryService();
service.getChangeLog().setEnabled( false );
Partition apachePartition = addPartition("apache", "dc=apache,dc=org");
LdapServer ldapService = new LdapServer();
ldapService.setTransports(new TcpTransport(389));
ldapService.setDirectoryService(service);
service.startup();
ldapService.start();
Here is an abbreviated version of how we use it:
File workingDirectory = ...;
Partition partition = new JdbmPartition();
partition.setId(...);
partition.setSuffix(...);
DirectoryService directoryService = new DefaultDirectoryService();
directoryService.setWorkingDirectory(workingDirectory);
directoryService.addPartition(partition);
LdapService ldapService = new LdapService();
ldapService.setSocketAcceptor(new SocketAcceptor(null));
ldapService.setIpPort(...);
ldapService.setDirectoryService(directoryService);
directoryService.startup();
ldapService.start();
I wasn't able to make it run neither with cringe's, Kevin's nor Jörg Pfünder's version. Received constantly NPEs from within my JUnit test. I have debugged that and compiled all of them to a working solution:
public class DirContextSourceAnonAuthTest {
private static DirectoryService directoryService;
private static LdapServer ldapServer;
#BeforeClass
public static void startApacheDs() throws Exception {
String buildDirectory = System.getProperty("buildDirectory");
File workingDirectory = new File(buildDirectory, "apacheds-work");
workingDirectory.mkdir();
directoryService = new DefaultDirectoryService();
directoryService.setWorkingDirectory(workingDirectory);
SchemaPartition schemaPartition = directoryService.getSchemaService()
.getSchemaPartition();
LdifPartition ldifPartition = new LdifPartition();
String workingDirectoryPath = directoryService.getWorkingDirectory()
.getPath();
ldifPartition.setWorkingDirectory(workingDirectoryPath + "/schema");
File schemaRepository = new File(workingDirectory, "schema");
SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor(
workingDirectory);
extractor.extractOrCopy(true);
schemaPartition.setWrappedPartition(ldifPartition);
SchemaLoader loader = new LdifSchemaLoader(schemaRepository);
SchemaManager schemaManager = new DefaultSchemaManager(loader);
directoryService.setSchemaManager(schemaManager);
schemaManager.loadAllEnabled();
schemaPartition.setSchemaManager(schemaManager);
List<Throwable> errors = schemaManager.getErrors();
if (!errors.isEmpty())
throw new Exception("Schema load failed : " + errors);
JdbmPartition systemPartition = new JdbmPartition();
systemPartition.setId("system");
systemPartition.setPartitionDir(new File(directoryService
.getWorkingDirectory(), "system"));
systemPartition.setSuffix(ServerDNConstants.SYSTEM_DN);
systemPartition.setSchemaManager(schemaManager);
directoryService.setSystemPartition(systemPartition);
directoryService.setShutdownHookEnabled(false);
directoryService.getChangeLog().setEnabled(false);
ldapServer = new LdapServer();
ldapServer.setTransports(new TcpTransport(11389));
ldapServer.setDirectoryService(directoryService);
directoryService.startup();
ldapServer.start();
}
#AfterClass
public static void stopApacheDs() throws Exception {
ldapServer.stop();
directoryService.shutdown();
directoryService.getWorkingDirectory().delete();
}
#Test
public void anonAuth() throws NamingException {
DirContextSource.Builder builder = new DirContextSource.Builder(
"ldap://localhost:11389");
DirContextSource contextSource = builder.build();
DirContext context = contextSource.getDirContext();
assertNotNull(context.getNameInNamespace());
context.close();
}
}
the 2.x sample is located at folloing link :
http://svn.apache.org/repos/asf/directory/sandbox/kayyagari/embedded-sample-trunk/src/main/java/org/apache/directory/seserver/EmbeddedADSVerTrunk.java
The default port for LDAP is 389.
Since ApacheDS 1.5.7 you will get a NullpointerException. Please use the tutorial at
http://svn.apache.org/repos/asf/directory/documentation/samples/trunk/embedded-sample
This project helped me:
Embedded sample project
I use this dependency in pom.xml:
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-server-integ</artifactId>
<version>1.5.7</version>
<scope>test</scope>
</dependency>
Further, in 2.0.* the working dir and other paths aren't anymore defined in DirectoryService, but rather in separate class InstanceLayout, which you need to instantiate and then call
InstanceLayout il = new InstanceLayout(BASE_PATH);
directotyService.setInstanceLayout(il);

Categories