I am storing an audio blob(recorded voice) in angular and then I am calling a spring boot API to store it in azure blob storage as so:
submit(){
const blob = this.audioRecording.getblob();
this.blobOutgoing = new FormData();
this.blobOutgoing.append('file', blob);
this.blobOutgoing.append('name', this.name);
this.blobOutgoing.append('email', this.email);
this.blobOutgoing.append('uid', this.uid);
this.pronunciationAPIService.saveEmployeeNameAlternate(this.blobOutgoing)
.subscribe((response: any) => {
console.log(response);
})
}
public void insertEmpoyeeRecord(Employee employee) {
try {
Statement stmt = getStatement();
System.out.println("Connected to the YugabyteDB Cluster successfully.");
// stmt.execute("DROP TABLE IF EXISTS employee");
/*stmt.execute("CREATE TABLE IF NOT EXISTS employee" +
" (id int primary key, name varchar, age int, language text)");*/
// System.out.println("Created table employee");
String insertStr = "INSERT INTO employees.employees VALUES ('"+employee.getUid()+"','"+employee.getEmail()+"','"+employee.getName()+"','"+employee.getUid()+"')";
String deleteStr = "DELETE FROM employees.employees WHERE email='"+employee.getEmail()+"' or uid='"+employee.getUid()+"'";
stmt.execute(deleteStr);
stmt.execute(insertStr);
----------> blobService.uploadFile(employee.getMultipartFile(), employee.getUid()); <----------------------------------
System.out.println("EXEC: " + insertStr);
ResultSet rs = stmt.executeQuery("select * from employees.employees");
while (rs.next()) {
System.out.println(String.format("Query returned: uid = %s, email = %s, name = %s, blob = %s",
rs.getString("uid"), rs.getString("email"), rs.getString("name"), rs.getString("audio")));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void uploadFile(MultipartFile multipartFile, String audioFilenameRequest){
// String localFolderPath = "C:\\Users\\erman\\Downloads\\audiofolder\\";
try {
byte[] bytes = multipartFile.getBytes();
System.out.println("lenght:: " + bytes.length);
String audioFileName = audioFilenameRequest;
CloudBlobContainer containerReference = getCloudBlobContainer();
//Getting a blob reference
CloudBlockBlob blockBlobReference = containerReference.getBlockBlobReference(audioFileName);
//Creating blob and uploading file to it
//System.out.println("Uploading the sample file, Absolute path: "+sourceFile.getAbsolutePath() );
blockBlobReference.uploadFromByteArray(bytes,0,bytes.length);
System.out.println("upload to Azure cloud blob is done!!!!");
// blockBlobReference.upload
/* Path path = Paths.get(localFolderPath + multipartFile.getOriginalFilename());
Files.write(path,bytes);*/
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (StorageException e) {
e.printStackTrace();
}
}
And then I try to retrieve from Angular by calling another Spring boot API:
playAudioFromBlob(){
this.pronunciationAPIService
.pronounceName(this.employee)
.subscribe((response: Array<Employee>) => {
console.log(response);
response.forEach( (employee) => {
let blob = new Blob(employee.blobByte, {type: "audio/webm"});
console.log(employee.blob);
const audioURL = URL.createObjectURL(blob);
let audio = new Audio(audioURL)
audio.controls = true;
audio.play();
})
});
}
public List<Employee> searchEmployeeByUid(String uid){
Employee employee = null;
try {
System.out.println("Connected to the YugabyteDB Cluster successfully.");
Statement stmt = getStatement();
String selectStr = "SELECT uid,email,name,audio FROM employees.employees WHERE uid='"+uid+"'";
stmt.execute(selectStr);
System.out.println("EXEC: " + selectStr);
ResultSet rs = stmt.executeQuery(selectStr);
while (rs.next()) {
employee = new Employee();
employee.setUid(rs.getString("uid"));
employee.setEmail(rs.getString("email"));
employee.setName(rs.getString("name"));
employee.setBlob(rs.getString("audio"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
byte[] blob = blobService.downloadFile(employee.getBlob());
employee.setBlobByte(blob);
return employee;
}
public byte[] downloadFile(String audioFileName) {
File downloadedFile = null;
byte[] audioByteArray = new byte[472179];
try {
// byte[] bytes = multipartFile.getBytes();
// String audioFileName = multipartFile.getOriginalFilename();
CloudBlobContainer containerReference = getCloudBlobContainer();
//Getting a blob reference
CloudBlockBlob blockBlobReference = containerReference.getBlockBlobReference(audioFileName);
// downloadedFile = new File(audioFileName);
//byte [] b = new byte[472179];
blockBlobReference.downloadToByteArray(audioByteArray,0);
System.out.println("download from Azure cloud blob is done!!!!:: Size : " + audioByteArray.length);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (StorageException e) {
e.printStackTrace();
}
return audioByteArray;
}
public class Employee {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBlob() {
return blob;
}
public void setBlob(String blob) {
this.blob = blob;
}
public MultipartFile getMultipartFile() {
return blobOutgoing;
}
public void setMultipartFile(MultipartFile multipartFile) {
this.blobOutgoing = multipartFile;
}
private String name;
private String uid;
private String email;
private String blob;
private MultipartFile blobOutgoing;
public byte[] getBlobByte() {
return blobByte;
}
public void setBlobByte(byte[] blobByte) {
this.blobByte = blobByte;
}
private byte[] blobByte;
}
The problem is when converting the byte[] stream to a blob in angular I get the error:
Failed to construct 'Blob': The provided value cannot be converted to a sequence
I think I am getting this issue because I am not properly writing or reading the blob. I use ng-audio-recorder for the audio recordings in Angular. ng-audio-recorder builds the blob in audio webm
update: perhaps a more simplified question is how can you play back the byte[] stream in multipartfile in angular?
The initial argument (Parameter) must be presented in the sequence.
let blob = new Blob(employee.blobByte, {type: "audio/webm"}); console.log(employee.blob);
In place of this replace with the below one.
let blob=new Blob([employee.blobByte] ,{type: "audio/webm"}); console.log(employee.blob);
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.
My task is to send data from a client through the server in a database and retrieve those data through the server and fill some tables.
I can't find a way how to fill those tables in the way I want.
GitHub project link.
Client Listener from where I get the data for the client
public clientListener(TextArea textArea) {
this.textArea = textArea;
int portNr = Integer.parseInt(port);
try {
// Create a socket to connect to the server
#SuppressWarnings("resource")
Socket socket = new Socket("localhost", portNr);
// Create an output stream to send data to the server
outputToServer = new PrintWriter(socket.getOutputStream());
// Create an input stream to read data from the server
inputFromServer = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
} catch (IOException ex) {
Platform.runLater(() -> textArea.appendText("Exception in gateway constructor: " + ex.toString() + "\n"));
}
}
public ObservableList<Qyteti> getQytet() {
outputToServer.println(GET_QYTET);
outputToServer.flush();
String ID = null, Qyteti = null, ZIP = null;
try {
ObservableList<Qyteti> Qytet = null;
Qytet.add(new Qyteti(inputFromServer.readLine().concat(ID),
inputFromServer.readLine().concat(Qyteti),
inputFromServer.readLine().concat(ZIP)));
return Qytet;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
Form Controller
public void updateTable() {
ID.setCellValueFactory(new PropertyValueFactory<>("ID"));
Qyteti.setCellValueFactory(new PropertyValueFactory<>("Qyteti"));
ZIP.setCellValueFactory(new PropertyValueFactory<>("ZIP"));
QytetiList.add((application.Qyteti) gateway.getQytet());
tblQyteti.setItems(QytetiList);
}
Server Functions from where in different cases I get different results
public void run() {
handler = new ConnectionHandler();
try {
// Create reading and writing streams
BufferedReader inputFromClient = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter outputToClient = new PrintWriter(socket.getOutputStream());
// Continuously serve the client
while (true) {
// Receive request code from the client
int request = Integer.parseInt(inputFromClient.readLine());
// Process request
switch(request) {
case GET_QYTET: {
connection = handler.getConnection();
String merrQytet = "SELECT * FROM tblQyteti";
try {
pst = connection.prepareStatement(merrQytet);
ResultSet rs = pst.executeQuery();
while(rs.next()) {
outputToClient.printf(merrQytet, rs.getString("qid"), rs.getString("Qyteti"), rs.getString("ZIP"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
catch(IOException ex) {
Platform.runLater(()->textArea.appendText("Exception in client
thread: "+ex.toString()+"\n"));
}
Qyteti class which is used as an object type:
import java.io.Serializable;
public class Qyteti implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
String ID, Qyteti, ZIP;
public Qyteti(String ID, String Qyteti, String ZIP) {
this.ID = ID;
this.Qyteti = Qyteti;
this.ZIP = ZIP;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getQyteti() {
return Qyteti;
}
public void setQyteti(String qyteti) {
Qyteti = qyteti;
}
public String getZIP() {
return ZIP;
}
public void setZIP(String zIP) {
ZIP = zIP;
}
}
So I have problem with testing my application. I am trying to do REST/HTTP test. Here is my code:
#Path("/ftpaction")
public class JerseyFileUpload {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response postMsg(#HeaderParam("FTP-Host") String Host, #HeaderParam("FTP-Port") String Port,
#HeaderParam("FTP-User") String User, #HeaderParam("FTP-Password") String Password,
#HeaderParam("FTP-Path") String Path, #FormDataParam("file") InputStream inputStream) {
try {
InformationHandler informationHandler = new InformationHandler(Path, Host, Port, User, Password);
CountriesStructure worker = new CountriesStructure();
worker.prepareCountriesStructure(inputStream, true, informationHandler);
} catch (UsernameOrPasswordException e) {
return Response.status(401).entity("Status 401.").build();
} catch (SocketException e) {
return Response.status(404).entity("Status 404.").build();
} catch (IOException e) {
return Response.status(400).entity("Status 400.").build();
} catch (JAXBException e) {
return Response.status(500).entity("Status 500.").build();
} catch (Exception e) {
return Response.status(500).entity("Status 500.").build();
}
return Response.status(200).entity("Success!").build();
}
}
And my test:
#RunWith(HttpJUnitRunner.class)
public class TestMain extends TestCase {
#Rule
public Destination destination = new Destination(this, "http://localhost:8080");
#Context
private Response response;
#HttpTest(method = Method.POST, path = "/JerseyWebApp/ftpaction/upload", content = "{}", file = "/CountriesList.txt", type = MediaType.MULTIPART_FORM_DATA, headers = {
#Header(name = "FTP-Host", value = "localhost"), #Header(name = "FTP-Port", value = "21"),
#Header(name = "FTP-User", value = "ftptest"), #Header(name = "FTP-Password", value = "test"),
#Header(name = "FTP-Path", value = "/test123"), #Header(name = "Accept-Encoding", value = "multipart/form-data")})
public void checkPost() {
System.out.println(response.getBody());
}
}
I have problem with reading file by test. I don't know what I have to do, because I am using file as "FormDataParam". Somebody have any idea how can I upload file to test as FormDataParam? Because like now it doesn't see my file and just return "Status 400".
I have a POJO (the class has getters set for each field) which i am sending back to a variable in a different class where the template configuration is done. Somehow i am getting an error when the ftl tries to populate the view.
I don't know how to present an object of this type to a template: org.test.config.TransformerInfoBuilder. Here is the code where the error comes from:
[line 13, column 5 in templates/ConfigMain.ftl]
list TransformerInfoBuilders as TransformerInfoBuilder
Java error stacktrace:
freemarker.template.TemplateModelException: Don't know how to present an object of this type to a template: org.test.config.TransformerInfoBuilder
at freemarker.template.SimpleObjectWrapper.handleUnknownType(SimpleObjectWrapper.java:139)
at freemarker.template.SimpleObjectWrapper.wrap(SimpleObjectWrapper.java:116)
at freemarker.template.WrappingTemplateModel.wrap(WrappingTemplateModel.java:131)
at freemarker.template.SimpleSequence.get(SimpleSequence.java:197)
at freemarker.template.IteratorBlock$Context.runLoop(IteratorBlock.java:163)
at freemarker.template.Environment.visit(Environment.java:316)
at freemarker.template.IteratorBlock.accept(IteratorBlock.java:94)
at freemarker.template.Environment.visit(Environment.java:180)
at freemarker.template.IfBlock.accept(IfBlock.java:81)
at freemarker.template.Environment.visit(Environment.java:180)
at freemarker.template.MixedContent.accept(MixedContent.java:91)
at freemarker.template.Environment.visit(Environment.java:180)
at freemarker.template.Environment.process(Environment.java:166)
at freemarker.template.Template.process(Template.java:238)
at org.mule.config.ConfigLoader.main(ConfigLoader.java:116)
The ftl is as below.
<#if TransformerInfoBuilders?has_content>
<#list TransformerInfoBuilders as TransformerInfoBuilder>
<flow name="${TransformerInfoBuilder.id}">
</flow>
</#list>
<#else>
no content
</#if>
Java class for creating the object.
public class TransformerInfoBuilder {
String id="";
String name="";
String returnClass="";
String ignoreBadInput="";
String encoding="";
String mimeType="";
String templateName="";
public TransformerInfoBuilder(String id, String name,String returnClass, String encoding, String ignoreBadInput)
{
this.id=id;
this.name=name;
this.returnClass=returnClass;
this.encoding=encoding;
this.ignoreBadInput=ignoreBadInput;
}
public void setid(String id)
{
this.id=id;
}
public void setname(String name)
{
this.name=name;
}
public String getname()
{
return this.name;
}
public String getid()
{
return this.id;
}
public String getreturnClass()
{
return this.returnClass;
}
public String getignoreBadInput()
{
return this.ignoreBadInput;
}
public String getencoding()
{
return this.encoding;
}
}
Java class where the call to configurator is made:
public class ConfigLoader {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, IOException {
Configuration cfg = new Configuration();
Template template = cfg.getTemplate("/templates/ConfigMain.ftl");
Connection dbconn=null;
Statement stmt=null;
ResultSet rs= null;
String id="";
HashMap<String,Map<String,String>> tinfo= new HashMap<String,Map<String,String>> ();
List<String> flowList = new ArrayList<String>();
List<TransformerInfoBuilder> TransformerInfoBuilders = new ArrayList<TransformerInfoBuilder>();
//Map<String,Object> flistfinal = new HashMap<String,Object>();
Map<String, Object> data = new HashMap<String, Object>();
List<Map<String,ArrayList<String>>> mapsfinal = new ArrayList<Map<String,ArrayList<String>>>();
try {
// Load the template
String configId =args[0];
System.out.println("+++++++++++++++++++++++configID is " + configId + " +++++++++++++++++++++++");
dbconn=DBConnection.connection();
System.out.println("\n\n++++++++++++++++++ Obtained DB connection ++++++++++++++++");
stmt = dbconn.createStatement();
System.out.println("\n\n++++++++++++++++++ Querying for Config Application Name ++++++++");
rs = stmt.executeQuery("SELECT * FROM FlowInfo where ConfigFileId =" + configId);
while (rs.next()) {
id = rs.getString("FlowID");
flowList.add(id);
}
TransformerInfoBuilders=Transformer.TransformerInfo(flowList);
data.put("TransformerInfoBuilders",TransformerInfoBuilders);
data.put("message","#[payload]");
Writer writer = new FileWriter("output/MainConfig.xml");
template.process(data, writer);
writer.flush();
writer.close();
//out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException et) {
et.printStackTrace();
}finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (dbconn != null) dbconn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
Any pointers on what i might be doing wrong over here??
Thanks
Salim
After extending the DefaultObjectWrapper class the problem was solved. I had to upgrade it to a higher version of Freemarker.jar.
Im trying to read values from my jTable1
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int colum=jTable1.getSelectedColumn();
int row=jTable1.getSelectedRow();
System.out.println("row of selected is "+row+"col is "+colum);
final String remark1 = (String) jTable1.getValueAt(row, 8);
final String remark2 = (String) jTable1.getValueAt(row, 9);
final String invoiceno = (String) jTable1.getValueAt(row, 11);
final String id=(String) jTable1.getValueAt(row, 12);
System.out.println(id + "id");
try{
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
System.out.println("try loop for update");
SentenceExec followinsert = new PreparedSentence(s
, "UPDATE FOLLOWUP SET REMARK1= ?, REMARK2=?, INVOICENO=? WHERE ID= ?"
, SerializerWriteParams.INSTANCE);
followinsert.exec(new DataParams() { public void writeValues() throws BasicException {
System.out.println("executing command");
setString(1, remark1);
setString(2, remark2);
setString(3, invoiceno);
setString(2, id);
//System.out.println(" after update line");
}});
return null;
}
};
t.execute(); //im getting null pointer exception here :(
}
catch (BasicException ex) {
Logger.getLogger(FollowUp.class.getName()).log(Level.SEVERE, null, ex);
}
}
i get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.openbravo.data.loader.Transaction.execute(Transaction.java:42)
at com.openbravo.pos.followup.FollowUp.jcmdOKActionPerformed(FollowUp.java:679)
at com.openbravo.pos.followup.FollowUp.access$300(FollowUp.java:66)
at com.openbravo.pos.followup.FollowUp$5.actionPerformed(FollowUp.java:193)
Transaction.java is
public abstract class Transaction<T> {
private Session s;
/** Creates a new instance of Transaction */
public Transaction(Session s) {
this.s = s;
}
public final T execute() throws BasicException {
if (s.isTransaction()) {
return transact();
} else {
try {
try {
s.begin();
T result = transact();
s.commit();
return result;
} catch (BasicException e) {
s.rollback();
throw e;
}
} catch (SQLException eSQL) {
throw new BasicException("Transaction error", eSQL);
}
}
}
protected abstract T transact() throws BasicException;
}