example OAuth 1.0 implementation in java - java

I need an example in java to be able to consume an API using OAuth 1.0 to generate the token :
NB: i have only those informations (the consumerKey, ConsumerSecret, AccesToken and the acessTokenSecret).
I have searched int the internet but I have not found a result that can help me.

I'm looking for the same but, actually, I have an example provided by the admins of the API that I'm trying to consume.
Since no one replied to this thread, I'll paste the mentioned example here, hoping it could help in some way.
Also, if someone can give me a hand, understand the code and explain how to implement it, it would be great.
package com.example.entities;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.oauth.client.OAuthClientFilter;
import com.sun.jersey.oauth.signature.HMAC_SHA1;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;
public class SSRestServiceClient {
/*
* private constructor to avoid construction of object.
*/
private SSRestServiceClient(String url, String consumerKey, String consumerSecret, int timeoutSeconds) {
OAuthParameters params = new OAuthParameters().signatureMethod(HMAC_SHA1.NAME).consumerKey(consumerKey).version(OAUTH_VERSION);
OAuthSecrets secrets = new OAuthSecrets().consumerSecret(consumerSecret);
Client httpClient = Client.create();
httpClient.setConnectTimeout(timeoutSeconds * 1000);
httpClient.setReadTimeout(timeoutSeconds * 1000);
OAuthClientFilter filter = new OAuthClientFilter(httpClient.getProviders(), params, secrets);
httpClient.addFilter(filter);
httpClient.addFilter(new LoggingFilter());
this.consumerKey = consumerKey;
this.webResource = httpClient.resource(url);
}
/*
* Creates instance of the Client class, returns existing instance if it's already created.
*/
public static synchronized SSRestServiceClient getInstance(String url, String consumerKey, String consumerSecret) {
return getInstance(url, consumerKey, consumerSecret, 0);
}
/*
* Creates instance of the Client class, returns existing instance if it's already created.
*/
public static synchronized SSRestServiceClient getInstance(String url, String consumerKey,String consumerSecret, int timeoutSeconds) {
if (client == null || client.getConsumerKey() == null || !client.getConsumerKey().equals(consumerKey)) {
if (timeoutSeconds != 0 && timeoutSeconds < ONE_MINUTE) {
timeoutSeconds = ONE_MINUTE;
}
client = new SSRestServiceClient(url, consumerKey, consumerSecret, timeoutSeconds);
}
return client;
}
/*
* Return a list of all active source cities.
*/
#Override
public CityList getAllSources() {
return webResource.path(GET_ALL_SOURCES).get(CityList.class);
}
}

Related

Listing my Azure permissions from Azure Java SDK

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:

Java Webcrawler to extract emails

