How to execute a sql gzipped script for postgresql database in java using jdbc API? - postgresql

I'd like to execute a sql script gzipped to a postgresql database using java jdbc API.
I know how to do this in H2 database using the sql run script statement.

I manage to do this for any database using this code
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.zip.GZIPInputStream;
/**
* Created on 09/01/16.
*
* #author Tony Chemit - chemit#codelutin.com
*/
public class RunSqlScript {
public void executeSqlScript(Connection connection, boolean gzip, int batchSize, byte... content) throws SQLException, IOException {
boolean autoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
try (BufferedReader reader = createReader(gzip, content)) {
try (Statement statement = connection.createStatement()) {
int currentBatchSize = 0;
String command = null;
String line;
while ((line = reader.readLine()) != null) {
String trimLine = line.trim();
if (trimLine.startsWith("--")) {
continue;
}
command = command == null ? line : command + ' ' + line;
if (trimLine.endsWith(";")) {
statement.addBatch(command);
batchSize++;
command = null;
if (currentBatchSize % batchSize == 0) {
flushStatement(statement);
}
}
}
flushStatement(statement);
}
} finally {
connection.setAutoCommit(autoCommit);
}
}
protected BufferedReader createReader(boolean gzip, byte... content) throws IOException {
return new BufferedReader(new InputStreamReader(new BufferedInputStream(gzip ? new GZIPInputStream(new ByteArrayInputStream(content)) : new ByteArrayInputStream(content))));
}
protected void flushStatement(Statement statement) throws SQLException {
statement.executeBatch();
statement.clearBatch();
}
}

Related

net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master

