Zookeeper connection in java - java

The below code(not mine) is supposed to check the connection status of a zookeeper by using the znode_exists() method. I want to use it at a producerAPI before a message publish. But i am getting an error at defining the ZooKeeperConnection object. I have added the possible classes and libraries.
import java.io.IOException;
//import org.apache.zookeeper.*; adding this doesn't help
import org.apache.zookeeper.ZooKeeperMain;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.data.Stat;
public class ZKExists {
private static ZooKeeper zk;
private static ZooKeeperConnection conn; // Object cannot be resolve to a type
// Method to check existence of znode and its status, if znode is available.
public static Stat znode_exists(String path) throws
KeeperException,InterruptedException {
return zk.exists(path, true);
}
public static void main(String[] args) throws InterruptedException,KeeperException {
String path = "/Znode_path"; // Assign znode to the specified path
try {
ZooKeeperConnection conn = new ZooKeeperConnection();
zk = conn.connect("localhost");
Stat stat = znode_exists(path); // Stat checks the path of the znode
if(stat != null) {
System.out.println("Node exists and the node version is " +
stat.getVersion());
} else {
System.out.println("Node does not exists");
}
} catch(Exception e) {
System.out.println(e.getMessage()); // Catches error messages
}
}
}
Which library am i missing to make the object valid ?

Related

Jackcess: getTable(aName) is null while getTableNames yields aName (among others)

I am new to Jackcess (downloaded it today, version 4.0.4) and immediately running into troubles: Would anybody know, why db.getTable(aName) returns null whereas db.getTableNames() shows me that very aName among others?
Note that I am running it jointly with Apache Commons Lang 3.12.0 because I could not find Apache Commons Lang 3.10 as requested in the dependencies of Jackcess 4.0.4. But would this explain the behavior?
In the code below, "dbfile" and "tble" should still be defined according to your database. Unfortunately I cannot release my data base as it is proprietary. I am getting null from db.getTable(aName) no matter what the OPTION is. Obviously, any the code with OPTION!=1 is a work-around to find out whether the corresponding table name is within the database. When I run the code with OPTION=0, the output is:
That is it: [my table name]
Your table is null.
I would appreciate if you could share your ideas so I can make this example work.
import java.io.IOException;
import java.io.File;
import java.util.Set;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Table;
public class JackcessTrial {
private static final int OPTION = 0;
public JackcessTrial() {
super();
}
public void openSourceTable(File dbFile, String tbleName) {
Database db = null;
Table myTable = null;
try {
db = new DatabaseBuilder(dbFile).setReadOnly(true).open();
if (db==null) {
System.out.println("No database found.");
return;
}
if (OPTION==1) {
myTable = db.getTable(tbleName);
} else {
Set<String> names = db.getTableNames();
for(String name : names) {
if (name.equals(tbleName)) {
System.out.println("That is it: "+name);
myTable = db.getTable(name);
break;
}
}
}
if (myTable == null) {
System.out.println("Your table is null.");
db.close();
return;
}
System.out.println("Got your table!");
db.close();
} catch(Exception e) {
e.printStackTrace();
db = null;
}
}
public static void main(String args[]) throws IOException {
File dbfile = ...;
String tble = ...;
JackcessTrial test = new JackcessTrial();
test.openSourceTable(dbfile, tble);
}
}

How can i check the proxy settings done by 'System.setProperty' in Java?