I want to write a web crawler that starts at one page and goes to each link on that page looking for an email address. This is what I have so far, but it's not doing anything other than going from webpage to webpage.
`package com.netinstructions.crawler;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class WebCrawler {
private static final int MAX_PAGES_TO_SEARCH = 26;
private Set<String> pagesVisited = new HashSet<String>();
private List<String> pagesToVisit = new LinkedList<String>();
private List<String> emails = new LinkedList<>();
private String nextUrl()
{
String nextUrl;
do
{
nextUrl = this.pagesToVisit.remove(0);
} while(this.pagesVisited.contains(nextUrl));
this.pagesVisited.add(nextUrl);
return nextUrl;
}
public void search(String url, String searchWord)
{
while(this.pagesVisited.size() < MAX_PAGES_TO_SEARCH)
{
String currentUrl;
SpiderLeg leg = new SpiderLeg();
if(this.pagesToVisit.isEmpty())
{
currentUrl = url;
this.pagesVisited.add(url);
}
else
{
currentUrl = this.nextUrl();
}
leg.crawl(currentUrl); // Lots of stuff happening here. Look at the crawl method in
// SpiderLeg
leg.searchForWord(currentUrl, emails);
this.pagesToVisit.addAll(leg.getLinks());
this.pagesToVisit.addAll(leg.getLinks());
}
System.out.println(emails.toString());
//System.out.println(String.format("**Done** Visited %s web page(s)", this.pagesVisited.size()));
}
}
And this is my Spider Leg Class
package com.netinstructions.crawler;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class SpiderLeg
{
// We'll use a fake USER_AGENT so the web server thinks the robot is a normal web browser.
private static final String USER_AGENT =
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
private List<String> links = new LinkedList<String>();
private Document htmlDocument;
/**
* This performs all the work. It makes an HTTP request, checks the response, and then gathers
* up all the links on the page. Perform a searchForWord after the successful crawl
*
* #param url
* - The URL to visit
* #return whether or not the crawl was successful
*/
public boolean crawl(String url)
{
try
{
Connection connection = Jsoup.connect(url).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
this.htmlDocument = htmlDocument;
if(connection.response().statusCode() == 200) // 200 is the HTTP OK status code
// indicating that everything is great.
{
System.out.println("\n**Visiting** Received web page at " + url);
}
if(!connection.response().contentType().contains("text/html"))
{
System.out.println("**Failure** Retrieved something other than HTML");
return false;
}
Elements linksOnPage = htmlDocument.select("a[href]");
//System.out.println("Found (" + linksOnPage.size() + ") links");
for(Element link : linksOnPage)
{
this.links.add(link.absUrl("href"));
}
return true;
}
catch(IOException ioe)
{
// We were not successful in our HTTP request
return false;
}
}
/**
* Performs a search on the body of on the HTML document that is retrieved. This method should
* only be called after a successful crawl.
*
* #param searchWord
* - The word or string to look for
* #return whether or not the word was found
*/
public void searchForWord(String searchWord, List<String> emails)
{
if(this.htmlDocument == null)
{
System.out.println("ERROR! Call crawl() before performing analysis on the document");
//return false;
}
Pattern pattern =
Pattern.compile("\"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\\\.[A-Z]{2,6}$\", Pattern.CASE_INSENSITIVE");
Matcher matchs = pattern.matcher(searchWord);
while (matchs.find()) {
System.out.println(matchs.group());
}
}
public List<String> getLinks()
{
return this.links;
}
}
My web crawler was taken from another source and I changed a few things. I added a List to hold the emails and return them all in a list to me. I think I am going wrong in my way that I take the email and put it in the list, but I am not sure how to fix it.
Spider Leg Class
Pattern.compile("\"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\\\.[A-Z]{2,6}$\", Pattern.CASE_INSENSITIVE");
Shouldn't this be...?
Pattern.compile("[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}", Pattern.CASE_INSENSITIVE);
Nothing gets added to the emails, so you need to emails.push() the emails you find to the list. Secondly, you probably want to be parsing the HTML document, not the URL of the page. Since the method now doesn't return anything, you need to expand the if statement to avoid the null pointer. The searchForWord method should be:
public void searchForWord(String searchWord, List<String> emails)
{
if(this.htmlDocument == null)
{
System.out.println("ERROR! Call crawl() before performing analysis on the document");
} else
{
String input = this.htmlDocument.toString();
Pattern pattern =
Pattern.compile("[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}", Pattern.CASE_INSENSITIVE);
Matcher matchs = pattern.matcher(input);
while (matchs.find()) {
emails.push(matchs.group());
}
}
}

Jackrabbit WebDAV Synchronization Examples?

I'm using the Jackrabbit library for communicating with a cloud storage using the webdav protocol. I need a way to list all files from a specific directory and get the last modified property but I can't seem to find any working examples on this.
I basically need code to synchronize files from the local directory with the webdav url.
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.apache.jackrabbit.webdav.client.methods.PutMethod;
public class WebDavClient
{
private String resourceUrl;
private HttpClient client;
private Credentials credentials;
private DavMethod method;
public WebDavClient(String resourceUrl, String username, String password)
throws Exception
{
this.resourceUrl = resourceUrl;
client = new HttpClient();
credentials = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(AuthScope.ANY, credentials);
}
public int upload(String fileToUpload) throws Exception
{
method = new PutMethod(getUpdatedWebDavPath(fileToUpload));
RequestEntity requestEntity = new InputStreamRequestEntity(
new FileInputStream(fileToUpload));
((PutMethod) method).setRequestEntity(requestEntity);
client.executeMethod(method);
return method.getStatusCode();
}
public int createFolder(String folder) throws Exception
{
method = new MkColMethod(getUpdatedWebDavPath(folder));
client.executeMethod(method);
return method.getStatusCode();
}
private String getUpdatedWebDavPath(String file)
{
// Make sure file names do not contain spaces
return resourceUrl + "/" + new File(file).getName().replace(" ", "");
}
}
Usage example for uploading the file Test.txt to the Backup folder:
String myAccountName = "...";
String myPassword = "...";
WebDavClient webdavUploader = new WebDavClient("https:\\\\webdav.hidrive.strato.com\\users\\" + myAccountName + "\\Backup", myAccountName, myPassword);
webdavUploader.upload("C:\\Users\\Username\\Desktop\\Test.txt");
Here's a list of different DavMethods that could be helpful:
http://jackrabbit.apache.org/api/1.6/org/apache/jackrabbit/webdav/client/methods/package-summary.html
Please help, I'm been struggling on this for so long!
Take a look at the AMES WebDAV Client code from Krusche and Partner on the EU portal. It is licensed under GPL, so should it may fit your purpose.
https://joinup.ec.europa.eu/svn/ames-web-service/trunk/AMES-WebDAV/ames-webdav/src/de/kp/ames/webdav/WebDAVClient.java
It works for me, though to access e.g. Win32LastModifiedTime I need to get the custom namespace, e.g.
private static final Namespace WIN32_NAMESPACE = Namespace.getNamespace("Z2", "urn:schemas-microsoft-com:");
and retrieve the custom Property Win32LastModifiedTime from the properties.
/*
* Win32LastModifiedTime
*/
String win32lastmodifiedtime = null;
DavProperty<?> Win32LastModifiedTime = properties.get("Win32LastModifiedTime", WIN32_NAMESPACE);
if ((Win32LastModifiedTime != null) && (Win32LastModifiedTime.getValue() != null)) win32lastmodifiedtime = Win32LastModifiedTime.getValue().toString();

Magento XML-RPC API - Create Shipment From Java

Im trying to create shipments for magento orders from my third party app using the XML-RPC API. Everything works great when i make the call to "sales_order_shipment.create" with just the order increment id, but if i try making the same call with both an order increment id and a set of items and quantities, it will say "Requested order not exists." Why is that? what im doing wrong? what type should be the itemQuantity)
heres my code
package magentoapiclient;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
public class XMLRPCAPIClient {
public static void main(String[] args) {
createShipment("100000005", 5, 1.0);
}
public static XmlRpcClient prepareClient() throws MalformedURLException {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("myHost"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
client.setTypeFactory(new MyTypeFactory(client));
return client;
}
public static void createShipment(String orderIncrementId, int itemId, double quantity) {
try {
XmlRpcClient client = prepareClient();
String sessionId = login("myUser", "myKey", client);
System.out.println(sessionId);
Object[] request = {orderIncrementId, new HashMap()};
client.execute("call", new Object[]{sessionId, "sales_order_shipment.create", request});
endSession(sessionId, client);
} catch (XmlRpcException | MalformedURLException ex) {
Logger.getLogger(XMLRPCAPIClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static String login(String user, String password, XmlRpcClient client) throws XmlRpcException {
String sessionId = (String) client.execute("login", new Object[]{user, password});
return sessionId;
}
public static void endSession(String sessionToken, XmlRpcClient client) throws XmlRpcException {
client.execute("endSession", new Object[]{sessionToken});
}
}
As you see in the line
Object[] request = {orderIncrementId, new HashMap()};
i try sending a hashMap that actually should contain the order item id and quantity. Ive also tried sending an array of objects and it doesnt work for any of them. What sould be there instead then if neither a Map or an Array is available?
Thank you for your help
Order Id and Order increment id are different. You should send order increment id.
http://www.magentocommerce.com/api/soap/sales/salesOrder/sales_order.info.html

How to call Fedora Commons findObjects method (web service)

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());
}

Categories

Resources