I want to connect Android to an owl file using the code below, but this line
model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_TRANS_INF)
throws an exception.
public class OntoQuery {
private Model model;
public OntoQuery(String inputFileName) {
model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_TRANS_INF);
InputStream in = FileManager.get().open(inputFileName);
if(in == null) {
throw new IllegalArgumentException("File: " + inputFileName + " not found");
} else {
model.read(in, "RDF/XML");
}
}
public String executeQuery(String queryString) throws UnsupportedEncodingException {
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, this.model);
Throwable var5 = null;
String fieldValue;
try {
ResultSet results = qe.execSelect();
ByteArrayOutputStream go = new ByteArrayOutputStream();
ResultSetFormatter.out(go, results, query);
fieldValue = new String(go.toByteArray(), "UTF-8");
} catch (Throwable var15) {
var5 = var15;
throw var15;
} finally {
if(qe != null) {
if(var5 != null) {
try {
qe.close();
} catch (Throwable var14) {
//var5.addSuppressed(var14);
}
} else {
qe.close();
}
}
}
return fieldValue;
}
}
Related
Problem is the following: I am saving hashed password for a school project, however i am stuck on the syntax for the SQL statement to replace the data if it is already present. The table will only need to store a single username/password combination.
public class DatabaseManager {
String dbPath = "jdbc:sqlite:test.db";
public DatabaseManager () {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection(dbPath);
if (conn != null) {
System.out.println("Connected to the database");
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
// Setting up database
databaseSetup(conn);
boolean tempInsertion = databaseInsert("pancake", "house", conn);
// Inserting data
if (tempInsertion) {
System.out.println("Data insertion failed");
}
// Retrieving data
List<String> retrievedData = databaseSelect(conn);
if (retrievedData == null) {
System.out.println("Data extraction failed");
}
else {
System.out.println(retrievedData.size());
}
conn.close();
}
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private boolean databaseInsert(String username, String password, Connection conn) {
String sqlInsert = "INSERT OR REPLACE INTO login(username, password) VALUES(?,?)";
PreparedStatement prepStatement;
try {
prepStatement = conn.prepareStatement(sqlInsert);
prepStatement.setString(1, encrypt(username));
prepStatement.setString(2, encrypt(password));
prepStatement.executeUpdate();
} catch (SQLException e) {
return false;
}
return true;
}
private List<String> databaseSelect(Connection conn) {
List<String> tempList = new ArrayList<String>();
String sqlSelect = "SELECT * FROM login";
Statement stmt;
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlSelect);
tempList.add(rs.getString("username"));
tempList.add(rs.getString("password"));
int columnsNumber = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rs.getMetaData().getColumnName(i));
}
System.out.println("");
}
} catch (SQLException e) {
return null;
}
return tempList;
}
private void databaseSetup( Connection conn) {
String sqlExpression = "CREATE TABLE login (username varchar(255), password varchar(255))";
try {
Statement statement = conn.createStatement();
statement.execute(sqlExpression);
} catch (SQLException e) {}
}
private String encrypt(String string) {
try {
MessageDigest exampleCrypt = MessageDigest.getInstance("SHA1");
exampleCrypt.reset();
exampleCrypt.update(string.getBytes("UTF-8"));
return convertByte(exampleCrypt.digest());
}
catch(NoSuchAlgorithmException e) {
System.out.println("Error, cannot encrypt string");
e.printStackTrace();
}
catch(UnsupportedEncodingException e) {
System.out.println("Error, cannot encrypt string");
e.printStackTrace();
}
return null;
}
private static String convertByte(final byte[] hash) {
Formatter formatter1 = new Formatter();
for (byte i : hash) {
formatter1.format("%02x", i);
}
String encryptedData = formatter1.toString();
formatter1.close();
return encryptedData;
}
}
The problem as stated, is that i'd like to only store a single password/username combination at a time, as a hash. However, when this happens it duplicates the hash combination, instead of replacing it.
The controller code :
#GetMapping("/show/{id}")
public ResponseEntity<Student> findId(#PathVariable Student student) throws Exception {
Student showId = studentService.findId(student);
return new ResponseEntity<Student>(showId, HttpStatus.OK);
}
needs to return an object for a path id
Repository code:
public Student findId(Student student) throws Exception {
Connection connect = null;
Statement st = null;
ResultSet rec = null;
PreparedStatement pre = null;
List<Student> userlist = new ArrayList<Student>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +"?user=root&password=root&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
connect.setAutoCommit(false);
st = connect.createStatement();
String sql = "SELECT * FROM student WHERE studentid = ? ";
pre = connect.prepareStatement(sql);
pre.setLong(1, student.getId());
pre.executeQuery();
} catch (Exception e) {
if (connect != null) {
try {
st.close();
connect.rollback();
} catch(SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (st != null) {
try {
st.close();
connect.setAutoCommit(true);
} catch(SQLException e) {
e.printStackTrace();
}
}
}
try {
connect.close();
} catch (SQLException e) {
e.printStackTrace();
}
return student;
}
ResultSet result = pre.executeQuery();
while (result.next()) {
long id = resultSet.getLong("studentId");
String name = resultSet.getString("name");
// another fields
return new Student(id, name);
}
And for controller if need only id (#PathVariable Long id) is more light.
Student response = studentService.findById(id);
return ResponseEntity.ok(response);
I connect to Hive and get id's of my data from row of table. Problems does not happens, when I connect to hive, send request and get response. But when i get id's from ResultSet i get an exception: org.apache.thrift.transport.TTransportException: SASL authentication not complete. Why does this exception arise and what needs to be done to avoid it? Sorry for my bad english.
It's my subsidiary class to create hive connection and send requests:
public class HiveDataSearcher implements AutoCloseable {
private static final String hiveDriverName = "org.apache.hive.jdbc.HiveDriver";
static {
try {
Class.forName(hiveDriverName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private Connection hiveConnection;
private String tableName;
private String whereBody;
public HiveDataSearcher(String url, String login, String password) {
try {
hiveConnection = DriverManager.getConnection(url, login, password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
this.tableName = "";
this.whereBody = "";
}
public HiveDataSearcher(Connection hiveConnection) {
Objects.requireNonNull(hiveConnection, "hiveConnection");
this.hiveConnection = hiveConnection;
this.tableName = "";
this.whereBody = "";
}
public String getTableName() {
return tableName;
}
public HiveDataSearcher setTableName(String tableName) {
Objects.requireNonNull(tableName, "tableName");
this.tableName = tableName;
return this;
}
public String getWhereBody() {
return whereBody;
}
public HiveDataSearcher setWhereBody(String whereBody) {
Objects.requireNonNull(whereBody, "whereBody");
this.whereBody = whereBody;
return this;
}
public ResultSet select(String ... selectParams) {
return select(Arrays.asList(selectParams));
}
public ResultSet select(Iterable<String> selectParams) {
String request = prepareRequest(selectParams);
ResultSet response;
try {
response = hiveConnection
.createStatement()
.executeQuery(request);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return response;
}
private String prepareRequest(Iterable<String> selectParams) {
return new StringBuilder()
.append("select").append(' ').append(selectParamsToHiveFormat(selectParams)).append(' ')
.append("from").append(' ').append(tableName).append(' ')
.append("where").append(' ').append(whereBody)
.toString();
}
private String selectParamsToHiveFormat(Iterable<String> selectParams) {
StringBuilder formattedSelectParams = new StringBuilder();
for (String selectedParam : selectParams) {
formattedSelectParams.append('\'').append(selectedParam).append('\'').append(',');
}
if (formattedSelectParams.length() == 0) {
formattedSelectParams.append('*');
} else {
formattedSelectParams.deleteCharAt(formattedSelectParams.length() - 1);
}
return formattedSelectParams.toString();
}
public void close() {
if (hiveConnection != null) {
try {
hiveConnection.close();
} catch (SQLException e) {
//nothing to do, just close connection
} finally {
hiveConnection = null;
}
}
}
}
This is the code in which i connect to hive:
private static final String HIVE_URL = <hive url>;
private static final String HIVE_LOGIN = <hive login>;
private static final String HIVE_PASSWORD = <hive password>;
private static final String[] SEARCH_FIELDS = new String[] {"rowkey"};
private List<String> getIdsFromHive(String tableName, String whereBody) {
ResultSet hiveResponse;
try (HiveDataSearcher searcher = new HiveDataSearcher(HIVE_URL, HIVE_LOGIN, HIVE_PASSWORD)) {
hiveResponse = searcher
.setTableName(tableName)
.setWhereBody(whereBody)
.select(SEARCH_FIELDS);
}
List<String> ids = new ArrayList<>();
try {
while (hiveResponse.next()) { // in this place throw TTransportException
ids.add(hiveResponse.getString(SEARCH_FIELDS[0]));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return ids;
}
In my case, the reason for this exception is closed the connection before closed the statement. So I suggest you to check whether you has maintain the connection correctly.
Here is my code, wish it will inspire you something:
Wrong code, close connection before closing the statement:
Connection connection = null;
Statement statement = null;
try {
connection = HIVEUTILS.getConnection();
statement = connection.createStatement();
statement.execute("DROP TABLE IF EXISTS tbl1");
statement.execute("CREATE TABLE `tbl1` (`id` int)");
statement.execute("INSERT INTO tbl1 VALUES(1)");
}finally {
if (connection != null){
connection.close();
}
if (statement != null){
statement.close(); // exception occur here.
}
}
The correct order of closing is: close resultSet(if any) -> close statement -> close connection.
Connection connection = null;
Statement statement = null;
try {
connection = HIVEUTILS.getConnection();
statement = connection.createStatement();
statement.execute("DROP TABLE IF EXISTS tbl1");
statement.execute("CREATE TABLE `tbl1` (`id` int)");
statement.execute("INSERT INTO tbl1 VALUES(1)");
}finally {
if (statement != null){
statement.close(); // change the order
}
if (connection != null){
connection.close();
}
}
When I download a pdf file generated with JasperReports, its name is document.pdf.
I tried to set name with JasperPrint.setName(); but it doesn't work.
How can I change solve the task?
public class JaspereQueCaMarche {
public static enum Export {
PDF, HTML
};
private String cheminSource;
private JasperReport jasperReport;
private String nomRapport;
private List<ParametreJasper> parametres = new ArrayList<ParametreJasper>();
private static List<JaspereQueCaMarche> rapports = new ArrayList<JaspereQueCaMarche>();
protected JaspereQueCaMarche() {
}
public String getCheminSource() {
return cheminSource;
}
public String getNomRapport() {
return nomRapport;
}
public List<ParametreJasper> getParametres() {
return parametres;
}
public ParametreJasper getParametre(String nom) {
for (ParametreJasper pa : this.parametres) {
if (pa.getNom().equals(nom)) {
return pa;
}
}
return null;
}
public static List<JaspereQueCaMarche> getRapports() {
return rapports;
}
public static void setRapports(List<JaspereQueCaMarche> rapports) {
JaspereQueCaMarche.rapports = rapports;
}
public static JaspereQueCaMarche getFromHashCode(int hash) {
for (JaspereQueCaMarche jp : JaspereQueCaMarche.getRapports()) {
if (jp.hashCode() == hash) {
return jp;
}
}
return null;
}
public static void chargerListe(String repertoire) {
for (final File fic : new File(repertoire).listFiles()) {
if (!fic.isDirectory() && fic.getName().endsWith(".jrxml")) {
long dateModifSource = fic.lastModified();
String nomJasper = fic.getAbsolutePath();
nomJasper = nomJasper.substring(0, nomJasper.length() - 5) + "jasper";
File jasper = new File(nomJasper);
long dateModifObjet = jasper.exists() ? jasper.lastModified() : 0;
JaspereQueCaMarche jp = new JaspereQueCaMarche();
jp.cheminSource = fic.getAbsolutePath();
jp.nomRapport = fic.getName();
JasperReport jr = (dateModifObjet < dateModifSource) ? jp.compilerRapport() : jp.chargerRapport(jasper);
if (jr != null) {
jp.jasperReport = jr;
jp.extraireParametres();
JaspereQueCaMarche.rapports.add(jp);
}
}
}
}
public static JaspereQueCaMarche getEtat(String nom) {
String jrxml = nom + ".jrxml";
for (JaspereQueCaMarche jqcm : JaspereQueCaMarche.rapports) {
if (jqcm.nomRapport.equals(jrxml)) {
return jqcm;
}
}
return null;
}
private void extraireParametres() {
org.jdom2.Document document = null;
Element racine;
SAXBuilder sxb = new SAXBuilder();
try {
document = sxb.build(new File(this.getCheminSource()));
} catch (Exception e) {
Log.getLogGeneral().msgtest("erreur xml", e);
}
racine = document.getRootElement();
#SuppressWarnings("rawtypes")
List listeParametres = racine.getChildren();
#SuppressWarnings("rawtypes")
Iterator it = listeParametres.iterator();
while (it.hasNext()) {
Element courant = (Element) it.next();
if (courant.getName().equals("parameter")) {
String nom = courant.getAttributeValue("name");
String classe = courant.getAttributeValue("class");
String valeurParDefaut = "";
String description = "";
List<?> details = courant.getChildren();
Iterator<?> itDetails = details.iterator();
while (itDetails.hasNext()) {
Element detail = (Element) itDetails.next();
if (detail.getName().equals("defaultValueExpression")) {
valeurParDefaut = detail.getText();
} else if detail.getName().equals("parameterDescription")) {
description = detail.getText();
}
}
ParametreJasper pj = new ParametreJasper(nom, description, classe, valeurParDefaut);
this.parametres.add(pj);
}
}
}
public JasperPrint genererRapport(String transporteurConnecte) {
return genererRapport(transporteurConnecte, new HashMap<String, Object>());
}
public JasperPrint genererRapport(String transporteurConnecte, HashMap<String, Object> parametres) {
Connection conn = null;
JasperPrint jasperPrint = null;
try {
conn = new ConnexionJDBC(transporteurConnecte).getInstance();
} catch (SQLException | ClassNotFoundException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("impossible d'obtenir une connexion", e);
}
try {
if (this.jasperReport != null) {
jasperPrint = JasperFillManager.fillReport(jasperReport, parametres, conn);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("erreur fillReport", e);
}
return jasperPrint;
}
public void exporterRapport(JasperPrint jasperPrint, OutputStream outputStream, String transporteurConnecte) {
exporterRapport(jasperPrint, Export.PDF, outputStream, transporteurConnecte);
}
public void exporterRapport(JasperPrint jasperPrint, Export format, OutputStream outputStream, String transporteurConnecte) {
try {
if (format == Export.PDF) {
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest(" erreur exportReportToPdfStream", e);
}
}
public void sauvegarderRapport(JasperPrint jasperPrint, Export format, String emplacement, String transporteurConnecte) {
try {
if (format == Export.PDF) {
JasperExportManager.exportReportToPdfFile(jasperPrint, "test.pdf");
} else if (format == Export.HTML) {
JasperExportManager.exportReportToHtmlFile(jasperPrint, emplacement);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("erreur exportReport", e);
}
}
protected JasperReport compilerRapport() {
JasperReport jr = null;
try {
String cheminRapportCompile = JasperCompileManager.compileReportToFile(this.cheminSource);
jr = chargerRapport(new File(cheminRapportCompile));
} catch (JRException e) {
Log.getLogGeneral().msgprod("Impossible de compiler le rapport " + this.cheminSource, e);
}
return jr;
}
protected JasperReport chargerRapport(File fJasper) {
JasperReport jr = null;
try {
jr = (JasperReport) JRLoader.loadObject(fJasper);
} catch (JRException e) {
Log.getLogGeneral().msgprod("Impossible de charger le rapport " + fJasper.getAbsolutePath(), e);
}
return jr;
}
}
You may use exportReportToPdfFile from JasperExportManager, (report being your JasperPrint object)
JasperExportManager.exportReportToPdfFile(report, fileName);
The question is not clear enough, If you're using servlet/JSF you can do it like this.
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
httpServletResponse.addHeader("Content-disposition", "attachment; filename=report"+dateR+"_"+dateR1+".pdf");
ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
In order to execute a whole SQL script file[which includes create table statements and some rules defining create table]. I found this solution in order to achieve it --->"There is great way of executing SQL scripts from Java without reading them yourself as long as you don't mind having a runtime dependency on Ant. In my opinion such a dependency is very well justified in your case. Here is sample code, where SQLExec class lives in ant.jar:
private void executeSql(String sqlFilePath) {
final class SqlExecuter extends SQLExec {
public SqlExecuter() {
Project project = new Project();
project.init();
setProject(project);
setTaskType("sql");
setTaskName("sql");
}
}
SqlExecuter executer = new SqlExecuter();
executer.setSrc(new File(sqlFilePath));
executer.setDriver(args.getDriver());
executer.setPassword(args.getPwd());
executer.setUserid(args.getUser());
executer.setUrl(args.getUrl());
executer.execute();
}
I don't know whether it will work or not!!!
Can anybody give some hints to work on the above solution? I mean how to get the code work and also let me know any other solution to execute SQL script files!!!
Thanks,
Mahesh
This is a code snippet I stole from the internet somewhere (I don't remember where) that I know works great: it wont run the way that it is below. It might give you enough clues to get yours working though, or you might find the source on Google somewhere:
private void runScriptOnce(Connection conn, Reader reader) throws IOException, SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}