i'm developing an Java application that will be used to launch some Test Automation scripts on dedicated environment.
It is required to set also the proxy when necessary.
I developed a class that will be used to configure the proxy settings once a properties read from external contains the flag 'ENABLE_PROXY' equals 'True'.
Following is my snippet code:
package proxy;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class ProxyConfiguration {
private static String proxyHost;
private static String proxyPort; //80 if it isn't provided
private static String nonProxyHosts;
private static String protocolType;
public static boolean flagProxy;
//Set method used to read the flag Proxy
public static boolean isProxyEnabled(Properties myPropertiesFile) {
flagProxy = Boolean.parseBoolean(myPropertiesFile.getProperty("ENABLE_PROXY").toLowerCase());
return flagProxy;
}
public static String getProxyHost() {
return proxyHost;
}
//Set method used to read the Proxy host from properties
public static void setProxyHost(Properties myPropertiesFile) {
ProxyConfiguration.proxyHost = myPropertiesFile.getProperty("PROXY_HOST");
}
public static String getProxyPort() {
return proxyPort;
}
//Set method used to read the Proxy port from properties
public static void setProxyPort(Properties myPropertiesFile) {
ProxyConfiguration.proxyPort = myPropertiesFile.getProperty("PROXY_PORT");
}
public static String getNonProxyHosts() {
return nonProxyHosts.replace(",", "|");
}
//Set method used to read the exception from properties
public static void setNonProxyHosts(Properties myPropertiesFile) {
ProxyConfiguration.nonProxyHosts = myPropertiesFile.getProperty("PROXY_EXCEPTION");
}
public static String getProtocolType() {
return protocolType;
}
//Set method used to read the exception from properties
public static void setProtocolType(Properties myPropertiesFile) {
ProxyConfiguration.protocolType = myPropertiesFile.getProperty("PROTOCOL_TYPE");
}
//Method used to set the Proxy settings on system
public static void setProxyConfiguration(Properties myPropertiesFile) {
try {
ProxyConfiguration.setProtocolType(myPropertiesFile);
ProxyConfiguration.setProxyHost(myPropertiesFile);
ProxyConfiguration.setProxyPort(myPropertiesFile);
ProxyConfiguration.setNonProxyHosts(myPropertiesFile);
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty(ProxyConfiguration.getProtocolType() +".proxyHost", ProxyConfiguration.getProxyHost());
System.setProperty(ProxyConfiguration.getProtocolType() +".proxyPort", ProxyConfiguration.getProxyPort());
boolean exceptions = ProxyConfiguration.getNonProxyHosts().isEmpty();
if(!exceptions) {
System.setProperty(ProxyConfiguration.getProtocolType() +".nonProxyHosts", ProxyConfiguration.getNonProxyHosts());
}
try {
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();
//return true;
} catch (Exception e) {
//return false;
}
} catch (Exception e) {
System.err.println("Si รจ verificato un errore nella setProxyConfiguration: ");
String exc = ExceptionUtils.getStackTrace(e);
System.err.println(exc);
System.exit(-1);
}
}
}
How can i check if the proxy settings are set correctly?
I tried also to used the command prompt of my local machine and launch the follwing command:
netsh winhttp show proxy
but i receive:
Current WinHTTP proxy settings:
Direct access (no proxy server).
The properties read are:
PROTOCOL_TYPE=http
PROXY_HOST=webcache.mydomain.com (it is an example found on Java Networking)
PROXY_PORT=8080
PROXY_EXCEPTION=
Thanks for supporting!

AccessControlException while trying to create a directory on Azure

I'm trying this to Create Directory in azureDataLake using azure data lake dependency
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-data-lake-store-sdk</artifactId>
<version>2.1.5</version>
</dependency>
Using the following method:
private ADLStoreClient client;
public boolean createDirectory(String path) {
try {
// create directory
client.createDirectory(path);
} catch (ADLException ex) {
printExceptionDetails(ex);
return false;
} catch (Exception ex) {
log.error(" Exception in createDirectory : {}", ex);
return false;
}
return true;
}
and I got this exception:
Error creating directory /gx-zweappdhd004/home/azhdipaasssh2/ADH/Compta/1458/1533632735200/RAPPORTS/
Operation MKDIRS failed with HTTP403 : AccessControlException
I checked the permission and I have all of them, so it's not related to the permissions.
Update:
To be more specefic the problem happening inside the method isSuccessfulResponse(), and exactlly in this line HttpTransport.java#L137 because the httpResponseCode equals to 403, can anybody explain this.
Update2:
I found that this line is returning the 403 status : HttpTransport.java#L288, I also tried to evaluate conn.getErrorStream().read() and I got this stream is closed, FYI this is bug occures sometimes and not always.
I didn't reproduce your issue,you could refer to my working code:
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
import com.microsoft.azure.datalake.store.ADLStoreClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CreateDirectory {
static ADLStoreClient client;
public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
setup();
}
public static void setup() throws IOException, ExecutionException, InterruptedException {
String APP_ID = "<your app id>";
String APP_SECRET = "<your app secret>";
String dirName = "/jay";
String StoreAcct = "jaygong";
String authority = "https://login.microsoftonline.com/<your tenant id>";
String resourcUrl = "https://management.core.windows.net/";
ExecutorService service = Executors.newFixedThreadPool(1);
AuthenticationContext context = new AuthenticationContext(authority, true, service);
// Acquire Token
Future<AuthenticationResult> result = context.acquireToken(
resourcUrl,
new ClientCredential(APP_ID, APP_SECRET),
null
);
String token = result.get().getAccessToken();
System.out.println(token);
String account = StoreAcct + ".azuredatalakestore.net";
client = ADLStoreClient.createClient(account, token);
client.createDirectory(dirName);
System.out.println("finish.....");
}
}
Don't forget grant access ADL permissons to your client.
Hope it helps you.

