I am trying to consume JSON from my ASP.net Web API application, from a Java client.
I able to easily do this from a .net client. But cannot figure out a way to do it in JAVA. I have scoured the web to no avail.
Any help would be sincerely appreciated.
Here is the controller code.
public class OrderController : ApiController
{
private SuperiorPizzaEntities1 db = new SuperiorPizzaEntities1();
// GET api/Order
public IEnumerable<Order> GetOrders()
{
List<Order> orders = db.Orders.ToList();
return orders;
}
... More controller methods here.
}
/// Orders Class
public partial class Order
{
public Order()
{
this.OrderDetails = new HashSet<OrderDetail>();
}
public int OrderID { get; set; }
public int UserID { get; set; }
public System.DateTime CreatedDate { get; set; }
public virtual UserAddress UserAddress { get; set; }
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
Java Client Code follows.
This is the code I have written to try to decipher the JSON
/// Java code
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.Object;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.json.*;
import javax.json.stream.*;
import javax.json.stream.JsonParser.Event;
public class JSONReader {
public static void main(String[] args) {
try {
URL url = new URL("http://MyServer/WebAPIs/api/Order");
InputStream is = url.openStream();
JsonParser parser = Json.createParser(is);
{
while (parser.hasNext())
{
Event e = parser.next();
if (e == Event.KEY_NAME)
{
switch (parser.getString())
{
case "name":
parser.next();
System.out.print(parser.getString());
System.out.print(": ");
break;
case "message":
parser.next();
System.out.println(parser.getString());
System.out.println("---------");
break;
default:
//parser.next();
System.out.println(parser.getString());
System.out.println("---------");
break;
}
}
}
}
}
catch(IOException exc)
{
System.out.println("There was an error creating the HTTP Call: " + exc.toString());
}
}
Thanks again
I would try to get away from the manual parsing of the Json. I use the Google GSON library to serialize JSON into an actual java class instance. Here is a quick example.
// standard import statements
// ....
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MyItem
{
public String name;
public String message;
}
/// ... calling code
Gson gson = new Gson();
// hypotehtical call to HTTP endpoint for JSON
String fullJSONListText = getFullJSONFromURL();
// JSON array example e.g: [{name: 'test', message: 'hello}, ...]
Type listType = new TypeToken<List<MyItem>>(){}.getType();
List<MyItem> results = gson.fromJson(fullJSONListText, listType);
//JSON object example
// hypotehtical call to another HTTP endpoint again
String fullJSONObjectText = getFullJSONObjectFromURL();
Type objType = new TypeToken<MyItem>(){}.getType();
MyItem result = gson.fromJson(fullJSONObjectText, objType);
Related
There is Azure API for listing my own permissions. It's partially documented in Azure API Permissions doc (thought they miss the per-subscription case in documentation).
I am struggling to find a way how to call this API via Azure Java SDK - there is Access Management interface accessible via .accessManagement() method, but that contains methods for listing roles and role assignments, not for listing the actual permissions.
Is this missing from the SDK or am I just searching badly?
Sometimes Azure SDK lacks some functionality. And I also checked the java SDK source seems there is no such interface to call this API directly.
So you have 2 options here:
1. Get the role assignments so that you can get the actual role ID, use this role ID you can get the role actual permissions by code below:
Set<Permission> permissions = azureResourceManager.accessManagement().roleDefinitions().getById(
"{role id}")
.permissions();
2. Call the REST API directly, just try the code below:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.stream.Collectors;
import com.azure.core.credential.TokenCredential;
import com.azure.core.credential.TokenRequestContext;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.google.gson.Gson;
public class testAzureAPI {
public static void main(String[] args) {
AzureProfile azureProfile = new AzureProfile(AzureEnvironment.AZURE);
//I use ClientSecretCredential just for demo here, you can change it your self
TokenCredential tokenCredential = new ClientSecretCredentialBuilder()
.clientId("").clientSecret("")
.tenantId("")
.authorityHost(azureProfile.getEnvironment().getActiveDirectoryEndpoint()).build();
String accessToken = tokenCredential
.getToken(new TokenRequestContext().addScopes("https://management.azure.com/.default")).block()
.getToken();
String reqURL = "https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Authorization/permissions?api-version=2015-07-01";
try {
URL url = new URL(reqURL);
URLConnection conn = url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine = in.lines().collect(Collectors.joining());
in.close();
Permissions perms = new Gson().fromJson(inputLine, Permissions.class);
System.out.println(perms.getValue().get(2).getActions());
} catch (Exception e) {
e.printStackTrace();
}
}
public class Value {
public List<String> actions;
public List<Object> notActions;
public List<String> getActions() {
return actions;
}
public void setActions(List<String> actions) {
this.actions = actions;
}
public List<Object> getNotActions() {
return notActions;
}
public void setNotActions(List<Object> notActions) {
this.notActions = notActions;
}
}
public class Permissions {
public List<Value> value;
public List<Value> getValue() {
return value;
}
public void setValue(List<Value> value) {
this.value = value;
}
}
}
I have tested on my side and it works for me perfectly:
Result:
By API:
By code:
I store all static data in the JSON file. This JSON file has up to 1000 rows. How to get the desired data without storing all rows as ArrayList?
My code, I'm using right now and I want to increase its efficiency.
List<Colors> colorsList = new ObjectMapper().readValue(resource.getFile(), new TypeReference<Colors>() {});
for(int i=0; i<colorsList.size(); i++){
if(colorsList.get(i).getColor.equals("Blue")){
return colorsList.get(i).getCode();
}
}
Is it possible? My goal is to increase efficiency without using ArrayList. Is there a way to make the code like this?
Colors colors = new ObjectMapper().readValue(..."Blue"...);
return colors.getCode();
Resource.json
[
...
{
"color":"Blue",
"code":["012","0324","15478","7412"]
},
{
"color":"Red",
"code":["145","001","1","7879","123984","89"]
},
{
"color":"White",
"code":["7","11","89","404"]
}
...
]
Colors.java
class Colors {
private String color;
private List<String> code;
public Colors() {
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public List<String> getCode() {
return code;
}
public void setCode(List<String> code) {
this.code = code;
}
#Override
public String toString() {
return "Colors{" +
"color='" + color + '\'' +
", code=" + code +
'}';
}
}
Creating POJO classes in this case is a wasting because we do not use the whole result List<Colors> but only one internal property. To avoid this we can use native JsonNode and ArrayNode data types. We can read JSON using readTree method, iterate over array, find given object and finally convert internal code array. It could look like below:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
ArrayNode rootArray = (ArrayNode) mapper.readTree(jsonFile);
int size = rootArray.size();
for (int i = 0; i < size; i++) {
JsonNode jsonNode = rootArray.get(i);
if (jsonNode.get("color").asText().equals("Blue")) {
Iterator<JsonNode> codesIterator = jsonNode.get("code").elements();
List<String> codes = new ArrayList<>();
codesIterator.forEachRemaining(n -> codes.add(n.asText()));
System.out.println(codes);
break;
}
}
}
}
Above code prints:
[012, 0324, 15478, 7412]
Downside of this solution is we load the whole JSON to memory which could be a problem for us. Let's try to use Streaming API to do that. It is a bit difficult to use and you must know how your JSON payload is constructed but it is the fastest way to get code array using Jackson. Below implementation is naive and does not handle all possibilities so you should not rely on it:
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
System.out.println(getBlueCodes(jsonFile));
}
private static List<String> getBlueCodes(File jsonFile) throws IOException {
try (JsonParser parser = new JsonFactory().createParser(jsonFile)) {
while (parser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = parser.getCurrentName();
// Find color property
if ("color".equals(fieldName)) {
parser.nextToken();
// Find Blue color
if (parser.getText().equals("Blue")) {
// skip everything until start of the array
while (parser.nextToken() != JsonToken.START_ARRAY) ;
List<String> codes = new ArrayList<>();
while (parser.nextToken() != JsonToken.END_ARRAY) {
codes.add(parser.getText());
}
return codes;
} else {
// skip current object because it is not `Blue`
while (parser.nextToken() != JsonToken.END_OBJECT) ;
}
}
}
}
return Collections.emptyList();
}
}
Above code prints:
[012, 0324, 15478, 7412]
At the end I need to mention about JsonPath solution which also can be good if you can use other library:
import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONArray;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JSONArray array = JsonPath.read(jsonFile, "$[?(#.color == 'Blue')].code");
JSONArray jsonCodes = (JSONArray)array.get(0);
List<String> codes = jsonCodes.stream()
.map(Object::toString).collect(Collectors.toList());
System.out.println(codes);
}
}
Above code prints:
[012, 0324, 15478, 7412]
You can use DSM stream parsing library for memory, CPU efficiency and fast development. DSM uses YAML based mapping file and reads the whole data only once.
Here is the solution of your question:
Mapping File:
params:
colorsToFilter: ['Blue','Red'] # parameteres can be passed programmatically
result:
type: array
path: /.*colors # path is regex
filter: params.colorsToFilter.contains(self.data.color) # select only color that exist in colorsToFilter list
fields:
color:
code:
type: array
Usage of DSM to parse json:
DSM dsm = new DSMBuilder(new File("path/maping.yaml")).create(Colors.class);
List<Colors> object = (List<Colors>) dsm.toObject(jsonData);
System.out.println(object);
Output:
[Colors{color='Blue', code=[012, 0324, 15478, 7412]}, Colors{color='Red', code=[145, 001, 1, 7879, 123984, 89]}]
I am currently doing an internship that involves creating Jira plugins to solve some problems the users at the company experience with Jira. For the first extension I need to create a new section on the view issue page where users can put input and edit the input. In order to do this I've created a web-panel which contains a input. But no matter what I try (And I've been trying different things for the last 3 weeks) I can't get active objects to work.
Currently the moment the plugin tries to load in jira it shows the error: "Error rendering 'tig.jira.extension.tigPasswordExtension:issue-page-input'. Please contact your JIRA administrators." and when I try to test the REST API call in the restbrowser it shows the error:
""message": "AOP configuration seems to be invalid: tried calling method [public abstract net.java.ao.RawEntity[] com.atlassian.activeobjects.external.ActiveObjects.find(java.lang.Class,net.java.ao.Query)] on target [com.atlassian.activeobjects.osgi.TenantAwareActiveObjects#12bfb51b]; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class",
_ "status-code": 500,"_
Is there anyone here that can replicate my problem and pinpoint what I am screwing up?
My current files are as follows:
Atlassian-plugin.xml
<atlassian-plugin key="${atlassian.plugin.key}" name="${project.name}" plugins-version="2">
<plugin-info>
<description>${project.description}</description>
<version>${project.version}</version>
<vendor name="${project.organization.name}" url="${project.organization.url}"/>
<param name="plugin-icon">images/pluginIcon.png</param>
<param name="plugin-logo">images/pluginLogo.png</param>
</plugin-info>
<!-- add our i18n resource -->
<resource type="i18n" name="i18n" location="tigPasswordExtension"/>
<!-- add our web resources -->
<web-resource key="tigPasswordExtension-resources" name="tigPasswordExtension Web Resources">
<dependency>com.atlassian.auiplugin:ajs</dependency>
<resource type="download" name="tigPasswordExtension.css" location="/css/tigPasswordExtension.css"/>
<resource type="download" name="tigPasswordExtension.js" location="/js/tigPasswordExtension.js"/>
<resource type="download" name="images/" location="/images"/>
<context>tigPasswordExtension.resource</context>
</web-resource>
<web-panel name="IssuePageInput" i18n-name-key="issue-page-input.name" key="issue-page-input" location="atl.jira.view.issue.right.context" weight="1">
<description key="issue-page-input.description">Passwords en SSH</description>
<context-provider class="tig.jira.extension.tigPasswordExtension.PasswordContextProvider"/>
<component-import key="appProps" interface="com.atlassian.sal.api.ApplicationProperties"/>
<resource name="view" type="velocity" location="/vm/password-input.vm"/>
<label key="issue-page-input.title"/>
</web-panel>
<!-- Active Objects module -->
<ao key="password-ao">
<description>The configuration of the Active Objects service</description>
<entity>tig.jira.extension.tigPasswordExtension.ao.PasswordModel</entity>
</ao>
<rest name="Password Resource" i18n-name-key="password-resource.name" key="password-resource" path="/passwordresource" version="1.0">
<description key="password-resource.description">The Password Resource Plugin</description>
</rest>
</atlassian-plugin>
tigPasswordExtension.js
AJS.toInit(function($) {
AJS.$('#searchButton2').click(function (){
var test = "lol";
AJS.$.ajax({
url:"jira/rest/passwordresource/1.0/password",
type: "post",
dataType: 'json',
async: false,
data: ({issueKey : document.getElementById("issueKeyInput").value, content: document.getElementById("passwordInput").value}),
success: function(data)
{
test = data;
console.log(test);
}
})
});
});
PasswordDto
package tig.jira.extension.tigPasswordExtension.dto;
public class PasswordDto {
private String issueKey;
private String content;
public PasswordDto(){}
public String getIssueKey(){return this.issueKey;}
public void setIssueKey(String issueKey){this.issueKey = issueKey;}
public String getContent(){return this.content;}
public void setContent(String content){this.content = content;}
}
PasswordModel
package tig.jira.extension.tigPasswordExtension.ao;
import net.java.ao.Entity;
import net.java.ao.Preload;
#Preload
public interface PasswordModel extends Entity {
String getIssue();
void setIssue(String issue);
String getContent();
void setContent(String content);
}
PasswordDao
package tig.jira.extension.tigPasswordExtension.ao;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import com.google.common.collect.ImmutableMap.Builder;
import net.java.ao.Query;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Map;
#Named
public class PasswordDao {
private final ActiveObjects activeObjects;
#Inject
public PasswordDao(#ComponentImport ActiveObjects activeObjects){this.activeObjects = activeObjects;}
public PasswordModel getByIssueKey(String issueKey){
Query query = this.buildIssueQuery(issueKey);
PasswordModel[] passwordModels = this.activeObjects.find(PasswordModel.class, query);
return passwordModels.length > 0 ? passwordModels[0] : null;
}
public void update(String issueKey, String content){
PasswordModel passwordModel = this.getByIssueKey(issueKey);
if (passwordModel == null){
Map<String, Object> params = (new Builder()).put("ISSUE_KEY", issueKey).put("CONTENT", content).build();
this.activeObjects.create(PasswordModel.class, params);
} else {
passwordModel.setContent(content);
passwordModel.save();
}
}
private Query buildIssueQuery(String issueKey){
return Query.select().where("ISSUE_KEY = ?", issueKey);
}
}
PasswordResource
package tig.jira.extension.tigPasswordExtension.rest;
import tig.jira.extension.tigPasswordExtension.service.PasswordService;
import javax.ws.rs.*;
#Path("/password")
public class PasswordResource{
private final PasswordService passwordService;
public PasswordResource(PasswordService passwordService){this.passwordService = passwordService;}
#POST
public void update(#QueryParam("issue") String issueKey, #QueryParam("content") String content) {
this.passwordService.update(issueKey, content);
}
}
PasswordService
package tig.jira.extension.tigPasswordExtension.service;
import tig.jira.extension.tigPasswordExtension.ao.PasswordDao;
import tig.jira.extension.tigPasswordExtension.ao.PasswordModel;
import tig.jira.extension.tigPasswordExtension.dto.PasswordDto;
import javax.inject.Inject;
import javax.inject.Named;
#Named
public class PasswordService {
private final PasswordDao passwordDao;
#Inject
public PasswordService(PasswordDao passwordDao){
this.passwordDao = passwordDao;
}
public void update(String issueKey, String content){
this.passwordDao.update(issueKey, content);
}
public PasswordDto getByIssueKey(String issueKey){
PasswordModel passwordModel = this.passwordDao.getByIssueKey(issueKey);
if (passwordModel == null){
return null;
} else {
PasswordDto dto = new PasswordDto();
dto.setIssueKey(issueKey);
dto.setContent(passwordModel.getContent());
return dto;
}
}
}
PasswordContextProvider
package tig.jira.extension.tigPasswordExtension;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.plugin.webfragment.contextproviders.AbstractJiraContextProvider;
import com.atlassian.jira.plugin.webfragment.model.JiraHelper;
import com.atlassian.jira.user.ApplicationUser;
import tig.jira.extension.tigPasswordExtension.dto.PasswordDto;
import tig.jira.extension.tigPasswordExtension.service.PasswordService;
import java.util.HashMap;
import java.util.Map;
public class PasswordContextProvider extends AbstractJiraContextProvider {
Map contextMap = new HashMap();
private String issueKey;
private final PasswordService passwordService;
public PasswordContextProvider(PasswordService passwordRepository){
this.passwordService = passwordRepository;
}
public Map getContextMap(ApplicationUser user, JiraHelper jiraHelper) {
Issue currentIssue = (Issue) jiraHelper.getContextParams().get("issue");
issueKey = currentIssue.getKey();
//passwordService.update(issueKey, "klote");
PasswordDto passwordDto = this.passwordService.getByIssueKey(issueKey);
if (passwordDto != null){
contextMap.put("AO", "1");
contextMap.put("content", "Staat nog niks in gek");
if (passwordDto.getContent() != null) {
contextMap.put("content", passwordDto.getContent());
}
}
contextMap.put("issueKey", issueKey);
return contextMap;
}
}
The only problem I could find after a quick look is in the class PasswordDao. If I replace the variable query by it's value then it will look like below.
activeObjects.find(PasswordModel.class, Query.select().where("ISSUE_KEY = ?", issueKey));
Whereas your entity class PasswordModel.java does not have any such method String xxxIssueKey(). Refer Offical document for column name of table created using ActiveObjects.
Best practice documentation can be a good start for you when working with Active Objects.
Update the method as given below (change ISSUE_KEY to ISSUE).
private Query buildIssueQuery(String issueKey){
return Query.select().where(" ISSUE = ? ", issueKey);
}
I hope this helps you.
I am trying to query vendors using the QBOVendorService but having no luck.
I am creating the service as follows:
QBOVendorService vService = QBServiceFactory.getService(context, QBOVendorService.class);
where the context is a valid PlatformSessionContext. I know the platform session context is good since I can get information about the user with it. When I try
vService.addVendor(context, vendor);
I end up with a NPE like my vService is null. Shouldn't I get an error initializing the QBOVendorService if it fails? Is there a good place to find more examples for using this since the intuit developer forums have been shut down?
I'm sharing a sample code snippet. Replace your OAuth tokens and relamId. It should work fine.
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import com.intuit.ds.qb.QBIdType;
import com.intuit.ds.qb.QBVendor;
import com.intuit.ds.qb.QBVendorQuery;
import com.intuit.ds.qb.QBVendorService;
import com.intuit.ds.qb.QBInvalidContextException;
import com.intuit.ds.qb.QBObjectFactory;
import com.intuit.ds.qb.QBServiceFactory;
import com.intuit.ds.qb.impl.QBRecordCountImpl;
import com.intuit.ds.qb.qbd.QBDRecordCountService;
import com.intuit.ds.qb.qbd.QBDServiceFactory;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.security.OAuthCredentials;
import com.intuit.ds.qb.QBSyncStatusRequest;
import com.intuit.ds.qb.QBSyncStatusRequestService;
import com.intuit.ds.qb.QBSyncStatusResponse;
import com.intuit.sb.cdm.NgIdSet;
import com.intuit.sb.cdm.ObjectName;
import org.slf4j.Logger;
// QBD API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/vendor
// QBO API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/vendor
// JavaDocs - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
public class CodegenStubVendorall {
final PlatformSessionContext context;
public CodegenStubVendorall(PlatformSessionContext context) {
this.context = context;
}
public void testAdd() {
final List<QBVendor> entityList = new ArrayList<QBVendor>();
try {
QBVendorService service = QBServiceFactory.getService(context, QBVendorService.class);
//Your Code
//Use Vendor POJO for creating Vendor
}
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
PlatformSessionContext context = getPlatformContext();
CodegenStubVendorall testObj = new CodegenStubVendorall(context);
testObj.testAdd();
}
public static PlatformSessionContext getPlatformContext() {
String accesstoken = "rplce_your_application_token";
String accessstokensecret = "rplce_your_application_token";
String appToken = "rplce_your_application_token";
String oauth_consumer_key = "rplce_your_application_token";
String oauth_consumer_secret = "rplce_your_application_token";
String realmID = "123456";
String dataSource = "QBO";
PlatformServiceType serviceType;
if (dataSource.equalsIgnoreCase("QBO")) {
serviceType = PlatformServiceType.QBO;
} else {
serviceType = PlatformServiceType.QBD;
}
final OAuthCredentials oauthcredentials = new OAuthCredentials(
oauth_consumer_key, oauth_consumer_secret, accesstoken,
accessstokensecret);
final PlatformSessionContext context = new PlatformSessionContext(
oauthcredentials, appToken, serviceType, realmID);
return context;
}
}
You can try to use ApiExplorer tool to verify your OAuth tokens and to check the create Vendor API endpoint.
Link - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Please let me know how it goes.
Thanks
I'm trying to make a search through the Fedora Commons web service. I'm interested in the findObjects method. How can I make a search in Java equal to the example described on the findObjects syntax documentation.
I'm particularly interested in this type of request:
http://localhost:8080/fedora/search?terms=fedora&pid=true&title=true
I'll attach some code, I have a class that can call my Fedora service already.
package test.fedora;
import info.fedora.definitions._1._0.types.DatastreamDef;
import info.fedora.definitions._1._0.types.MIMETypedStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.ws.BindingProvider;
import org.w3c.dom.Document;
public class FedoraAccessor {
info.fedora.definitions._1._0.api.FedoraAPIAService service;
info.fedora.definitions._1._0.api.FedoraAPIA port;
final String username = "xxxx";
final String password = "yyyy";
public FedoraAClient() {
service = new info.fedora.definitions._1._0.api.FedoraAPIAService();
port = service.getFedoraAPIAServiceHTTPPort();
((BindingProvider) port.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
}
public List findObjects() {
//how?
}
public List<DatastreamDef> listDatastreams(String pid, String asOfTime) {
List<DatastreamDef> result = null;
try {
result = port.listDatastreams(pid, asOfTime);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
It's easier using the client from mediashelf (http://mediashelf.github.com/fedora-client/). Here's an example searching for objects containing the string foobar in the title:
#Test
public void doTest() throws FedoraClientException {
connect();
FindObjectsResponse response = null;
response = findObjects().pid().title().query("title~foobar").execute(fedoraClient);
List<String> pids = response.getPids();
List<String> titles = new ArrayList<String>();
for (String pid : pids) {
titles.add(response.getObjectField(pid, "title").get(0));
}
assertEquals(7, titles.size());
}