Applications Credentials not avaliable in Google Cloud Vision API - java

I am trying to setup Google Cloud Vision API, I have defined a Application Credential Variable through CMD by using set GOOGLE_APPLICATION_CREDENTIALS PathToJSON however this still does not allow me to connect to Google Cloud Vision API for OCR.
I have also tried to set it manually through the windows UI, however still no luck, I created and defined a project in the Google Cloud page, and generated a credential key, when it asked me "Are you planning to use this API with App Engine or Compute Engine?", I selected No.
I am currently using Googles boilerplate code
public class DetectText {
public static void main(String args[])
{
try{
detectText();
}catch (IOException e)
{
e.printStackTrace();
}
}
public static void detectText() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String filePath = "C:\\Users\\Programming\\Desktop\\TextDetection\\Capture.PNG";
detectText(filePath);
}
// Detects text in the specified image.
public static void detectText(String filePath) throws IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
for (EntityAnnotation annotation : res.getTextAnnotationsList()) {
System.out.format("Text: %s%n", annotation.getDescription());
System.out.format("Position : %s%n", annotation.getBoundingPoly());
}
}
}
}
static void authExplicit(String jsonPath) throws IOException {
}
}
I am not using a server or Google compute virtual machine.
Can someone please explain to me what the problem is, and how I would go about fixing it?
Stack Trace
java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:119)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:91)
at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:67)
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:142)
at com.google.cloud.vision.v1.stub.GrpcImageAnnotatorStub.create(GrpcImageAnnotatorStub.java:117)
at com.google.cloud.vision.v1.stub.ImageAnnotatorStubSettings.createStub(ImageAnnotatorStubSettings.java:156)
at com.google.cloud.vision.v1.ImageAnnotatorClient.<init>(ImageAnnotatorClient.java:136)
at com.google.cloud.vision.v1.ImageAnnotatorClient.create(ImageAnnotatorClient.java:117)
at com.google.cloud.vision.v1.ImageAnnotatorClient.create(ImageAnnotatorClient.java:108)
at DetectText.detectText(DetectText.java:54)
at DetectText.detectText(DetectText.java:36)
at DetectText.main(DetectText.java:25)

Based on your error message, it seems that the GOOGLE_APPLICATION_CREDENTIALS environment variable is not being found.
On one hand, before trying to run the text detection sample code, follow the steps outlined in the documentation in order to discard that any of them has been skipped.
On the other hand, if you are using an IDE such as IntelliJ or Eclipse, you have to set the environment variable GOOGLE_APPLICATION_CREDENTIALS global through Windows System Properties, so it can be used by the IDE. Nevertheless, when testing I had to close and reopen the IDE for the changes to take effect and the aforementioned error would not appear.
Additionally, there is also a way to specify the location of the JSON file within the code, as shown in this example. However, it is not advisable to put it that way, it is best to use the environment variables.

Related

Hyperledger fabric endorsement policy error using Java SDK