Exception thrown when trying to load Pentaho report through java program

This code was mostly taken from Pentaho's website on sample programs. The goal is to use their API to generate HTML output with a Pentaho report.
The report was created with Pentaho 3.5.0-RC2
The version of jars I am using are the following:
pentaho-reporting-engine-classic-core-3.5.0-RC2.jar
libloader-1.1.1.jar
libbase-1.1.1.jar
The exception I am getting is the following:
org.pentaho.reporting.libraries.resourceloader.ContentNotRecognizedException: None of the selected factories was able to handle the given data: ResourceKey{schema=org.pentaho.reporting.libraries.resourceloader.loader.URLResourceLoader, identifier=file:/C:/Users/elias.kopsiaftis/workspace_experimental/TestPentahoReport/bin/Test.prpt, factoryParameters={}, parent=null}
at org.pentaho.reporting.libraries.resourceloader.DefaultResourceManagerBackend.create(DefaultResourceManagerBackend.java:295)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:387)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:342)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.createDirectly(ResourceManager.java:205)
at ReportTester.getReportDefinition(ReportTester.java:74)
at ReportTester.getReport(ReportTester.java:25)
at ReportTester.main(ReportTester.java:84)
java.lang.NullPointerException
at ReportTester.getReport(ReportTester.java:26)
at ReportTester.main(ReportTester.java:84)
And finally, the code snippet!
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.io.*;
import org.pentaho.reporting.engine.classic.core.DataFactory;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlReportUtil;
import org.pentaho.reporting.libraries.resourceloader.Resource;
import org.pentaho.reporting.libraries.base.util.StackableException;
import org.pentaho.reporting.libraries.resourceloader.ResourceException;
import org.pentaho.reporting.libraries.resourceloader.ResourceManager;
public class ReportTester {
private String reportName = "FormCompleteUsagePerPartnerByMonth.prpt";
private String reportPath = "";
public void getReport() {
try {
final MasterReport report = getReportDefinition();
report.getParameterValues().put("partner", "");
report.getParameterValues().put("startingdate", "2015-03-01");
report.getParameterValues().put("endingdate", "2015-03-05");
HtmlReportUtil.createStreamHTML(report, System.out);
} catch(Exception e) {
e.printStackTrace();
}
}
private MasterReport getReportDefinition() {
try {
// Using the classloader, get the URL to the reportDefinition file
final ClassLoader classloader = this.getClass().getClassLoader();
final URL reportDefinitionURL = classloader.getResource(reportPath + reportName);
if(reportDefinitionURL == null) {
System.out.println("URL was null");
}
// Parse the report file
final ResourceManager resourceManager = new ResourceManager();
resourceManager.registerDefaults();
final Resource directly = resourceManager.createDirectly(reportDefinitionURL, MasterReport.class);
return (MasterReport) directly.getResource();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
ReportTester rt = new ReportTester();
rt.getReport();
}
}
Any advice on this would be much appreciated as I have been scratching my head on this all day. Thanks in advance!

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