web service to retrieve data from solr - web-services

how to write a rest web service to query data from solr server in java. I have the a java code to query from solr
CommonsHttpSolrServer server = null;
try
{
server = new CommonsHttpSolrServer("http://localhost:8080/solr/");
}
catch(Exception e)
{
e.printStackTrace();
}
SolrQuery query = new SolrQuery();
query.setQuery(solrquery);
query.set("rows",1000);
// query.setQueryType("dismax");
// query.setFacet(true);
// query.addFacetField("lastname");
// query.addFacetField("locality4");
// query.setFacetMinCount(2);
// query.setIncludeScore(true);
try
{
QueryResponse qr = server.query(query);
SolrDocumentList sdl = qr.getResults();
I need to get the same functionality in a web service by taking id as the query parameter.

If you just want to query the id passed as an parameter to the webservice -
String id = "100145";
String url = "http://localhost:8080/solr/core_name"; // core name needed if using multicore support
CommonsHttpSolrServer solrServer;
try {
solrServer = new CommonsHttpSolrServer(url);
ModifiableSolrParams qparams = new ModifiableSolrParams();
qparams.add("q", "id:"+id);
QueryResponse qres = solrServer.query(qparams);
SolrDocumentList results = qres.getResults();
SolrDocument doc = results.get(0);
System.out.println(doc.getFieldValue("id"));
} catch (Exception e) {
e.printStackTrace();
}

Related

wso2 identity server custom handler reading from properties file

public class UserRegistrationCustomEventHandler extends AbstractEventHandler {
JSONObject jsonObject = null;
private static final Log log = LogFactory.getLog(UserRegistrationCustomEventHandler.class);
#Override
public String getName() {
return "customClaimUpdate";
}
if (IdentityEventConstants.Event.POST_SET_USER_CLAIMS.equals(event.getEventName())) {
String tenantDomain = (String) event.getEventProperties()
.get(IdentityEventConstants.EventProperty.TENANT_DOMAIN);
String userName = (String) event.getEventProperties().get(IdentityEventConstants.EventProperty.USER_NAME);
Map<String, Object> eventProperties = event.getEventProperties();
String eventName = event.getEventName();
UserStoreManager userStoreManager = (UserStoreManager) eventProperties.get(IdentityEventConstants.EventProperty.USER_STORE_MANAGER);
// String userStoreDomain = UserCoreUtil.getDomainName(userStoreManager.getRealmConfiguration());
#SuppressWarnings("unchecked")
Map<String, String> claimValues = (Map<String, String>) eventProperties.get(IdentityEventConstants.EventProperty
.USER_CLAIMS);
String emailId = claimValues.get("http://wso2.org/claims/emailaddress");
userName = "USERS/"+userName;
JSONObject json = new JSONObject();
json.put("userName",userName );
json.put("emailId",emailId );
log.info("JSON:::::::"+json);
// Sample API
//String apiValue = "http://192.168.1.X:8080/SomeService/user/updateUserEmail?email=sujith#gmail.com&userName=USERS/sujith";
try {
URL url = new URL(cityAppUrl) ;
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
log.info("CONN:::::::::::::"+con);
OutputStream os = con.getOutputStream();
os.write(cityAppUrl.toString().getBytes("UTF-8"));
os.close();
InputStream in = new BufferedInputStream(con.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
jsonObject = new JSONObject(result);
log.info("JSON OBJECT:::::::::"+jsonObject);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void init(InitConfig configuration) throws IdentityRuntimeException {
super.init(configuration);
}
#Override
public int getPriority(MessageContext messageContext) {
return 250;
}
}
I'm using wso2 identity server 5.10.0 and have to push the updated claim value to an API so I'm using a custom handler and have subscribed to POST_SET_USER_CLAIMS, i have to read the API value from deployment.toml file in jave code of the custom handler. So can any one please help here to read the value from deployment file
I can fetch the updated claim value in logs but im not able to get the API value. So can anyone help me here to read the value from deployment file.
Since the API path is required inside your custom event handler, let's define the API path value as one of the properties of the event handler.
Add the deployment.toml config as follows.
[[event_handler]]
name= "UserRegistrationCustomEventHandler"
subscriptions =["POST_SET_USER_CLAIMS"]
properties.apiPath = "http://192.168.1.X:8080/SomeService/user/updateUserEmail"
Once you restart the server identity-event.properties file populates the given configs.
In your custom event handler java code needs to read the config from identity-event.properties file. The file reading is done at the server startup and every config is loaded to the memory.
By adding this to your java code, you can load to configured value in the property.
configs.getModuleProperties().getProperty("UserRegistrationCustomEventHandler.apiPath")
NOTE: property name needs to be defined as <event_handler_name>.<property_name>
Here is a reference to such event hanlder's property loading code snippet https://github.com/wso2-extensions/identity-governance/blob/68e3f2d5e246b6a75f48e314ee1019230c662b55/components/org.wso2.carbon.identity.password.policy/src/main/java/org/wso2/carbon/identity/password/policy/handler/PasswordPolicyValidationHandler.java#L128-L133

How can I read result of web api call from Dynamics 365?

I try to retrieve a record from Dynamics 365 Sales. I created an app registration in Azure and I can get tokens based on this app.
Also, I can call the HTTP client. But I couldn't figure out how to read the result of the HTTP call.
Microsoft published only WhoAmIRequest sample, but I couldn't find a sample of other entities.
Here is my sample code. I try to read body object.
try
{
string serviceUrl = "https://****.crm4.dynamics.com/";
string clientId = "******";
string clientSecret = "*******";
string tenantId = "*******";
A***.Library.Utility.MSCRM mscrm = new Library.Utility.MSCRM(serviceUrl, clientId, clientSecret, tenantId);
var token = await mscrm.GetTokenAsync();
Console.WriteLine(token);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(serviceUrl);
client.Timeout = new TimeSpan(0, 2, 0); //2 minutes
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "/api/data/v9.0/accounts");
// Set the access token
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
// Get the response content and parse it.
var responseStr = response.Content.ReadAsStringAsync();
JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Here is the result of body object.
You can use either of these syntax to read values. Read more
JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
// Can use either indexer or GetValue method (or a mix of two)
body.GetValue("obs_detailerconfigid");
body["obs_detailerconfigid"];

Error during web service call in Xamarin Forms

I've added connected service via Microsoft WCF Web Service Reference Provider (see picture) proxy class has been successfuly created.
Then, when I try execute sample method from this web service (client.TestLanguageAsync() - which returns string) I get null reference exception - but I dont know what is null, because details of exception are very poor (look on picture). Below is code.
private async void BtnTest_Clicked(object sender, EventArgs e) {
try {
var endpoint = new EndpointAddress("https://f9512056.f95.ficosa.com/WMS/WMSWebService.asmx");
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport) {
Name = "basicHttpBinding",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
TimeSpan timeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
WMSWebServiceSoapClient client = new WMSWebServiceSoapClient(binding, endpoint);
string text = await client.TestLanguageAsync(); //This causes exception
label.Text = text;
} catch (Exception E) {
label.Text = E.ToString();
}
}
Look also on screen
Adding service reference and exception screen
Any ideas? Thanks in advance:)

How to consume a webapi in webservice using .net framework 2.0

I need to consume a webapi service which is developed using java. While connecting to the api I am getting error as "Unable to retrieve resources for ' '".
When I consume the same api through soapUI I am able to get response.
Am I missing something?
using (WebClient client = new WebClient())
{
try
{
client.Headers.Clear();
client.Headers[HttpRequestHeader.ContentType] = "application/xml";
client.Headers[HttpRequestHeader.Accept] = "application/xml";
byte[] data = Encoding.UTF8.GetBytes(StrRequestXML);
byte[] result = client.UploadData("url+soapaction", "POST", data);
string xmlResponse = System.Text.Encoding.UTF8.GetString(result);
}
catch (WebException ex)
{
throw ex;
}
}
I think the problem is here:
byte[] result = client.UploadData("url+soapaction", "POST", data);
you pass string "url+soapaction" but there should be The URI of the resource to receive the data.
Maybe you mean
byte[] result = client.UploadData(url + soapaction, "POST", data);

Get Open Graph Data by Facebook API

I want to get some data (title, description, image) using url to page and 'Facebook SDK for .NET' library.
I don't receive image when I use GET request:
Request implementation:
var facebookClient = new FacebookClient(GetAccessToken());
try
{
dynamic data = facebookClient.Get(url);
return new OpenGraphData
{
Id = data.og_object.id,
Title = data.og_object.title,
Description = data.og_object.description
};
}
catch (Exception e)
{
}
Is it possible to create POST request using this library?
If not please tell me another way to get this data
Request data manually
using (WebClient client = new WebClient())
{
try
{
var json =
client.UploadString(String.Format(
"https://graph.facebook.com/v2.4/?id={0}&access_token={1}", url, at), "POST");
}
catch (Exception e)
{
}
}