I am working on golang version of fabcar smart contract while seeking to implement a Java-SDK API which enrolls an admin, registers a user and performs query-update value operations based on https://github.com/hyperledger/fabric-samples/tree/master/fabcar/java
I have successfully set up a 3 org-9 peers blockchain network, installed, instantiated and invoked chaincode on peers.
However, as i am working on implementing the relative API, i am only able to successfully query blockchain database, while getting a "Could not meet endorsement policy for chaincode mycc"
Please find below screenshot of relative error
Endorsement policy is "OR ('Org1MSP.member','Org2MSP.member', 'Org3MSP.member')".
Should registered user somehow get an Org1/Org2/Org3.member attribute? Any leads would be appreciated!
Like #Ikar Pohorský said, for me this got resolved after I used correct method name. Also, ensure that you delete 'wallet' folder in order to regenerate the user if your HLF n/w was recreated.
#Test
public void testMyMethodToBeInvoked() throws Exception {
deleteDirectory(".\\wallet");
EnrollAdmin.main(null);
RegisterUser.main(null);
// Load a file system based wallet for managing identities.
final Path walletPath = Paths.get("wallet");
final Wallet wallet = Wallet.createFileSystemWallet(walletPath);
// load a CCP
final Path networkConfigPath = Paths
.get("C:\\sw\\hlf146-2\\fabric-samples\\first-network\\connection-org1.yaml");
final Gateway.Builder builder = Gateway.createBuilder();
builder.identity(wallet, "user1").networkConfig(networkConfigPath).discovery(true);
// create a gateway connection
try (Gateway gateway = builder.connect()) {
final Network network = gateway.getNetwork("mychannel");
final Contract contract = network.getContract("mycc");
String myJSONString="{\"a\":\"b\"}";
byte[] result;
// Following did NOT work. Control goes directly to 'invoke' when 'submitTransaction' is done directly. 'invoke' need not be mentioned here.
// result = contract.submitTransaction("invoke", myJSONString);
// Following DID work. In chaincode (my chain code was Java) I had a method named 'myMethodToBeInvoked'. The chain code was written similar to https://github.com/hyperledger/fabric-samples/blob/release-1.4/chaincode/chaincode_example02/java/src/main/java/org/hyperledger/fabric/example/SimpleChaincode.java
result = contract.submitTransaction("myMethodToBeInvoked", my);
System.out.println(new String(result));
}
}
EDIT: Also, please remember that if your chaincode throws errorResponse, even then we can have this endorsement fail issue. So, check if your chain code is working without any issues.

Dynamic BlazeDS endpoint configuration

I search for some help creating a web Flex application using BlazeDS and Java server with dynamic BlazeDS endpoint configuration.
First, I will try to explain my current situation.
I have a Flex 3.2 application that provides GUI of the application. From the ActionScript I call Java methods using BlazeDS. To access the BlazeDS I use a Config class that provides the endpoint as shown below (it is a constructor):
public function Config(): void {
if (_serviceUrl == null) {
try {
var browser: IBrowserManager = BrowserManager.getInstance();
browser.init();
var url: String = browser.url;
var host: String = mx.utils.URLUtil.getServerName(url);
var port: uint = mx.utils.URLUtil.getPort(url);
var parts: Array = url.split('/');
if (parts[2] == '') {
url = DEFAULT_URL;
Alert.show("Unable to determine server location, using default URL: " + DEFAULT_URL, "Connection error");
}
else {
url = parts[0] + '//' + parts[2] + '/' + parts[3] + '/messagebroker/amf';
}
_serviceUrl = url;
} catch (e: Error) {
Alert.show("Exception while trying to determine server location, using default URL: " + DEFAULT_URL, "Connection exception");
_serviceUrl = DEFAULT_URL;
}
}
}
The idea of the class is to determine the endpoint from the request URL. I use a Delegate class to call the remote methods using BlazeDS like the following:
{
import com.adobe.cairngorm.business.ServiceLocator;
import mx.rpc.IResponder;
import mx.rpc.remoting.RemoteObject;
public class AbstractRemoteDelegate
{
public function AbstractRemoteDelegate(responder:IResponder,serviceName:String)
{
_responder=responder;
_locator=ServiceLocator.getInstance();
_service=_locator.getRemoteObject(serviceName);
_service.showBusyCursor=true;
_service.endpoint = Config.instance.serviceUrl;
}
private var _responder:IResponder;
private var _locator:ServiceLocator;
private var _service:RemoteObject;
protected function send(operationName:String,... args:Array) : void {
_service.getOperation(operationName).send.apply(_service.getOperation(operationName),args).addResponder(_responder);
}
}
}
This approach actually works fine. However, I got across a situation where I can't use dynamically determined URL. In such a situation, I need a hard-coded URL in the Config.as file. And this is the problem. When trying to deploy the application to another server, I always need to rebuild the application with a new URL configuration in the ActionScript class Config.
Therefore I search for a way to define a static configuration for the Flex application to connect to a BlazeDS server. And the way to change such configuration without rebuilding the application so I can give the customer his own way to reconfigure and move the Flex application.
I thought about using a configuration file, but Flex runs on the client side and there is no configuration file!
I thought about using database configuration, but I don't have any database on the client side!
To sum up, I am looking for a way, how to get BlazeDS URL from a configuration to be able to change it without rebuilding the whole app.
Thanks for any useful suggestions.
EDIT: Revised the question to be more actual. I improved the way to determine the URL dynamically from the request URL, so it works now even for proxy server. However, my curiosity persists for the configuration of flex without rebuilding.
Here is an old example Blaze DS Service of mine which does basically the same as you did. It's just the string which needs to be created correctly. If the endpoint address is wrong, catch the error accordingly.
My project may currently not build because of Flexmojos ... I'm not able to test that yet.
Since it did not read you question properly, I misunderstood you: You can put a configuration file next to the SWF and load it via URLLoader or pass it via FlashVars. That should give you the freedom to pass the endpoint dynamically.