Error this line :
mDataBase = SQLiteDatabase.openDatabase(dbPath, "123", null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
When open the database . but whats Wrong? how to open database with password? Can any one help me?
I set the password on SQLITE Db Browser > File> Set encryption
open this password in android part
When Open then show error
error : net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master
Can any one help me to solve it? thanks in advance
import android.content.Context;
import android.database.SQLException;
//import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;
import net.sqlcipher.database.SQLiteDatabase.CursorFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import net.sqlcipher.database.SQLiteDatabase;
import android.app.Activity;
import android.os.Bundle;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String TAG = DatabaseHelper.class.getName();
private static String DB_PATH = "";
private static String DB_NAME = "ec.db";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;
File databaseFile=null;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
this.mContext = context;
SQLiteDatabase.loadLibs(context);
File databaseFile = context.getDatabasePath(DB_NAME);
databaseFile.mkdirs();
}
public void createDataBase() throws IOException {
// If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if (!mDataBaseExist) {
this.getWritableDatabase("123");
this.close();
try {
// Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
} catch (IOException mIOException) {
throw new Error(mIOException.toString() + " : " + DB_PATH
+ DB_NAME);// "ErrorCopyingDataBase"
}
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
// Copy the database from assets
private void copyDataBase() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[4096];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
// Open the database, so we can query it
public boolean openDataBase() throws SQLException {
String mPath = DB_PATH + DB_NAME;
//File dbFile = new File(DB_PATH + DB_NAME);
//File databaseFile = mContext.getDatabasePath(DB_NAME);
//databaseFile.mkdirs();
//databaseFile.delete();
SQLiteDatabase.loadLibs(mContext);
String dbPath = mContext.getDatabasePath("ec.db").getPath();
//databaseFile.delete();
SQLiteDatabase.loadLibs(mContext);
//mDataBase = SQLiteDatabase.openOrCreateDatabase(databaseFile, "123", null);
//mDataBase = SQLiteDatabase.openDatabase(mPath, "123",null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
mDataBase = SQLiteDatabase.openDatabase(dbPath, "123", null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
#Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
i created a database with sqlcipher V3.5.7 and then changed the sqlcipher version to V4.1.3 and had this problem
in build.gradle i changed
implementation "net.zetetic:android-database-sqlcipher:4.1.3#aar"
to
implementation 'net.zetetic:android-database-sqlcipher:3.5.7#aar'
and the problem solved
You are referencing the password string value of 123456Sa, however your call within createDataBase uses the value of 123 as a password to getWritableDatabase.
I was getting this exception only in obfuscation case.
I added default constructors for both ByteArraySerializer and ByteArrayDeserializer classes.
Note: don't add above classes as inner classes. Declare these classes independently add keep these classes in proguard-rules.

HttpUrlConnection.connect() Query

After hours of trawling the internet and trying to make sense of the documentation I seem unable to find a resolution to this problem.
I have an application which is using an ASyncTask to connect to a server I have 3 addresses to "test" the connection.
Now the problem is when I use the Myconnection.connect() the background task just hangs if there is either no known address or a dead link.
How can I test this connection when with a dead link or dead server it hangs and does not receive any response
The errors in the Logcat are
07-02 12:47:13.101 13850-20562/nodomain.myapplication D/URL ERRORhttp://10.0.0.2/testdb/connection.php
07-02 12:47:13.339 13850-20562/nodomain.myapplication I/URL IS OK: [ 07-02 12:47:13.339 13850:20562 I/ ]Status : 200
07-02 12:47:13.344 13850-20562/nodomain.myapplication D/URL ERRORhttp://localhost/myPage.php
As you can see the only URL I get a response from is www.google.com
My code is below:
package nodomain.myapplication;
import android.os.AsyncTask;
import android.util.Log;
import org.w3c.dom.Text;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by Shab on 02/07/2017.
*/
public class bgWorker extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params)
{
String db_Username = "root";
String db_Password = "";
String db_Name = "testdb";
String url1 = "http://10.0.0.2/testdb/connection.php"; //DEAD? (NO RESPONSE)
(Program Hang until exception is called)
String url2 = "http://www.google.com"; //OK RESPONSE 200
String url3 = "http://localhost/myPage.php"; //NO RESPONSE
try {
getResponseCodes(url1);
getResponseCodes(url2);
getResponseCodes(url3);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
private String encodeURLString(String value) {
String encodedString = "";
try {
encodedString = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodedString;
}
public static int getResponseCodes(String TheURL) throws MalformedURLException,IOException
{
URL oUrl = new URL(TheURL);
HttpURLConnection oHuC = (HttpURLConnection) oUrl.openConnection();
oHuC.setRequestMethod("HEAD");
int response = 0;
try{
oHuC.connect();
response = oHuC.getResponseCode();
if(response == 200)
{
Log.i("URL IS OK","");
}else{
Log.i("URL IS NOT OK","");
}
Log.i("", "Status : " + response);
}catch(IOException e){
Log.d("URL ERROR" + oUrl, "D");
}
return response;
}
}
Even with the IF statement testing the response for a 200 OK it only manages to interpret one response from the 3 URL due to the URL IS OK output.

How to replicate a page and all its children using replicator API?

Here is the code in which I am replicating the page
final String pagePath = blogEntryPage.getPath();
final Resource jcrContent= blogEntryPage.getContentResource();
final Node jcrNode = jcrContent.adaptTo(Node.class);
adminSession = jcrNode.getSession();
// REPLICATE THE DATE NODE
replicator.replicate(adminSession, ReplicationActionType.ACTIVATE, pagePath);
Here the problem is only the parent page is getting replicated I want to replicate the child pages also
How about just iterating over the child pages and replicate them as well:
Iterator<Page> childPages = blogEntryPage.listChildren();
while (childPages.hasNext()) {
Page childPage = childPages.next();
replicator.replicate(adminSession, ReplicationActionType.ACTIVATE, childPage.getPath());
}
You could even put this in a method and call it recursively.
Try this, (have not tested)
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jcr.Session;
import com.day.cq.replication.Agent;
import com.day.cq.replication.AgentManager;
import com.day.cq.replication.ReplicationAction;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationContent;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.ReplicationOptions;
import com.day.cq.replication.Replicator;
import com.day.cq.wcm.api.WCMException;
import com.day.cq.wcm.msm.api.LiveRelationship;
import com.day.cq.wcm.msm.api.LiveRelationshipManager;
import com.day.cq.wcm.msm.api.RolloutManager;
import org.osgi.framework.ServiceReference;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.LoginException;
public class Activator implements BundleActivator {
/*
* (non-Javadoc)
* #see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
AgentManager agentManager = getService(context,AgentManager.class);
Replicator replicator = getService(context,Replicator.class);
ResourceResolverFactory resourceFactory = getService(context,ResourceResolverFactory.class);
ResourceResolver resourceResolver = null;
Session session = null;
String path = "/content/geometrixx-gov";
try {
resourceResolver = resourceFactory.getAdministrativeResourceResolver(null);
session = resourceResolver.adaptTo(Session.class);
for (Map.Entry<String, Agent> e : agentManager.getAgents().entrySet()) {
if (e.getValue().getConfiguration().getTransportURI().contains("/bin/receive?sling:authRequestLogin=1")) {
Agent a = e.getValue();
try {
ReplicationAction ra = new ReplicationAction(ReplicationActionType.ACTIVATE, path);
ReplicationContent rc = a.buildContent(session, ra);
a.replicate(ra, rc, new ReplicationOptions());
System.out.println("Activator cache flush requested check queue");
} catch (ReplicationException ex) {
ex.printStackTrace();
}
}
}
} catch (LoginException e) {
e.printStackTrace();
}
}
public <T> T getService(BundleContext bc, Class<T> c)
{
ServiceReference sr = bc.getServiceReference(c.getName());
if (sr != null)
{
return (T) bc.getService(sr);
}
return null;
}
/*
* (non-Javadoc)
* #see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
// TODO add cleanup code
}
}

Eclipse Luna F6 doesn't step over

Strange, I have a Java application in Eclipse Luna and when debugging it and I'm trying to use F6 it doesn't "step over", but instead it "steps into".
I was trying to build a Java applicaton in Eclipse Luna. It was a database application from
here.
With two source files (DB.java):
`import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DB {
public Connection conn = null;
public DB() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/Crawler";
conn = DriverManager.getConnection(url, "root", "admin213");
System.out.println("conn built");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public ResultSet runSql(String sql) throws SQLException {
Statement sta = conn.createStatement();
return sta.executeQuery(sql);
}
public boolean runSql2(String sql) throws SQLException {
Statement sta = conn.createStatement();
return sta.execute(sql);
}
#Override
protected void finalize() throws Throwable {
if (conn != null || !conn.isClosed()) {
conn.close();
}
}
}`
and Main.java:
`import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Main {
public static DB db = new DB();
public static void main(String[] args) throws SQLException, IOException {
db.runSql2("TRUNCATE Record;");
processPage("http://www.mit.edu");
}
public static void processPage(String URL) throws SQLException, IOException{
//check if the given URL is already in database
String sql = "select * from Record where URL = '"+URL+"'";
ResultSet rs = db.runSql(sql);
if(rs.next()){
}else{
//store the URL to database to avoid parsing again
sql = "INSERT INTO `Crawler`.`Record` " + "(`URL`) VALUES " + "(?);";
PreparedStatement stmt = db.conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, URL);
stmt.execute();
//get useful information
Document doc = Jsoup.connect("http://www.mit.edu/").get();
if(doc.text().contains("research")){
System.out.println(URL);
}
//get all links and recursively call the processPage method
Elements questions = doc.select("a[href]");
for(Element link: questions){
if(link.attr("href").contains("mit.edu"))
processPage(link.attr("abs:href"));
}
}
}
}`
I forgot to include the mysql-connector-java-5.1.16-bin.jar into the buildpath.
This resulted in an exception occuring in the initialization that occurs in the DB()
initializer code. At least this is my assumption that the behaviour of Eclipse was
irritated (maybe it's a feature?) and the step over didn't work right.

How to change the default folder for uploading file in jboss

I am trying to upload a file, I am trying to change the default location of the uploaded file. How to change this please suggest ?
package Controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import requests.Connect;
import display.DisplayLog;
/** * Servlet implementation class ControlServlet
*/
public class ControlServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
boolean result;
private boolean isMultipart;
private String filePath;
private int maxFileSize = 1000 * 1024;
private int maxMemSize = 1000 * 1024;
private File file ;
public ControlServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session=request.getSession();
String userName = request.getParameter("username");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("audio/mpeg3;audio/x-mpeg-3;video/mpeg;video/x-mpeg;text/xml");
PrintWriter out = response.getWriter( );
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
String root = getServletContext().getRealPath("/");
root = "F/images";
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(" Prashant File Upload Location is ");
// System.out.println(uploadedFile.getAbsolutePath());
System.out.println("fileName is " +fileName);
System.out.println("root is " + root);
System.out.println("path is " + path);
if(fileName!="")
{
item.write(uploadedFile);
System.out.println(" Prashant File Upload Location 2 is ");
System.out.println(uploadedFile.getAbsolutePath());
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
out.println(uploadedFile.getAbsolutePath());
out.println("<h1>File Uploaded Successfully....:-)</h1>");
System.out.println("file not found");
}
}
else
{
String abc = item.getString();
}
}
} catch (FileUploadException e) {
out.println(e);
} catch (Exception e) {
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
System.out.println("print this Prashant" + userName);
session.setAttribute("username",userName);
request.setAttribute("username","prashant");
// RequestDispatcher myDispatch = request.getRequestDispatcher("Index.jsp");
//myDispatch.forward(request, response);
}
}
I am getting this as default folder F:\jboss-4.2.3.GA-jdk6\jboss-4.2.3.GA\bin\ please help i am new to this
Your problem is here:
String root = getServletContext().getRealPath("/");
you are setting the upload path to the containers path, not a default path but the place where the server started from. You can make the upload path anything you want it to be, it depends on your needs and configuration.
You could create a system property with the directory of your choice, you could set it as a dynamic property in a JBoss configuration file (not sure what that would be for JBoss4).