So I am trying to use Mondrian 3.14 in Java 1.8, so I did something like this :
String catalogFilePath = "<path>/mdx_schema.xml";
String connectUrl = "Provider=mondrian;" +
"Jdbc=jdbc:postgresql://example.com:5432/database?user=user&password=pass;" +
"JdbcDrivers=org.postgresql.Driver;" +
"Catalog=file:" + catalogFilePath + ";";
Connection connection = DriverManager.getConnection(connectUrl, null);
String qs = "<query>";
Query q = connection.parseQuery(qs);
Result r = connection.execute(q);
However, as stated here, Connection::execute is deprecated :
Deprecated. This method is deprecated and will be removed in mondrian-4.0. It operates by internally creating a statement. Better to use olap4j and explicitly create a statement.
So, what should I use in olap to execute the query ?
So I actually found the answer here :
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import org.olap4j.CellSet;
import org.olap4j.OlapConnection;
import org.olap4j.OlapStatement;
import org.olap4j.OlapWrapper;
import org.olap4j.layout.RectangularCellSetFormatter;
import java.sql.SQLException;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("mondrian.olap4j.MondrianOlap4jDriver");
String catalogFilePath = "<path>/mdx_schema.xml";
String connectUrl = "jdbc:mondrian:" +
"Jdbc=jdbc:postgresql://example.com:5432/database?user=user&password=pass;" +
"JdbcDrivers=org.postgresql.Driver;" +
"Catalog=file:" + catalogFilePath + ";";
Connection connection = DriverManager.getConnection(connectUrl);
OlapWrapper wrapper = (OlapWrapper) connection;
OlapConnection olapConnection = wrapper.unwrap(OlapConnection.class);
OlapStatement statement = olapConnection.createStatement();
String qs = "<query>";
CellSet cellSet = statement.executeOlapQuery(qs);
RectangularCellSetFormatter formatter = new RectangularCellSetFormatter(false);
PrintWriter writer = new PrintWriter(System.out);
formatter.format(cellSet, writer);
writer.flush();
connection.close();
}
Related
I am executing my code using shell scripting file and as per requirement if i will not pass parameter then my code will execute on my local machine and if i will pass parameter with shell scripting then code should be execute on browser stack. If i am executing with parameter then my code is working fine . But if i am not passing parameter in shell scripting then unable to launch chrome browser because in If condition driver is null. This is my base class
When i am executing shell script without parameter then my execution is going in If condition but unable to launch chrome browser because driver variable is not initialized in if condition . if i am printing driver value then it is showing null.
package com.epath.smoketest.tests;
/**
* Class: Base
* Author: D Albanese
* Creation Date: 4/5/2017
*/
import org.junit.Rule;
import org.junit.rules.ExternalResource;
import org.openqa.selenium.WebDriver;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Base {
//-Browser capability passed by CLI argument.
private static String sBrowser;
//-Browser version passed by CLI argument.
private static String sBversion;
//-OS capability passed by CLI argument.
private static String sOsName;
//-OS version capability passed by CLI argument.
private static String sOsVersion;
//-Passing input folder name by CLI argument.
public String sFolderName = "resources";
public static String getExecutionPath;
public static String getResourcePath;
public static WebDriver driver;
public Base(String sBrowser, String sBversion, String sOsName, String sOsVersion,String sFolderName) {
this.sBrowser = sBrowser;
this.sBversion = sBversion;
this.sOsName = sOsName;
this.sOsVersion = sOsVersion;
if(null != sFolderName && ! sFolderName.trim().equals("")) {
this.sFolderName = sFolderName;
}
}
//-Utilizing ExternalResource rule to preserve functionality of #Before and #After annotations in tests
//-ExternalResource rule has before and after methods that execute prior to methods annotated with #Before and #After
#Rule
public ExternalResource resource = new ExternalResource() {
#Override
protected void before() throws Throwable {
//-Use this for local testing
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browser", sBrowser);
caps.setCapability("browser_version", sBversion);
caps.setCapability("os", sOsName);
caps.setCapability("os_version", sOsVersion);
caps.setCapability("folder_name", sFolderName);
caps.setCapability("browserstack.local", "true");
if(sBrowser.length() == 0 && sBversion.length() == 0 && sOsName.length() == 0 && sOsVersion.length() == 0)
{
System.out.println("Inside If Condition ");
//-Load the properties
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream(System.getProperty("user.home") +
"/epath/services/tests/resources/AutomationData.properties");
prop.load(input);
// getResourcePath=prop.getProperty("resources_path");
getExecutionPath = prop.getProperty("local_resources_path");
System.out.println("Print Execution Path :- " +getExecutionPath);
System.out.println("Print Driver Path :- " + driver);
System.setProperty("webdriver.chrome", "\\\\192.168.10.21\\volume1\\ngage_dev\\engineering\\ngage\testing\\automated\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
} else {
//-Load the properties
System.out.println("Inside else Condtions ");
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream(System.getProperty("user.home") +
"/epath/services/tests/resources/AutomationData.properties");
prop.load(input);
getResourcePath=prop.getProperty("resources_path");
getExecutionPath = prop.getProperty("resources_path")+sFolderName;
//-Get USERNAME and AUTOMATE_KEY of browser stack
String browserStackUsername = prop.getProperty("browser_stack_username");
String browserStackAutomateKey = prop.getProperty("browser_stack_automate_key");
String URL = "https://" + browserStackUsername + ":" +
browserStackAutomateKey + "#hub-cloud.browserstack.com/wd/hub";
driver = new RemoteWebDriver(new URL(URL), caps);
//-Load the URL to be tested
driver.get(prop.getProperty("test_url"));
//-For local file uploads
((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
}
}
#Override
protected void after() {
driver.quit();
}
};
public String getAutomationInputDataPath() {
return this.getExecutionPath;
}
public static String getResourcePathFromPropertiesfile() {
return getResourcePath;
}
}
And this is my test case class where i am calling base class(above class)
public class AddRegisterLAs extends Base {
private Login login;
private Navigation go;
private LearningActivityAdd addLa;
private ImageAdd addImage;
private DocumentAdd addDocument;
private VideoAdd addVideo;
private AudioAdd addAudio;
private LinkAdd addLink;
private CustomAdd addCustom;
private AiccAdd addAicc;
private ScormAdd addScorm;
private RegistrationCreate createRegistration;
private Utils utils;
private GetVersion getVersion;
public AddRegisterLAs() {
super(System.getProperty("browser"),System.getProperty("browser_version"),System.getProperty("os"),System.getProperty("ov"),System.getProperty("folderName"));
}
#Before
public void setUp() {
login = new Login(driver);
go = new Navigation(driver);
addLa = new LearningActivityAdd(driver);
addImage = new ImageAdd(driver);
addDocument = new DocumentAdd(driver);
addVideo = new VideoAdd(driver);
addAudio = new AudioAdd(driver);
addLink = new LinkAdd(driver);
addCustom = new CustomAdd(driver);
addAicc = new AiccAdd(driver);
addScorm = new ScormAdd(driver);
utils = new Utils();
getVersion = new GetVersion(driver);
createRegistration = new RegistrationCreate(driver);
}
#Test
public void Shallow() throws Exception {
//utils.logAndPrint("AddRegisterLAs");
int maxLAs = 1000;
int maxRegs = 1000;
//-Print to screen to create log. Log can be copied and pasted to Word document or elsewhere as needed.
System.out.println("\n" + "---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("Adding and Registering Learning Activities Automation"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
//-Load the properties
System.out.println("\n" + "---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("Read in PROPERTIES file"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
Properties prop = new Properties();
InputStream input = null;
At first kindly check that you have access to that driver path which you mentioned inside if.
i got the code snippet of adding a defect to defect suite from forums.
However, my requirement is to pull defect from defect suite and i am not aware of defect suite information.
Is there a way to pull collection of defect suites and defects from it.
Here is the sample code snippet to add defect to defect suite.
> import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.CreateRequest;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.request.UpdateRequest;
import com.rallydev.rest.response.CreateResponse;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.response.UpdateResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import com.rallydev.rest.util.Ref;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class addDefectToSuite {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#company.com";
String password = "secret";
String wsapiVersion = "v2.0";
String projectRef = "/project/12352608219";
String workspaceRef = "/workspace/12352608129";
String applicationName = "Create defect, add to a defectsuite";
RallyRestApi restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(applicationName);
QueryRequest defectSuiteRequest = new QueryRequest("DefectSuite");
defectSuiteRequest.setFetch(new Fetch("FormattedID","Name", "Defects"));
defectSuiteRequest.setWorkspace(workspaceRef);
defectSuiteRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "DS1"));
QueryResponse defectSuiteQueryResponse = restApi.query(defectSuiteRequest);
JsonObject defectSuiteJsonObject = defectSuiteQueryResponse.getResults().get(0).getAsJsonObject();
System.out.println("defectSuiteJsonObject" + defectSuiteJsonObject);
String defectSuiteRef = defectSuiteJsonObject.get("_ref").getAsString();
int numberOfDefects = defectSuiteJsonObject.getAsJsonObject("Defects").get("Count").getAsInt();
System.out.println(defectSuiteJsonObject.get("Name") + " ref: " + defectSuiteRef + "number of defects: " + numberOfDefects + " " + defectSuiteJsonObject.get("Defects"));
try {
JsonObject defect = new JsonObject();
defect.addProperty("Name", "bad defect 668");
CreateRequest createRequest = new CreateRequest("defect", defect);
CreateResponse createResponse = restApi.create(createRequest);
if (createResponse.wasSuccessful()) {
JsonObject defectJsonObject = createResponse.getObject();
String defectRef = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("Created %s", defectRef));
JsonObject defectSuitesOfThisDefect = (JsonObject) defectJsonObject.get("DefectSuites");
int numberOfSuites = defectSuitesOfThisDefect.get("Count").getAsInt();
System.out.println("number of defect suites this defect is part of: " + numberOfSuites);
QueryRequest defectSuitesOfThisDefectRequest = new QueryRequest(defectSuitesOfThisDefect);
JsonArray suites = restApi.query(defectSuitesOfThisDefectRequest).getResults();
System.out.println("suites: " + suites);
suites.add(defectSuiteJsonObject);
System.out.println("suites after add: " + suites);
//Update defect: add to defectsutites collection
JsonObject defectUpdate = new JsonObject();
defectUpdate.add("DefectSuites", suites);
UpdateRequest updateDefectRequest = new UpdateRequest(defectRef,defectUpdate);
UpdateResponse updateResponse = restApi.update(updateDefectRequest);
if (updateResponse.wasSuccessful()) {
System.out.println("Successfully updated defect: " + defectJsonObject.get("FormattedID"));
}
else {
String[] updateErrors;
updateErrors = createResponse.getErrors();
System.out.println("Error");
for (int i=0; i<updateErrors.length;i++) {
System.out.println(updateErrors[i]);
}
}
} else {
System.out.println("error");
}
} finally {
restApi.close();
}
}
}
The Defect object has a DefectSuites collection, so you could just query for all defects where DefectSuites contains your specified DefectSuite:
QueryRequest defectsRequest = new QueryRequest("Defect");
defectsRequest.setFetch(new Fetch("FormattedID","Name"));
defectsRequest.setQueryFilter(new QueryFilter("DefectSuites", "contains", defectSuiteRef));
QueryResponse defectsResponse = restApi.query(defectsRequest);
Or, you can come at it from the other way by querying the Defects collection directly on your DefectSuite in your original code above:
JsonObject defectsCollection = defectSuiteJsonObject.getAsJsonObject("Defects");
QueryRequest defectsRequest = new QueryRequest(defectsCollection);
defectSuiteRequest.setFetch(new Fetch("FormattedID","Name"));
QueryResponse defectsResponse = restApi.query(defectsRequest);
I wrote a java program about transfering a txt file to a sqlite db but it takes really more time there are about 83000 data (200 data takes about 1 minute).
how can i increase transfering speed. İ tried adding arraylist than get but its not change
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class NewMain {
public static Connection connect() {
Connection conn = null;
try {
String url1 = "jdbc:sqlite:c:/Users/sozdemir/Desktop/sozluk.db";
conn = DriverManager.getConnection(url1);
String sql1 = "CREATE TABLE IF NOT EXISTS KELIMELER (Kelime PRIMARYKEY NOT NULL);";
Statement s = conn.createStatement();
s.execute(sql1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return conn;
}
public void Verigir(String kelime){
String sql = "INSERT INTO KELIMELER (kelime) VALUES(?)";
try (Connection conn = this.connect();
PreparedStatement statement = conn.prepareStatement(sql)
){
statement.setString(1, kelime);
statement.executeUpdate();
} catch (Exception e) {
}
}
public static void main(String[] args) throws IOException {
/* connect();*/
NewMain app = new NewMain();
String kelime = null;
BufferedReader in = null;
int adet;
adet= 0;
in = new BufferedReader(new FileReader("C://Users//sozdemir//Desktop//ozluk.txt"));
while ((kelime=in.readLine()) !=null) {
app.Verigir(kelime);
adet +=1;
System.out.println(81742 - adet);
}
}
}
Some hints:
Use a single prepareStatement
Put everything inside a transaction
Use PRAGMA synchronous = OFF and PRAGMA journal_mode = OFF
This will give you very fast inserts.
I want to debug Lucene token filters and see results. How is it possible to apply a token filter to a token stream in order to see result?
(using Lucene 4.10.3)
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
public class TokenFilterExample {
public static void main(String[] args) throws IOException {
// 1] Create token stream
StringReader r = new StringReader("Hello World");
StandardTokenizer s = new StandardTokenizer(r);
// Create lower-case token filter
LowerCaseFilter f = new LowerCaseFilter(s);
// Print result
System.out.println(??????);
// close
f.close();
s.close();
}
}
The solution is this:
// Print result
f.reset();
Iterator it = f.getAttributeClassesIterator();
while (f.incrementToken()) {
System.out.println(f
.getAttribute(CharTermAttribute.class));
}
Is it possible to try out the new PHREAKS algorithm but using the conventional API from Drools 5.5
* EDIT: to make the question more precise *
conventional 5.5 API
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.Resource;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
instead new Drools 6 API
import org.kie.api.KieBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieScanner;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.conf.ClockTypeOption;
It's also possible with the 5 knowledge api in drools 6.0+ by setting a rule engine property:
drools.ruleEngine = phreak
Here's how you set in the 5 knowledge api:
knowledgeBaseConfiguration.setProperty("drools.ruleEngine", "phreak");
I'm copy-pasting the simplest Java code for launching a 6.0 session. Everything else - fact insertion, global definitions,... works using the same API, only with KieSession.
package simple;
import java.io.FileInputStream;
import org.kie.api.KieServices;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Results;
import org.kie.api.builder.Message;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.KieContainer;
public class Main {
private KieSession kieSession;
public void build() throws Exception {
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
FileInputStream fis = new FileInputStream( "simple/simple.drl" );
kfs.write( "src/main/resources/simple.drl",
kieServices.getResources().newInputStreamResource( fis ) );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
System.out.println( results.getMessages() );
throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
kieServices.newKieContainer( kieServices.getRepository().getDefaultReleaseId() );
KieBase kieBase = kieContainer.getKieBase();
kieSession = kieContainer.newKieSession();
}
public void exec(){
kieSession.fireAllRules();
}
public static void main( String[] args ) throws Exception {
Main m = new Main();
m.build();
m.exec();
}
}
Yes, most of the API is still supported. You will need to add the knowledge-api jar to your classpath (https://github.com/droolsjbpm/drools/tree/master/knowledge-api-legacy5-adapter).
The main difference is that Drools 6 no longer uses PKG for deployment. It uses mavenized kjars now. If you are not using PKG files (built by guvnor in Drools 5), you should be fine.
the working code to preserve rules and facts by using the same KieSession and deploy Jars, the code is adapted from here https://github.com/droolsjbpm/drools/blob/master/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java.
package test.drools;
import java.io.UnsupportedEncodingException;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.ReleaseId;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class Playground4 {
private String newline = System.getProperty("line.separator");
public static void main(String[] args) {
Playground4 pg = new Playground4();
try {
pg.doRules();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private String generateDRLString(int start, int end) {
StringBuilder sb;
sb = new StringBuilder();
sb.append("package performance.drools;" + newline);
for (int i = start; i <= end; i++) {
sb.append("rule \"R" + i + "\"" + newline);
sb.append("when" + newline);
sb.append("then" + newline);
sb.append("System.out.println(\"rule" + i + " fired!\");" + newline);
sb.append("end" + newline);
}
return sb.toString();
}
int count = 1;
public void doRules() throws UnsupportedEncodingException {
KieServices kieServices = KieServices.Factory.get();
KieBaseConfiguration kieBaseConf = kieServices.newKieBaseConfiguration();
//kieBaseConf.setProperty("drools.ruleEngine", "phreak");
kieBaseConf.setProperty("drools.ruleEngine", "phreak");
ReleaseId releaseId;
KieModule kieModule;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
// create session without rules for version 1.1.0
kieModule = createAndDeployJar(releaseId);
KieContainer kieContainer = kieServices.newKieContainer(kieModule
.getReleaseId());
kieContainer.newKieBase(kieBaseConf);
KieSession kieSession = kieContainer.newKieSession();
// Create an in-memory jar for version 1.2.0
count++;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
kieModule = createAndDeployJar(releaseId, generateDRLString(1, 3));
kieContainer.updateToVersion(releaseId);
kieSession.insert(new Object());
// Create an in-memory jar for version 1.3.0
count++;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
kieModule = createAndDeployJar(releaseId, generateDRLString(4, 12));
kieContainer.updateToVersion(releaseId);
kieSession.fireAllRules();
System.out.println(kieSession.getFactCount());
}
public KieModule createAndDeployJar(ReleaseId releaseId, String... drls) {
KieServices kieServices = KieServices.Factory.get();
byte[] jar = createKJar(kieServices, releaseId, null, drls);
return deployJar(kieServices, jar);
}
KieFileSystem kfs;
public byte[] createKJar(KieServices ks, ReleaseId releaseId,
String pom, String... drls) {
if (kfs == null) kfs = ks.newKieFileSystem();
if (pom != null) {
kfs.write("pom.xml", pom);
} else {
kfs.generateAndWritePomXML(releaseId);
}
for (int i = 0; i < drls.length; i++) {
if (drls[i] != null) {
kfs.write("src/main/resources/r" + 10 * count + i + ".drl", drls[i]);
}
}
KieBuilder kb = ks.newKieBuilder(kfs).buildAll();
if (kb.getResults()
.hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
for (org.kie.api.builder.Message result : kb.getResults()
.getMessages()) {
System.out.println(result.getText());
}
return null;
}
InternalKieModule kieModule = (InternalKieModule) ks.getRepository()
.getKieModule(releaseId);
byte[] jar = kieModule.getBytes();
return jar;
}
public KieModule deployJar(KieServices ks, byte[] jar) {
// Deploy jar into the repository
Resource jarRes = ks.getResources().newByteArrayResource(jar);
KieModule km = ks.getRepository().addKieModule(jarRes);
return km;
}
}