getting Restricted operation on a server while getting AdministrationProcess from Session in IBM Domino

I have a requirement to add group members to an IBM Domino Group through java code. I am using Notes.jar to connect to IBM Domino v9.0, and my java code is running on a different machine, then the Domino machine.
From the Domino documentation I found out that "AdministrationProcess" class needs to be used to add member to group. But when i am trying to create "AdministrationProcess" object by calling session.createAdministrationProcess("IBMDominoServer"). I am getting the error Restricted operation on a server.
My test code is as follows
public class LotusDomino{
public static void main(String args[]) throws Exception{
String[] argv = {"192.168.2.111","Administrator","<password>"};
deleteUser(argv[0], argv[1], argv[2]);
}
private static void deleteUser(String host, String userName, String password) throws Exception{
Session s = NotesFactory.createSession(host, userName, password);
try{
AdministrationProcess process = s.createAdministrationProcess("IBMDominoServer.xanadufinancials.com");
}catch(NotesException e){
System.err.println("exception --- "+e.id+":"+e.text+":"+e.internal); // this prints the following error : exception --- 4183:Restricted operation on a server:null
}
}
The code shows same error irrespective of what i pass in as the server Name . So it shouldn't be a code issue. I did a little bit of search for this, and found out that Administrator should have editor access on admin4.nsf. Verified the access it was present.
Please let me know what can be the issue. Thanks in advance.
Using the Administration Process is one way to add a user to a group, and it is the safest way when you have no knowledge of how directory services on the Domino server have been configured. But in most basic configurations, adding a user to a group is very simple. You open the names.nsf database, open the Groups view, locate the document for the group, and add the name to the list stored in the Members item. The one catch is that if the Members list is too long, you may have to write code that is capable of divide it into subgroups (and/or code to detect the pattern of existing subgroups and add to them instead).
Regarding using the NotesAdministrationProcess class, if we can trust that the error message means what it says it means, then your problem is that the user id you are using does not have permission to run restricted operations on the server. Here is a link to info about server configuration for agent permissions. If you're using NCSO.jar (see my question above), then be a separate configuration for users permitted to perform restricted operations over IIOP, but I'm not sure and my server is down at the moment so I can't check.

Developing a Java Application that uses an AppEngine database

This might be a very trivial question, but I'm having trouble finding an answer:
Using the Google Plugin for Eclipse, I would like to develop a plain old Java application (not a web-app), that uses AppEngine for cloud storage.
For this, I could, of course, simply create two projects, one containing the AppEngine server and one containing the Java application.
But I'm wondering whether it is possible to set up a single project in Eclipse that contains both the server and the client code (like for a GWT project). To execute it for local debugging, I would then want Eclipse to launch Tomcat to make my servlets available and then launch my Main.java from the client directory of the project as if the project was just a simple Java application. Is this what the "Launch and deploy from this directory" checkbox is for in the "Google" -> "Web Application" settings? If so, how do I use it?
I found one way to do it, but it's a bit cheesy.
First, add the following helper-class to the project:
// other imports
import com.google.appengine.tools.development.DevAppServerMain;
public class DevServer {
public static void launch(final String[] args) {
Logger logger = Logger.getLogger("");
logger.info("Launching AppEngine server...");
Thread server = new Thread() {
#Override
public void run() {
try {
DevAppServerMain.main(args); // run DevAppServer
} catch (Exception e) { e.printStackTrace(); }
}
};
server.setDaemon(true); // shut down server when rest of app completes
server.start(); // run server in separate thread
URLConnection cxn;
try {
cxn = new URL("http://localhost:8888").openConnection();
} catch (IOException e) { return; } // should never happen
boolean running = false;
while (!running) { // maybe add timeout in case server fails to load
try {
cxn.connect(); // try to connect to server
running = true;
// Maybe limit rate with a Thread.sleep(...) here
} catch (Exception e) {}
}
logger.info("Server running.");
}
}
Then, add the following line to the entry class:
public static void main(String[] args) {
DevServer.launch(args); // launch AppEngine Dev Server (blocks until ready)
// Do everything else
}
Finally, create the appropriate Run Configuration:
Simply click "Run As" -> "Web Application". To create a default Run Configuration.
In the created Run Configuration, under the "Main"-tab select your own entry class as the "Main class" instead of the default "com.google.appengine.tools.development.DevAppServerMain".
Now, if you launch this Run Configuration, it will first bring up the AppEngine server and then continue with the rest of the main(...) method in the entry class. Since the server thread is marked as a daemon thread, once the other code in main(...) completes, the application quits normally, shutting down the server as well.
Not sure if this is the most elegant solution, but it works. If someone else has a way to achieve this without the DevServer helper-class, please do post it!
Also, there might be a more elegant way to check whether the AppEngine server is running, other than pinging it with a URL connection as I did above.
Note: The AppEngine Dev Server registers its own URLStreamHandlerFactory to automatically map Http(s)URLConnections onto AppEngine's URL-fetch infrastructure. This means that you get errors complaining about missing url-fetch capabilities if you then use HttpURLConnections in your client code. Luckily, this can be fixed in two way as described here: Getting a reference to Java's default http(s) URLStreamHandler.
If you definitely want to use appengine, then you will end up creating two projects, one on appengine and another a standalone (no servlets). In this case you can take a look at appengine Remote API

How do I load test data into my GWT Widget?

I am using eclipse with the Google Toolkit and I have created a widget with a listbox, vertical split panel and a couple of buttons. What I am trying to do is have a list of files in a local directory listed in the listbox and I want to be able to click on a file and have it displayed in the top part of the split panel. I found out the hard way about browsers and file IO and not being able to use java.io.File.
What are my options? Can I put the data files inside a jar or something and have the widget read it in that way? I need to do this as a test run, to implement an new feature with working with the data. It's not going to be any kind of final server hosted application, I am not concerned about how the actual files will be loaded in the future.
Any suggestions would be greatly appreciated.
Respectfully,
DemiSheep
If you just need a hard-coded list of values to visually test your widget, you can simply put these values in a String array and load it from there. Or you can http GET the strings from a server using RequestBuilder. You can keep a simple file (CSV, XML, JSON etc.) in your war directory and load this file using Request builder.
Example code from GWT developer guide:
import com.google.gwt.http.client.*;
...
String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
Make sure you inherit HTTP module:
<inherits name="com.google.gwt.http.HTTP" />
Create testcases with JUnit!
This is the official Google site describing Testing with JUnit and varios test methods: Google Web Toolkit: Testing. You definitly find a solution here^^
As it comes to GWT, there is no such thing sent to a browser as a .jar-file.
The easiest thing to fetch the file would be to
put the files on a server
fetch them via a http-call
Remember the same-origin-policy that applies to GWT as it is underlying all javascript-Restrictions

Categories