Advertisement
Guest User

Untitled

a guest
May 31st, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.76 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package ru.bmstu;
  7. import java.nio.charset.StandardCharsets;
  8. import org.apache.commons.io.IOUtils;
  9. import sun.audio.*;
  10. import java.io.PipedOutputStream;
  11. import java.io.PipedInputStream;
  12. import java.io.DataInputStream;
  13. import java.io.PrintStream;
  14. import java.io.File;
  15. import java.awt.Image;
  16. import java.io.ByteArrayInputStream;
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.lang.String;
  21. import java.net.ConnectException;
  22. import java.sql.Blob;
  23. import java.sql.CallableStatement;
  24. import java.sql.Connection;
  25. import java.sql.DriverManager;
  26. import java.sql.PreparedStatement;
  27. import java.sql.ResultSet;
  28. import java.sql.SQLException;
  29. import javax.jws.WebMethod;
  30. import javax.jws.WebParam;
  31. import javax.naming.NamingException;
  32. import java.io.BufferedInputStream;
  33. import javazoom.jl.player.Player;
  34. import javax.sound.sampled.*; //AudioSystem;
  35. import java.io.InputStream;
  36. import java.io.IOException;
  37. import javax.sound.sampled.AudioFormat;
  38. import javax.sound.sampled.AudioInputStream;
  39. import javax.sound.sampled.AudioSystem;
  40. import javax.sound.sampled.DataLine;
  41. import javax.sound.sampled.LineUnavailableException;
  42. import javax.sound.sampled.SourceDataLine;
  43. import java.io.FilterInputStream;
  44. import javax.ws.rs.core.Response;
  45. import java.sql.DriverManager;
  46. import org.apache.commons.io.IOUtils;
  47. import javax.servlet.http.*;
  48. import java.io.OutputStream;
  49. /**
  50.  *
  51.  * @author Dell
  52.  */
  53. public class AnFilter {
  54.     Connection conn;
  55.     private long _blobId;
  56.     private long retNum;
  57.     private String MimeType;
  58.     private String fileName;
  59.     private boolean _controlErrors;
  60.     private InputStream isFile;
  61.     private String outFile;
  62.     private InputStream filteredFile;
  63.     private int size;
  64.    
  65.    
  66.    //public static void main(String[] args) {
  67.     //String part1 = args[0];
  68.     //String part2 = args[1];
  69.    
  70.     //int songID=Integer.parseInt(part1);
  71.     //int methNum=Integer.parseInt(part2);
  72.     //int songID=150; //только для тестирования типо
  73.     //int methNum=1; //только для тестирования типо
  74.     /*Filter fil = new Filter(songID);
  75.    
  76.     try{
  77.         System.out.println("Устанавливаем соединение...");
  78.         fil.initConnection();
  79.         System.out.println("Выгружаем данные...");
  80.         fil.initFile();
  81.         System.out.print("Название композиции:");
  82.         System.out.println(fil.getFileName());
  83.         if (methNum==1)
  84.         {  
  85.             System.out.println("Добавляем шум...");
  86.             SimpleSoundPlayer sound = new SimpleSoundPlayer(fil.getIsFile());
  87.             InputStream is = new ByteArrayInputStream(sound.getSamples());
  88.             EchoFilter filter = new EchoFilter(11025, .001f);
  89.             is = new FilteredSoundStream(is, filter);
  90.             System.out.println("Загружаем обработанные данные...");
  91.             fil.toDataBase(fil.getFileName(),is);
  92.         }
  93.         else
  94.         {
  95.             System.out.println("пока нифига");
  96.         }
  97.        
  98.         System.out.println("Закрываем соединение...");
  99.         fil.getConnection().close();    
  100.         }
  101.         catch(Exception ex){
  102.             ex.printStackTrace();
  103.         }*/
  104.     //}
  105.    
  106.     AnFilter(int syncID){
  107.        _blobId=syncID;
  108.        MimeType="audio/aiff";
  109.        size=0;
  110.     }
  111.    
  112.     public void setFilteredFile(InputStream is){
  113.         filteredFile=is;
  114.     }
  115.    
  116.     public InputStream getFilteredFile(){
  117.         return filteredFile;
  118.     }
  119.    
  120.     public String getMimeType(){
  121.         return MimeType;
  122.     }
  123.    
  124.     public String getFileName(){
  125.         return fileName;
  126.     }
  127.    
  128.     public long getRetNum(){
  129.         return retNum;
  130.     }
  131.    
  132.     public InputStream getIsFile(){
  133.         return isFile;
  134.     }
  135.     public InputStream getfilteredFile(){
  136.        
  137.         return filteredFile;
  138.     }
  139.     public Connection getConnection(){
  140.         return conn;
  141.     }
  142.    
  143.     public void initConnection() throws SQLException, NamingException, ClassNotFoundException {
  144.         Class.forName("oracle.jdbc.driver.OracleDriver");
  145.         conn = DriverManager.getConnection(
  146.                 "jdbc:oracle:thin:@localhost:1521:ORCL", "Mokona",
  147.                 "Mokona");
  148.         conn.setAutoCommit(false);
  149.  
  150.     }
  151.     public void initFile() throws SQLException {
  152.         boolean wasQuery;
  153.         try (PreparedStatement ps = conn.prepareStatement("select t.blob_data, t.file_name from audio t where t.sync_id = ?")) {
  154.             ResultSet rs;
  155.             Blob blob;
  156.             wasQuery = false;
  157.            
  158.             while(!wasQuery && _blobId < 10000){
  159.                 ps.setLong(1, _blobId);
  160.                 rs = ps.executeQuery();
  161.                 System.out.println(ps.toString());
  162.                 while (rs.next()) {
  163.                    
  164.                     blob = rs.getBlob(1);
  165.                     isFile = blob.getBinaryStream();
  166.                    
  167.                     fileName = rs.getString(2);
  168.                     wasQuery = true;
  169.                 }
  170.                 rs.close();
  171.             }
  172.         }
  173.         if (!wasQuery) {
  174.             throw new RuntimeException("Строка с sync_id=" + Long.toString(_blobId) + " не найдена.");
  175.         }
  176.         //return fileName;
  177.     }
  178.    
  179.     public static void copyStream(InputStream input, OutputStream output)
  180.         throws IOException
  181.         {
  182.             byte[] buffer = new byte[1024]; // Adjust if you want
  183.             int bytesRead;
  184.             while ((bytesRead = input.read(buffer)) != -1)
  185.             {
  186.                 output.write(buffer, 0, bytesRead);
  187.             }
  188.         }
  189.    
  190.     public static void copyReverseStream(InputStream input, OutputStream output, int size)
  191.         throws IOException
  192.         {
  193.             byte[] buffer = new byte[1024]; // Adjust if you want
  194.             int bytesRead;
  195.             int i=0;
  196.             while ((bytesRead = input.read(buffer)) != -1)
  197.             {
  198.                 output.write(buffer, size-i, bytesRead);
  199.                 i++;
  200.             }
  201.         }
  202.     public void toDataBase(String name, InputStream is) throws SQLException, IOException {
  203.         try {
  204.             String Query;
  205.            
  206.             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  207.             copyStream(is,baos);
  208.            
  209.             //copyReverseStream(is,baos,700);
  210.             size=baos.size();
  211.             System.out.print("Размер файла:");
  212.             System.out.println(size);
  213.          
  214.             ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
  215.            
  216.             Query = "declare ";
  217.             Query+= "nSYNC_NEW number; ";
  218.             Query+= "begin ";
  219.             Query+= "nSYNC_NEW:=seq_id.nextval ; ";
  220.             Query+= "  insert into audio (sync_id, file_name, blob_data, mime_type) "
  221.                                         + "values(nSYNC_NEW, ?, ?, 'audio/aiff'); ";
  222.             Query+= "  ? := nSYNC_NEW; ";
  223.             Query+= " end;";
  224.        
  225.             CallableStatement cs = conn.prepareCall(Query);
  226.             name="'shit_"+name+"'";
  227.             cs.setString(1, name);
  228.             cs.setBlob(2,bais,size);
  229.             cs.registerOutParameter(3, java.sql.Types.NUMERIC);
  230.      
  231.             cs.executeUpdate();
  232.      
  233.             long nSYNC_NEW = cs.getLong(3);
  234.             System.out.print("ID обработанной композиции:");
  235.             System.out.println(nSYNC_NEW);
  236.             retNum = nSYNC_NEW;
  237.             cs.close();
  238.         }
  239.         catch (Exception e)
  240.         {
  241.             e.printStackTrace();
  242.         }
  243.         finally {
  244.             conn.close();
  245.         }
  246.   }
  247.    
  248. }
  249.  
  250. /*
  251.  * To change this license header, choose License Headers in Project Properties.
  252.  * To change this template file, choose Tools | Templates
  253.  * and open the template in the editor.
  254.  */
  255. package ru.bmstu;
  256.  
  257. import java.io.ByteArrayInputStream;
  258. import java.io.InputStream;
  259. import javax.jws.WebService;
  260. import javax.jws.WebMethod;
  261. import javax.jws.WebParam;
  262. import java.lang.*;
  263. import java.nio.ByteBuffer;
  264. import org.apache.commons.io.IOUtils;
  265. import ru.bmstu.Filter;
  266. import javax.sound.sampled.AudioFormat;
  267. import javax.sound.sampled.AudioInputStream;
  268. import javax.sound.sampled.AudioSystem;
  269. import javax.sound.sampled.DataLine;
  270. import javax.sound.sampled.LineUnavailableException;
  271. import javax.sound.sampled.SourceDataLine;
  272. /**
  273.  *
  274.  * @author Dell
  275.  */
  276. @WebService(serviceName = "NewWebService")
  277. public class NewWebService {
  278.     public final int BUFFER_SIZE = 131072;
  279.     byte [] buff;
  280.     short [] sampleBuff;
  281.     /**
  282.      * This is a sample web service operation
  283.      */
  284.     @WebMethod(operationName = "hello")
  285.     public long hello(@WebParam(name = "songID") int songID,
  286.                         @WebParam(name = "methNum") int methNum) {
  287.        
  288.         AnFilter fil = new AnFilter(songID);
  289.    
  290.     try{
  291.         System.out.println("Устанавливаем соединение...");
  292.         fil.initConnection();
  293.         System.out.println("Выгружаем данные...");
  294.         fil.initFile();
  295.         System.out.print("Название композиции:");
  296.         System.out.println(fil.getFileName());
  297.         if (methNum==1)
  298.         {  
  299.             System.out.println("Добавляем эффект...");
  300.             SimpleSoundPlayer sound = new SimpleSoundPlayer(fil.getIsFile());
  301.             InputStream is = new ByteArrayInputStream(sound.getSamples());
  302.             EchoFilter filter = new EchoFilter(11025, .01f);
  303.             is = new FilteredSoundStream(is, filter);
  304.             //sound.play(is);
  305.             /*try     {
  306.                AudioInputStream audioStream = AudioSystem.getAudioInputStream(fil.getIsFile());
  307.                AudioFormat audioFormat = audioStream.getFormat();
  308.              
  309.                DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
  310.                
  311.                SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(info);
  312.                sourceLine.open(audioFormat);
  313.                
  314.                sourceLine.start();
  315.                int nBytesRead = 0;
  316.                
  317.                buff = new byte[BUFFER_SIZE];
  318.                sampleBuff = new short[BUFFER_SIZE>>>1];
  319.                System.out.println(BUFFER_SIZE>>>1);
  320.                Equalizer eq = new Equalizer(BUFFER_SIZE>>>1);
  321.                while (nBytesRead != -1) {
  322.                    
  323.                     nBytesRead = audioStream.read(buff, 0, buff.length);
  324.                     //System.out.println(nBytesRead);
  325.                     sampleBuff = new short[nBytesRead/2];
  326.                     this.ByteArrayToSamplesArray();
  327.                     eq.setInputSignal(sampleBuff);
  328.                     eq.equalization();
  329.                     this.SampleArrayByteArray();
  330.                    
  331.                     if (nBytesRead >= 0) {
  332.                         @SuppressWarnings("unused")
  333.                         int nBytesWritten = sourceLine.write(buff, 0, nBytesRead);
  334.                     }
  335.                    
  336.                 }
  337.                     sourceLine.drain();
  338.                     sourceLine.close();
  339.          
  340.             } catch (Exception e) {
  341.                 e.printStackTrace();
  342.                 System.exit(1);
  343.             }*/
  344.            
  345.             System.out.println("Загружаем обработанные данные...");
  346.             fil.toDataBase(fil.getFileName(),fil.getIsFile());
  347.         }
  348.         else
  349.         {
  350.             System.out.println("Загружаем обработанные данные...");
  351.             fil.toDataBase(fil.getFileName(),fil.getIsFile());
  352.         }
  353.    
  354.         System.out.println("Закрываем соединение...");
  355.         fil.getConnection().close();    
  356.         }
  357.         catch(Exception ex){
  358.             ex.printStackTrace();
  359.         }
  360.          
  361.         return fil.getRetNum();
  362.     }
  363.  
  364.     private void SampleArrayByteArray() {
  365.     for(int i = 0, j = 0; i < this.sampleBuff.length && j < (this.buff.length); i++, j += 2 ) {
  366.             this.buff[j] = (byte)(this.sampleBuff[i]);
  367.             this.buff[j + 1] = (byte)(this.sampleBuff[i] >>> 8);
  368.            
  369.     }
  370.     }
  371.     private void ByteArrayToSamplesArray() {
  372.         if (buff.length < BUFFER_SIZE) return;
  373.     for(int i = 0, j = 0; i < this.buff.length - 2; i += 2 , j++) {
  374.             this.sampleBuff[j] = (short) (0.5 *  (ByteBuffer.wrap(this.buff, i, 2).order(
  375.                     java.nio.ByteOrder.LITTLE_ENDIAN).getShort()));
  376.         }
  377.     }
  378. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement